API Reference

Lint Rules

class tukuroi.Rule(source, imports)

A lint rule. MESSAGE is the message of a report that gives none; the name of the rule is the name of its class, without a “Rule” at its end.

Parameters:
classmethod name()

The name of the rule: the name of its class, without “Rule” at its end.

Return type:

str

report(node, message=None, *, replacement=None, edits=(), span=None, unused_imports=())

Report a violation at node, with message or MESSAGE. The fix, if any, is replacement for the text of node, or edits.

span is where the report is, when it is not the span of node: for what the tree has no node for, such as an operator (#143). The comments that suppress the report are still those of node.

unused_imports are the qualified names (such as "typing.NamedTuple") that the fix may leave unused: after the fixes, the engine takes out their imports that no code reads any more (#141).

Parameters:
Return type:

None

INVALID: ClassVar[Sequence[Invalid | str]] = ()
MESSAGE: ClassVar[str] = ''
VALID: ClassVar[Sequence[Valid | str]] = ()
class tukuroi.Valid(code)

Code that the rule does not report.

Parameters:

code (str)

code: str
class tukuroi.Invalid(code, expected_message=None, expected_replacement=None, position=None)

Code that the rule reports. When given, the message, the code after the fix, and the position of the report are checked too.

Parameters:
  • code (str)

  • expected_message (str | None)

  • expected_replacement (str | None)

  • position (Position | None)

code: str
expected_message: str | None
expected_replacement: str | None
position: Position | None
class tukuroi.Edit(span, text)

Replace span with text. An empty span inserts at its place.

Parameters:
span: Span
text: str
class tukuroi.Position(line, column)

A line, counted from 1, and a column in characters, counted from 0.

Parameters:
column: int
line: int
class tukuroi.Span(start, end)

The offsets [start, end) into a text. An empty span (start == end) is the place to insert at.

Parameters:
end: int
start: int
class tukuroi.Range(start, end)

From start to end: the positions of a span, to show it.

Parameters:
end: Position
start: Position
class tukuroi.Source(path, text, encoding, bom, tree, lines, tokens, comments)

A file read and parsed, with what the rules and the engine need of it.

encoding is the name that tokenize.detect_encoding gives (such as "utf-8" or "iso-8859-1"), or None when the source was made from text. bom is whether the text started with a BOM, which text does not have.

Parameters:
span(node)

The span of node, a node of tree. A Module spans the whole text; another node without a position raises TypeError.

Parameters:

node (AST)

Return type:

Span

tokens_in(span)

The tokens whose spans are in span, in their order (#144).

Parameters:

span (Span)

Return type:

tuple[Token, …]

comments: tuple[Comment, ...]
path: Path | None
text: str
tokens: tuple[Token, ...]
tree: Module
class tukuroi.Token(type, string, span, start, end)

A token of tokenize: its type (such as tokenize.NAME), its string, its span, and the positions of the start and the end of the span (#144). The end of a token past the end of its line, as tokenize gives the line end tokens, is the start of the next line: a span is always in the text.

Parameters:
end: Position
span: Span
start: Position
string: str
type: int
class tukuroi.Comment(span, text)

A comment: its span, and its text from # to the end of the line.

Parameters:
span: Span
text: str
class tukuroi.ImportTable(bindings, _resolved=mappingproxy({}))

The qualified names that the imports of a module bind: bindings, those of the module scope, and the name of each node of the tree, by its scope.

Parameters:
qualified_names(node)

The qualified names of node: a name, or attributes of a name. Any other node, and a name that no import binds in its scope, has none. A name that is not a node of the tree, such as one made by a rule, is taken as a name of the module scope.

Parameters:

node (expr)

Return type:

frozenset[str]

Plugins

class tukuroi.FormatterPlugin(*args, **kwargs)

A formatter of the files that tukuroi fixes (#169): a class registered in the entry points tukuroi.formatters, by the name that formatter of a config gives. tukuroi makes one with no argument.

available()

Why the formatter cannot run, such as a missing package, or None.

Return type:

str | None

format(text, path)

text, the fixed text of the file at path, formatted.

Parameters:
Return type:

str

class tukuroi.OutputFormatPlugin(config)

An output format: a class registered in the entry points tukuroi.output_formats. tukuroi makes one for a run, with the config of the run (such as its output_template), and prints what it gives: at the start, for each result, and at the end. None prints nothing.

A format for programs to read, such as one JSON document, sets the class attribute MACHINE_READABLE = True (#178). tukuroi then prints on the standard output what the format gives, without colors, and nothing else: an error with its traceback, the diff of a fix, the metrics and the prompt of fix go to the standard error, and fix -, whose standard output is the fixed source, is a usage error. Without the attribute, the format is for people to read.

Parameters:

config (Config)

end()

What to print after the results, such as the end of a document.

Return type:

str | None

result(result)

What to print for result: a violation, an error, or a clean file.

Parameters:

result (Result)

Return type:

str | None

start()

What to print before the results, such as the start of a document.

Return type:

str | None

Frontends

Simple API

tukuroi.tukuroi_paths(paths, *, autofix=False, options=None, parallel=True, metrics_hook=None)

Lint multiple files or directories, recursively expanding each path.

Walks all paths given, obeying any .gitignore exclusions, finding Python source files. Lints each file found using tukuroi_file(), using a process pool when more than one file is being linted.

Yields Result objects for each path, lint error, or exception found. See tukuroi_bytes() for semantics.

If the first given path is STDIN (Path("-")), then content will be linted from STDIN using tukuroi_stdin(). The fixed content will be written to STDOUT. A second path argument may be given, which represents the original content’s true path name, and will be used: - to resolve the tukuroi.toml configuration file(s) - when printing status messages, diffs, or errors. If no second path argument is given, it will default to “stdin” in the current working directory. Any further path names will result in a runtime error. A STDIN after another path is skipped with a warning. The CLI refuses both, as usage errors (#40).

Fixes can be sent back to the generator, as with tukuroi_bytes(), with parallel=False only: in a process pool, sending True raises a ValueError (#179).

A path that does not exist raises a FileNotFoundError before the first result. A file given by name is linted though .gitignore has it, and a file given twice, by name or in a directory, is linted once (#40).

Note

Currently does not support applying individual fixes when parallel=True, due to limitations in the multiprocessing method in use. Setting parallel=False will enable interactive fixes. Setting autofix=True will always apply fixes automatically during linting.

When a rule ends the process that lints a file (os._exit, a crash, a kill), that file gets an error, and the other files their results (#94).

Before the first result, the config of the directory of each file is read (check()): a config that tukuroi cannot use raises a ConfigError, and no file is linted (#40). A file linted alone (tukuroi_file()) gets such an error as its result.

Parameters:
Return type:

Generator[Result, bool]

tukuroi.tukuroi_file(path, *, autofix=False, options=None, metrics_hook=None)

Lint a single file on disk, detecting and generating appropriate configuration.

Generates a merged Configuration based on all applicable config files. Reads file from disk as raw bytes, and uses tukuroi_bytes() to lint and apply any fixes to the content. Writes content back to disk if changes are detected.

Yields Result objects for each lint error or exception found, or a single empty result if the file is clean. See tukuroi_bytes() for semantics.

Parameters:
Return type:

Generator[Result, bool]

tukuroi.print_result(result, *, show_diff=False, stderr=False, output=None)

Print result: what output, an output format plugin (#169), gives for it (by default, that of tukuroi), and an exception with its traceback. With a format for programs to read (MACHINE_READABLE), what it gives is printed without colors, and the rest on stderr (#178).

Setting show_diff=True will output autofixes or suggested changes in unified diff format, using ANSI colors when possible.

Returns True if the result is “dirty” - either a lint error or exception.

Parameters:
Return type:

int

class tukuroi.Violation(rule_name, range, message, autofixable, diff='')

A violation that a rule reports: the rule, where it is (lines from 1, columns in characters from 0), the message, whether tukuroi can fix it, and the diff of its fix alone.

Parameters:
autofixable: bool
diff: str
message: str
range: Range
rule_name: str
class tukuroi.Result(path, violation, error=None, applied=0, remaining=0)

A single lint result for a given file and lint rule. A file whose fixes were applied ends with a result that has only applied: how many, and remaining: the violations left in the file after them.

Parameters:
applied: int = 0
error: Error | None = None
path: Path
remaining: int = 0
violation: Violation | None
class tukuroi.Error(type, message, traceback='', position=None)

An exception that stopped tukuroi on a file, in strings alone: the name of its type and its message, as traceback writes them, and the traceback (empty for a syntax error in the file). The process pool of lint sends it back whatever the exception was, even one that a rule of the repo defines (#64). A syntax error has its position too, which the LSP shows the error at (#96).

Parameters:
message: str
position: Position | None
traceback: str
type: str

Advanced API

tukuroi.FileContent

alias of bytes

tukuroi.tukuroi_bytes(path, content, *, config, autofix=False, metrics_hook=None)

Lint raw bytes content representing a single path, using the given configuration.

Yields Result objects for each lint error or exception found, or a single empty result if the file is clean. A file is considered clean if no lint errors or no rules are enabled for the given path. Returns the final FileContent including any fixes applied.

Use capture() to more easily capture return value after iterating through violations. Use generator.send(...) with a boolean value to apply individual fixes for each violation.

If autofix is True, all violations with replacements will be applied automatically, even if False is sent back to the generator. After the violations of a file whose fixes were applied, a last Result tells how many were (applied), and how many violations are left in the fixed text (remaining): fix exits with 1 if any are (#40).

It runs the new engine (#21). The fixes that autofix takes are applied round after round; those sent back to the generator, in one round. The fixed text is formatted with ruff format when the config chooses it (#108).

A rule of config that cannot be loaded is the error of the file, without a traceback, and no rule runs (#40).

Parameters:
Return type:

Generator[Result, bool, bytes | None]

class tukuroi.util.capture(generator)

Wrap a generator, and capture it’s final return value in the result property.

Allows sending values back to the generator using the respond() method.

Example usage:

generator = capture( tukuroi_bytes(...) )
for result in generator:  # Result
    ...
    generator.respond(...)  # optional

result = generator.result  # FileContent
Parameters:

generator (Generator)

respond(answer)

Send a value back to the generator in the next iteration.

Can be called while iterating on the wrapped generator object.

Parameters:

answer (Send)

Return type:

None

property result: Return

Contains the final return value from the wrapped generator, if any.

class tukuroi.Config(path=<factory>, root=<factory>, enable_root_import=False, custom_rules=True, enable=<factory>, disable=<factory>, formatter='none', output_format='tukuroi', output_template='')

Materialized configuration valid for processing a single file.

Parameters:
custom_rules: bool = True
disable: list[QualifiedRule]
enable: list[QualifiedRule]
enable_root_import: bool | Path = False
formatter: str = 'none'
output_format: str = 'tukuroi'
output_template: str = ''
path: Path
root: Path
class tukuroi.Options(debug=None, config_file=None, rules=(), output_format=None, output_template='', print_metrics=False, custom_rules=True)

Command-line options to affect runtime behavior

Parameters:
config_file: Path | None = None
custom_rules: bool = True
debug: bool | None = None
output_format: str | None = None
output_template: str = ''
print_metrics: bool = False
rules: Sequence[QualifiedRule] = ()
class tukuroi.QualifiedRule(module: str, name: str | None = None, local: str | None = None, root: pathlib.Path | None = None)
Parameters:
  • module (str)

  • name (str | None)

  • local (str | None)

  • root (Path | None)

property builtin: bool

Whether this names rules that come with tukuroi, not custom rules. The module of a local rule starts with “.”, so it never matches.

local: str | None = None
module: str
name: str | None = None
root: Path | None = None