User Guide

Quick Start

Setup

Install tukuroi from PyPI:

$ pip install tukuroi

By default, tukuroi enables all of the lint rules that ship with tukuroi, all of which are part of the tukuroi.rules package.

If you want to customize the list of enabled rules, either to add new rules or disable others, see the Configuration Guide for details and options available.

tukuroi offers multiple integrations, including pre-commit actions and LSP support for VSCode and other editors. See the Integrations Guide for details.

Usage

See lints and suggested changes for a set of source files:

$ tukuroi lint <path>

Apply suggested changes on those same files automatically:

$ tukuroi fix <path>

If given directories, tukuroi will automatically recurse them, finding any files with the .py or .pyi extension, while obeying the .gitignore at the root of your repo.

See the Command Reference for more details.

Example

Given the following code:

# foo_test.py

import unittest


class FooTest(unittest.TestCase):
    def test_bar(self) -> None:
        self.assertTrue(value in values)
        if True:
            self.assertTrue(value, None)

When running tukuroi, we see three separate lint errors:

$ tukuroi lint foo_test.py
foo_test.py@8:8 UseAssertIn: Use assertIn/assertNotIn instead of assertTrue/assertFalse for inclusion check.
See https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn) (has autofix)
foo_test.py@9:8 NoStaticIfCondition: Your if condition appears to evaluate to a static value (e.g. `or True`, `and False`). Please double check this logic and if it is actually temporary debug code.
foo_test.py@10:12 NoAssertTrueForComparisons: "assertTrue" does not compare its arguments, use "assertEqual" or other appropriate functions. (has autofix)
🛠️  1 file checked, 1 file with errors, 2 auto-fixes available 🛠️

We can also see any suggested changes by passing --diff:

$ tukuroi lint --diff foo_test.py
foo_test.py@8:8 UseAssertIn: Use assertIn/assertNotIn instead of assertTrue/assertFalse for inclusion check.
See https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn) (has autofix)
--- a/foo_test.py
+++ b/foo_test.py
@@ -7,3 +7,3 @@
     def test_bar(self) -> None:
-        self.assertTrue(value in values)
+        self.assertIn(value, values)
         if True:
...

tukuroi checks the rules that come with it (see Built-in Rules); ruff covers the others that Fixit had (see Rules Replaced by ruff). To write rules of your own, see Writing Rules.

Silencing Errors

For lint rules without autofixes, it may still be useful to silence individual errors. A simple # lint-ignore or # lint-fixme comment, either as a trailing inline comment, or as a dedicated comment line above the code that triggered the lint rule:

self.assertTrue(a in b)  # lint-fixme: UseAssertIn

# lint-ignore: UseAssertIn
self.assertTrue(c in d)

By providing one or more lint rule, separated by commas, tukuroi can still report issues triggered by other lint rules that haven’t been listed in the comment, but this is not required. The names follow a :, and must have the same case as the names of the rules, with or without Rule at the end. A directive that does not fit this form silences nothing, and tukuroi warns about it (invalid lint-ignore directive). A comment can hold other tools’ directives too: # noqa  # lint-ignore: UseAssertIn.

If no rule name is listed, tukuroi will silence all rules when reported on code associated with that comment:

self.assertTrue(a in b)  # lint-ignore

“ignore” vs “fixme”

Both comment directives achieve the same result — silencing errors for a particular statement of code. The semantics of using either term is left to the user, though they are intended to be used with the following meanings:

  • # lint-fixme for errors that need to be corrected or reviewed at a later date, but where the lint rule should be silenced temporarily for the sake of CI or similar external circumstances.

  • # lint-ignore for errors that are false-positives (please report issues if this occurs with built-in lint rules) or the code is otherwise intentionally written or structured in a way that the lint error cannot be avoided.

Future versions of tukuroi may offer reporting or similar tools that treat “fixme” directives differently from “ignore” directives.

Commands

$ tukuroi [OPTIONS] COMMAND ...

The following options are available for all commands:

--debug / --quiet

Raise or lower the level of output and logging.

--config-file PATH

Override the normal hierarchical configuration and use the configuration from the specified path, ignoring all other configuration files entirely. Its enable and disable apply to every file, wherever it is. The paths of its [[tool.tukuroi.overrides]], and its local rules, are relative to the directory of the configuration file, as in any other.

--custom-rules / --no-custom-rules

Load custom rules, or turn them off. Custom rules are the rules that do not come with tukuroi (anything but tukuroi.rules), such as local rules in the repo. tukuroi loads them by default. See Security for when to turn them off, and what tukuroi does then.

The environment variable TUKUROI_CUSTOM_RULES sets the default, and the option wins over it. tukuroi reads the variable as Click reads a boolean, ignoring letter case:

  • 1, true, t, yes, y, on: load custom rules.

  • 0, false, f, no, n, off: turn them off.

  • Unset or empty: the default, load them.

  • Any other value is a usage error.

No standard defines how to write a boolean in an environment variable, so these are the values that Click accepts.

--output-format / -o FORMAT_TYPE

Override how tukuroi prints violations to the terminal.

See output-format for available formats.

--output-template TEMPLATE

Override the python formatting template to use with output-format = 'custom'. The same variables as in output-template are allowed, and nothing else: an invalid template is a usage error.

Any command exits with 2 on a usage error, and on a configuration that tukuroi cannot use: a file that is not TOML, or an invalid value. The error goes to stderr, without a traceback. lint and fix read the configurations of the current directory and of the directory of each file to lint, or the one given with --config-file, and load the rules that they name, before they lint any file, and stop at the first error. A rule of --rules that cannot be loaded is a usage error. No standard defines exit codes other than 0 and nonzero: 2 is the code of Click and Ruff for these.

lint

Lint one or more paths, and print a list of lint errors. If “-” is given as the first path, then the second given path will be used for configuration lookup and error messages, and the input read from STDIN. No other path may follow, and “-” after another path is a usage error.

A path that does not exist is a usage error, before any file is linted. A directory is walked for Python files (.py and .pyi), by name, without those that the .gitignore at the root of the project has, as git reads it: the root is the nearest directory with pyproject.toml, .git or .hg, from the directory up. The .gitignore files of the directories under the root are not read. A symbolic link to a file is a file, and one to a directory is not walked, as git keeps the link. A file given by name is linted, though .gitignore has it. A file given twice, by name or in a directory, is linted once.

$ tukuroi lint [--diff] [PATH ...]
--diff / -d

Show suggested fixes, in unified diff format, when available. The diff names the file as the lint error does: relative to the current directory, or absolute outside it.

The exit code is 0 when no file has a lint error, 1 when a file has one, and 2 when tukuroi could not lint a file (a syntax error, an exception in a rule, or a configuration of the file that tukuroi cannot use); 3 for both.

fix

Lint one or more paths, and apply suggested fixes. If “-” is given as the first path, then the second given path will be used for configuration lookup, the input read from STDIN, and the fixed output printed to STDOUT (ignoring --interactive); the lint errors, the diffs of --diff, and the metrics of --print-metrics, go to STDERR. As with lint, no other path may follow, and the paths are found the same way. With an output format for programs to read, such as json, “-” is a usage error: that format prints on STDOUT too (see Output for programs).

$ tukuroi fix [--interactive | --automatic [--diff]] [PATH ...]
--interactive / -i

Interactively prompt the user to apply or decline suggested fixes for each auto-fix available. default

--automatic / -a

Automatically apply suggested fixes for all lint errors when available.

--diff / -d

Show applied fixes in unified diff format when applied automatically.

The exit code is that of lint, for the lint errors left after the fixes, as with ruff check --fix: 1 only when a file still has one, because it has no fix, or its fix was declined or could not be applied.

lsp

Start the language server providing IDE features over LSP. This command is only available if installed with the lsp extras (e.g. pip install "tukuroi[lsp]"). See IDE Integrations for more details.

$ tukuroi lsp [--stdio] [--debounce-interval SECONDS]

The server talks over stdio only, with the editor that starts it. As LSP asks, the exit code is 0 when the client asked the server to shut down before it exits, and 1 otherwise.

--stdio

Serve LSP over stdio, as without it. Some clients pass it.

--debounce-interval

Delay in seconds for server-side debounce. default: 0.5

test

Test one or more lint rules using their VALID and INVALID test cases.

Expects qualified lint rule packages or names, with the same form as when configuring enable and disable.

$ tukuroi test [RULES ...]

Example:

$ tukuroi test .rules
test_INVALID_0 (tukuroi.testing.HollywoodName.test_INVALID_0) ... ok
test_INVALID_1 (tukuroi.testing.HollywoodName.test_INVALID_1) ... ok
test_VALID_0 (tukuroi.testing.HollywoodName.test_VALID_0) ... ok
test_VALID_1 (tukuroi.testing.HollywoodName.test_VALID_1) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.024s

OK

debug

Debug options for validating tukuroi configuration.

$ tukuroi debug [PATH ...]

validate-config

Check a configuration file, alone and as a root configuration, without linting any file.

$ tukuroi validate-config PATH

tukuroi reads the file as lint does, and stops at the first value that it cannot use. Then it loads every rule that the file names, in enable, disable and all the [[tool.tukuroi.overrides]], with its enable-root-import, and reports each one that cannot be loaded. A file without [tool.tukuroi] has nothing to check. As the file is checked alone, an enable-root-import that is only wrong under a parent configuration is not found: lint finds it.

Each error goes to stderr, in the form of lint:

$ tukuroi validate-config pyproject.toml
Error: pyproject.toml: enable: could not find rule tukuroi.rules:Nope

The exit code is 0 when the file is valid, and 2 when it is not, as for any configuration that tukuroi cannot use. With custom rules turned off (--no-custom-rules), only the names of custom rules are checked, with a warning that they are skipped; see Security.

Configuration

tukuroi uses TOML format for configuration, and supports hierarchical, cascading configuration. tukuroi will read values from both the standardized pyproject.toml file as well as a separate .tukuroi.toml or tukuroi.toml file, with values from the latter taking precendence over the former, and values from files “nearer” to those being linted taking precedence over values from files “further” away.

When determining the configuration to use for a given path, tukuroi will continue looking upward in the filesystem until it reaches either the root of the repository, or a configuration file is found with root set to True. tukuroi will then read configuration values from each file, from further to nearest, and merge or override values as appropriate. For enable and disable, the nearer wins: see Which rules run.

The root of the repository is the nearest directory with .git (a directory, or a file in a worktree or a submodule) or .hg. Outside a repository, tukuroi looks up to the current directory if the path is in it, or else only in the directory of the path. A configuration file above that is not read: pass it with --config-file to use it.

This behavior enables a monorepo to provide a baseline configuration, while individual projects can choose to either add to that baseline, or define their own root of configuration to ignore any other baseline configs. This also allows the inclusion of external or third-party projects to maintain consistent linting results, regardless of whether they are being linted externally or within the containing monorepo.

[tool.tukuroi]

The main configuration table. In tukuroi.toml and .tukuroi.toml too, the keys go under [tool.tukuroi]: a key or a table outside it is a configuration error there. In pyproject.toml, the keys of other tools are left alone.

A key other than the ones below, a value of a type other than the one given below, or a rule name that is not valid, is a configuration error. tukuroi checks the whole file as it reads it, and stops at the first error. The settings of Fixit that tukuroi does not support (python-version, options, tags) are errors that say so.

root: bool = false

Marks this file as a root of the configuration hierarchy.

If set to true, tukuroi will not visit any configuration files further up the filesystem hierarchy. tukuroi does not look above the root of the repository in any case.

enable: list[str] = []

List of modules or individual rules to enable when linting files covered by this configuration.

Rules bundled with tukuroi, or available in the environment’s site-packages, can be referenced as a group by their fully-qualified package name, or individually by adding a colon and the rule name:

[tool.tukuroi]
enable = [
    "tukuroi.rules",  # all lint rules in this package (non-recursive)
    "tukuroi.rules:UseAssertIn",  # single lint rule by name
]

Local rules, available only in the repo being linted, can be referenced by their locally-qualified package names, as if they were being imported from a Python module relative to the configuration file specifying the rule:

# teambread/tukuroi.toml
[tool.tukuroi]
enable = [
    ".rules",  # all rules in teambread/rules/ (non-recursive)
    ".rules.hollywood",  # all rules in teambread/rules/hollywood.py
    ".rules:HollywoodName",  # single lint rule by name
]

Wins over disable further up the hierarchy, for the rules that it names. See Which rules run.

tukuroi will enable the built-in tukuroi.rules lint rules by default. The stricter rules of tukuroi.rules.strict come with tukuroi too, and run only when named:

[tool.tukuroi]
enable = [
    "tukuroi.rules",
    "tukuroi.rules.strict:NoValueObjectDefault",
]

tukuroi imports the rules that are enabled, which runs their code. See Security for the configurations to trust, and for turning off the rules that do not come with tukuroi.

A name whose rules cannot be loaded is a configuration error, in disable too: the module cannot be imported, its code raises an exception, it has no rules, or the rule is not in it. With --rules, the names in the configuration are not used, and not loaded.

disable: list[str] = []

List of modules or individual rules to disable when linting files covered by this configuration.

Wins over enable further up the hierarchy, for the rules that it names, and over enable in the same table for a name as specific or less. See Which rules run.

See enable for details on referencing lint rules.

enable-root-import

Allow importing local rules using absolute imports, relative to the root of the project. This provides an alternative to using dotted rule names for enabling and importing local rules (see enable) from either the directory containing the root config (when set to true), or a single, optional path relative to the root config.

For example, project orange using a src/orange/ project hierarchy could use the following config:

[tool.tukuroi]
root = true
enable-root-import = "src"
enable = ["orange.rules"]

Assuming that the namespace orange is not already in site-packages, then orange.rules would be imported from src/orange/rules/, while also allowing these local rules to import from other components in the orange namespace.

This option may only be specified in the root config file. Specifying the option in any other config file is treated as a configuration error. Absolute paths, or paths containing .. parent-relative components, are not allowed. Any value other than true, false, or a relative path that is not empty is a configuration error.

This option is roughly equivalent to adding the configured path, relative to the root configuration, to sys.path when attempting to import and materialize any enabled lint rules.

With custom rules turned off (see Security), this option is ignored.

formatter: str

What formats a file after tukuroi fix (or the LSP server) fixed it:

  • none: nothing, the default. Only the ranges that the fixes replace change. An import that a fix adds goes on a new line after the last import, and is not sorted.

  • ruff: ruff sorts the imports, as its isort rule (I001) fixes them, then ruff format formats the file, both with the settings of ruff for the file. An import that a fix adds goes to its place. It needs the optional ruff package: pip install "tukuroi[ruff]". Without it, formatter = "ruff" is a configuration error.

  • The name of a formatter plugin of another package (see Plugins). It runs code of that package: with custom rules turned off, it is not loaded, and tukuroi warns.

The nearest configuration or override that sets it wins: a subdirectory can turn formatting off with formatter = "none". A name that no plugin has, or a plugin that cannot run, is a configuration error. The formatters of Fixit (black, ufmt) are not built in.

[tool.tukuroi]
formatter = "ruff"
output-format

Choose one of the presets for terminal output formatting. This option is inferred based on the current working directory or from an explicity specified config file – subpath overrides will be ignored.

Can be one of, in any letter case as with --output-format:

  • custom: Specify your own format using the output-template option below.

  • tukuroi: the default output format.

  • json: one JSON document of the results, for programs to read (see Output for programs).

  • sarif: a log of SARIF 2.1.0, which GitHub code scanning reads (see Output for programs).

  • vscode: A format that provides clickable paths for Visual Studio Code.

  • The name of an output format that another package registers (see Plugins).

output-template

Sets the format of output printed to terminal. It is a Python format string (str.format()) with the names of the variables below only. A field with an attribute or an index ({path.parent}, {path[0]}), an unknown name, or no name ({}) is a configuration error, as is a format spec that the value does not take ({path:d}); format specs and conversions ({path:<40}, {message!r}) are fine. The template is checked even when output-format is not custom. Only active with output-format set to custom.

This option is inferred based on the current working directory or from an explicity specified config file – subpath overrides will be ignored.

Supported variables:

  • message: Message emitted by the applied rule (a string).

  • path: Path to affected file, as tukuroi shows it (a string).

  • rule_name: Name of the applied rule (a string).

  • start_col: Start column of affected code (a number, from 0).

  • start_line: Start line of affected code (a number, from 1).

  • end_col: End column of affected code (a number, from 0).

  • end_line: End line of affected code (a number, from 1).

[[tool.tukuroi.overrides]]

Overrides provide a mechanism for hierarchical configuration within a single configuration file. They are defined as an array of tables, with each table defining the subpath it applies to, along with enable, disable and formatter for it. No other key is allowed in an override:

[[tool.tukuroi.overrides]]
path = "foo/bar"
disable = ["tukuroi.rules:ExampleRule"]

[[tool.tukuroi.overrides]]
path = "fizz/buzz"
enable = ["plugin:SomethingNeat"]

Each table needs path, a string that is not empty. tukuroi checks every table, whether or not it applies to the file being linted.

An override applies to the files under its path, relative to the directory of the configuration file. It wins over the top level of the file, and a deeper path wins over a shallower one, wherever they are in the file: see Which rules run.

Which rules run

The enable and disable of a file come in levels, from the farthest to the nearest: the root configuration, then each configuration nearer to the file. Within a configuration, the top level comes first, then the [[tool.tukuroi.overrides]] that apply to the file, the shallowest path first, and in the order of the file for the same path. With --config-file, that configuration is the only one, and its top level applies to every file, wherever it is.

A nearer level wins. The rules that a level enables are enabled, though a level further up disables them, and the other way round:

# pyproject.toml
[tool.tukuroi]
root = true
enable = ["tukuroi.rules:UseAssertIn"]

# tests/tukuroi.toml
[tool.tukuroi]
disable = ["tukuroi.rules"]  # UseAssertIn too, in tests/

A module names its own rules, and if it is a package, those of the modules in it: one level down, not those of its packages. module:Rule names one rule. tukuroi tells the rules that a name gives by the names alone. A package such as tukuroi.rules names the rules of its modules as its own, so tukuroi.rules.use_assert_in and tukuroi.rules:UseAssertIn do not name the same rule for it: name a rule the same way at every level.

Within one level, the more specific name wins: a rule over a module, and a module over the package that it is in. For two names as specific, such as one name in both enable and disable, the rule is disabled:

[tool.tukuroi]
disable = ["tukuroi.rules"]
enable = ["tukuroi.rules:UseAssertIn"]  # UseAssertIn only

Security

Configuration files can run code. tukuroi imports the rules that a configuration enables, which runs their code with the permissions of the user running tukuroi. That includes custom rules: local rules in the repo (see enable), the modules found through enable-root-import, and rules from any package other than tukuroi. Before it lints any file, tukuroi imports every rule that the configurations name: in disable and in all the [[tool.tukuroi.overrides]] too, whether or not they apply to a file. The rules checked by tukuroi validate-config are imported too.

tukuroi looks for configuration files from each linted file up to the root of the repository, or outside one, up to the current directory. A configuration file in a parent directory of the repo, which someone else may have written, is not read.

Only run tukuroi with custom rules on code whose configuration you trust. For other code, turn custom rules off with --no-custom-rules, or with the environment variable TUKUROI_CUSTOM_RULES=0 (see Commands). Then tukuroi imports only the built-in rules, in tukuroi.rules:

  • Custom rules in enable are skipped with a warning. The built-in rules still run, and the exit code does not change.

  • Custom rules in disable, and enable-root-import, are ignored.

  • tukuroi validate-config checks only the names of custom rules, and warns that it skipped them.

  • A custom rule named with --rules, or given to tukuroi test, is a usage error.

Turn custom rules off when tukuroi runs on code that others can change, such as:

  • CI jobs that lint pull requests from forks,

  • repositories that you clone to review or investigate,

  • editors that start tukuroi lsp in any folder that you open.

For example, in a CI job:

$ TUKUROI_CUSTOM_RULES=0 tukuroi lint src/

To keep custom rules off by default, set TUKUROI_CUSTOM_RULES=0 in your shell, and pass --custom-rules in the repos that you trust. The option on the command line wins over the variable. So the variable does not keep custom rules off when the repo can change the command line, for example with the args of a hook in .pre-commit-config.yaml, or with the workspace settings of an editor that starts tukuroi lsp. pre-commit runs the hooks that the repo defines, so running it on a repo is beyond what this option can protect.

Also:

  • Run the tukuroi command, or python -P -m tukuroi. python -m tukuroi puts the current directory first on sys.path. tukuroi takes it off when it starts, so that the modules it imports later (such as a formatter) are not read from there. But a tukuroi package in the current directory is imported in place of tukuroi before that.

  • To use a configuration that you trust instead of the ones found next to the linted files, pass --config-file. tukuroi still imports the custom rules that it enables.

Integrations

IDE

tukuroi can be used to lint as you type as well as to format files.

To get this functionality, install the lsp extras (e.g. pip install "tukuroi[lsp]") then set up an LSP client to launch and connect to the tukuroi LSP server. See the lsp command for command usage details.

The server lints the documents that the client opens as Python (languageId python), whatever their suffix, and formats only an open document. It reads the configuration of a document each time it lints it, so a change to a configuration needs no restart. A syntax error, an exception in a rule, and a configuration that tukuroi cannot use are diagnostics too, with the severity Error: a syntax error where it is, and the others at the start of the document. The traceback of an exception goes to the log of the client.

The server imports the custom rules that the configuration of each opened file enables, a file outside the workspace too, with the configurations found from it as for lint (see Configuration). To open code that you do not trust, start it with tukuroi --no-custom-rules lsp (see Security). It imports each module of rules once: after changing a custom rule, restart the server.

Examples of client setup:

require("lspconfig.configs").tukuroi = {
  default_config = {
    cmd = { "tukuroi", "lsp" },
    filetypes = { "python" },
    root_dir = require("lspconfig").util.root_pattern(
      "pyproject.toml", "setup.py", "requirements.txt", ".git",
    ),
    single_file_support = true,
  },
}

lspconfig.tukuroi.setup({})

pre-commit

tukuroi can be included as a hook for pre-commit, or for prek, which reads the same configuration.

Once you install it, you can add tukuroi’s pre-commit hook to the .pre-commit-config.yaml file in your repository.

  • To run lint rules on commit, add:

repos:
  - repo: https://github.com/Fkinds/tukuroi
    rev: <commit SHA>  # no release of this fork has a tag yet
    hooks:
      - id: tukuroi-lint
  • To run lint rules and apply autofixes, add:

repos:
  - repo: https://github.com/Fkinds/tukuroi
    rev: <commit SHA>  # no release of this fork has a tag yet
    hooks:
      - id: tukuroi-fix

The hooks install tukuroi without its extras. With formatter = "ruff" in the configuration (see formatter), add ruff to the hook:

- id: tukuroi-fix
  additional_dependencies: ["ruff"]

To read more about how you can customize your pre-commit configuration, see the pre-commit docs.

The hooks import the custom rules that the repo’s configuration enables, and pre-commit runs the hooks that the repo defines: only run them on repos that you trust (see Security).

Output for programs

Two output formats are for programs to read (see output-format). They print one document on STDOUT, after all the results, and nothing else: the errors with their tracebacks, the diffs of --diff, the metrics of --print-metrics and the prompt of fix --interactive go to STDERR, with the summary line. fix -, which prints the fixed source on STDOUT, is a usage error with them. The paths are relative to the current directory when they are under it, as in the other formats.

json prints one JSON document (RFC 8259), in ASCII. The lines are counted from 1, and the columns in characters from 0, as in the other formats. The lists are sorted by path, and the violations by position:

{
  "files": ["broken.py", "t.py"],
  "violations": [
    {
      "path": "t.py",
      "rule": "NoAssertTrueForComparisons",
      "message": "\"assertTrue\" does not compare its arguments, ...",
      "autofixable": true,
      "start": {"line": 1, "column": 0},
      "end": {"line": 1, "column": 21},
      "diff": "--- a/t.py\n+++ b/t.py\n..."
    }
  ],
  "errors": [
    {
      "path": "broken.py",
      "type": "tukuroi.core.source.ParseError",
      "message": "Syntax Error @ 1:5: unmatched ')'",
      "traceback": null,
      "position": {"line": 1, "column": 5}
    }
  ],
  "fixed": [{"path": "t.py", "applied": 1, "remaining": 0}]
}
  • files: each file checked.

  • violations: the end is the position after the last character, and diff is the diff of the fix of the violation alone, or null.

  • errors: a file that tukuroi could not lint. position is that of a syntax error, or null; traceback is null for a syntax error.

  • fixed: with fix, the files whose fixes were applied, how many, and how many violations are left in each.

sarif prints a log of SARIF 2.1.0, with one run. Its rules are those that the configuration of the current directory enables, with those reported, each with its message and its docstring; a result is a violation, with the level warning; and an error of a file is a notification of the invocation, which makes it unsuccessful. The columns are counted in code points, from 1 (columnKind is unicodeCodePoints). The paths are URIs relative to %SRCROOT%, the current directory.

To see the violations in GitHub code scanning, run tukuroi lint with --output-format sarif from the root of the repository, and upload the file with the action github/codeql-action/upload-sarif. lint exits with 1 when it finds a violation: the step of the upload needs if: always().

$ tukuroi --output-format sarif lint > tukuroi.sarif

VSCode

For better integration with Visual Studio Code setting output-format can be set to vscode. That way VSCode opens the editor at the right position when clicking on code locations in tukuroi’s terminal output.

Writing Rules

tukuroi makes it easy to write new lint rules, directly in your codebase alongside the code they lint. A rule finds code in the syntax tree of Python’s ast module, and fixes it by replacing ranges of the original text: the rest of the file stays as it was, comments included. With formatter = "ruff" (see formatter), tukuroi then sorts the imports of each file it fixes, and formats it, with ruff. Write a replacement that reads well without it.

A Rule

A rule is a subclass of tukuroi.Rule, with a message, examples of code it accepts and reports, and visit_<node> methods named after the classes of ast:

# teambread/rules/hollywood.py

import ast

from tukuroi import Invalid, Rule, Valid


class HollywoodName(Rule):
    MESSAGE = "It's underproved!"
    VALID = (
        Valid('name = "Susan"\n'),
        Valid('print("Terry")\n'),
    )
    INVALID = (
        Invalid('name = "Paul"\n', expected_replacement='name = "Mary"\n'),
        Invalid("print('Paul')\n", expected_replacement='print("Mary")\n'),
    )

    def visit_Constant(self, node: ast.Constant) -> None:
        if node.value == "Paul":
            self.report(node, replacement='"Mary"')
  • 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.

  • tukuroi walks the tree once, parents before children, and calls the methods of every rule for each node. visit_stmt or visit_expr takes every node of that kind; the most specific method runs first.

  • self.report(node, message=None, *, replacement=None, edits=(), span=None, unused_imports=()) reports node, at the start of its range, or of span when it is given. Without replacement or edits, the report has no fix.

Where a Report Is

Some code has no node of its own: an operator such as is, the @ of a decorator, or the module of from a.b import c. To report it, give the node that holds it, and its span, from the tokens of the source. The comments that suppress the report are still those of the node:

import ast

from tukuroi import Invalid, Position, Rule, Span, Valid


class IsLiteral(Rule):
    MESSAGE = "Compare with a literal with ==, not with is."
    VALID = (Valid("x is None\n"), Valid("x == 1\n"))
    INVALID = (Invalid("if (x) is 1:\n    pass\n", position=Position(1, 7)),)

    def visit_Compare(self, node: ast.Compare) -> None:
        right = node.comparators[0]
        if not (
            isinstance(node.ops[0], ast.Is)
            and isinstance(right, ast.Constant)
            and type(right.value) in (int, float, str)
        ):
            return
        between = Span(
            self.source.span(node.left).end, self.source.span(right).start
        )
        is_ = next(t for t in self.source.tokens_in(between) if t.string == "is")
        self.report(node, span=is_.span)

State

tukuroi makes an instance of each rule for each file. A rule that keeps a state, such as the names that it has seen, sets it up in __init__: it takes the tukuroi.Source of the file and its tukuroi.ImportTable, and passes them on to super().__init__:

import ast

from tukuroi import ImportTable, Rule, Source, Valid


class NoRepeatedImport(Rule):
    MESSAGE = "This module is imported already."
    VALID = (Valid("import os\nimport sys\n"),)
    INVALID = ("import os\nimport os\n",)

    def __init__(self, source: Source, imports: ImportTable) -> None:
        super().__init__(source, imports)
        self.seen: set[str] = set()

    def visit_Import(self, node: ast.Import) -> None:
        for alias in node.names:
            if alias.name in self.seen:
                self.report(node)
            self.seen.add(alias.name)

Fixes

A fix is replacement, a string for the text of the node reported, or edits, a list of tukuroi.Edit: each replaces a tukuroi.Span of the text, and an empty span inserts. Build them from the original text, so that quotes, comments and spacing stay as they are:

  • self.source.text is the text of the file, and self.source.span(node) the span of a node in it. self.source.comments (each a tukuroi.Comment) and self.source.tokens (each a tukuroi.Token) come from tokenize: each token has its type (such as tokenize.OP), its string, its span, and the positions start and end of the span. self.source.tokens_in(span) gives the tokens in a span, such as that of a node: the operators, @ or parentheses that the tree has no node for.

  • self.imports.qualified_names(node) tells what a name or an attribute refers to through the imports of the module: with import typing as t, t.Callable is typing.Callable. It follows the scopes of Python: an import in a function counts in that function only, and a parameter, an assignment or the target of a comprehension hides an import of the module. In one scope, a name assigned again after its import is not followed.

  • tukuroi.core.imports.add_import gives the name to use for a module or a name of it, and the edit that imports it when the file does not yet.

  • A fix that may leave an import unused names it in unused_imports, by its qualified name, such as "typing.NamedTuple". After all the fixes, tukuroi takes out its imports that no code reads any more: from typing import NamedTuple, or import typing that it was read through. A name that is still read, as code or as a word in a string (__all__, an annotation in quotes), keeps its import. tukuroi.core.imports.remove_import gives these edits, for a fix that needs them itself.

tukuroi applies the fixes of a file in the order of their start, and skips one that overlaps a fix applied before it. Then it lints the result again, until no fix is left (at most 100 rounds). A fix that would drop a comment inside the range it replaces is not applied: the report has no fix. Nor is a fix after which the file would not parse: tukuroi warns, with the name of the rule, and applies the other fixes. Test the replacements of a rule with its INVALID cases.

Tests

VALID and INVALID are the tests of the rule. A valid case must not be reported. An invalid case must be reported, with expected_message and position (a tukuroi.Position) when given. When the rule fixes it, the case must give expected_replacement: the file after all the fixes, as they leave it, compared as it is written. The tests do not format it.

Run them with tukuroi test, or add them to a test module of your own:

from tukuroi.testing import add_rule_tests_to_module

from .rules.hollywood import HollywoodName

add_rule_tests_to_module(globals(), [HollywoodName])

Enabling Rules

Enable the rules in the project’s Configuration file:

# teambread/pyproject.toml

[tool.tukuroi]
enable = [
    ".rules.hollywood",  # enable just the rules in hollywood.py
    ".rules",  # enable rules from all files in the rules/ directory
]

Note

The leading . (period) is required when using in-repo, or “local”, lint rules, with a module path relative to the directory containing the config file. This allows tukuroi to locate and import the lint rule without needing to install a plugin in the user’s environment.

tukuroi imports each module of rules once in a process. After changing a rule, restart tukuroi lsp (or the editor that runs it) for the change to take effect.

Rules run the code of the repo: see Security before linting code you do not trust.

Plugins

Other packages add to tukuroi: rules, formatters, and output formats. A package that you install with tukuroi brings them; a configuration of the repository names them. They run the code of the package: with custom rules turned off (see Security), tukuroi uses only those that come with it.

Rules

A package of rules needs nothing more than its modules: the configuration names them, as it names the rules in the repository (see Writing Rules), without the leading .:

[tool.tukuroi]
enable = ["tukuroi_django.rules"]

Formatters

A formatter formats the files that tukuroi fix fixes, when a configuration names it with formatter. It is a class with two methods, as tukuroi.FormatterPlugin has them, that a package registers in the entry points tukuroi.formatters, by the name that the configuration gives:

# tukuroi_black/__init__.py

import importlib.util
from pathlib import Path


class BlackFormatter:
    def available(self) -> str | None:
        # Why it cannot run, or None.
        if importlib.util.find_spec("black") is None:
            return "needs the black package"
        return None

    def format(self, text: str, path: Path | None) -> str:
        import black

        return black.format_str(text, mode=black.Mode())
# pyproject.toml of tukuroi-black

[project.entry-points."tukuroi.formatters"]
black = "tukuroi_black:BlackFormatter"

tukuroi makes the class with no argument, and calls format with the fixed text of a file and its path, or None for the standard input. ruff comes with tukuroi, registered the same way. When two packages register a name, that of tukuroi wins.

Output formats

An output format prints the results of tukuroi lint and tukuroi fix, when a configuration names it with output-format, or the command line with --output-format. It is a class with the methods of tukuroi.OutputFormatPlugin, that a package registers in the entry points tukuroi.output_formats:

# tukuroi_count/__init__.py

from tukuroi import Config, Result


class CountFormat:
    def __init__(self, config: Config) -> None:
        self.count = 0

    def start(self) -> str | None:
        return None

    def result(self, result: Result) -> str | None:
        if result.violation is None:
            return None
        self.count += 1
        line = result.violation.range.start.line
        return f"{result.path}:{line} {result.violation.message}"

    def end(self) -> str | None:
        return f"{self.count} violations"
# pyproject.toml of tukuroi-count

[project.entry-points."tukuroi.output_formats"]
count = "tukuroi_count:CountFormat"

tukuroi makes the class once for a run, with the configuration of the current directory, and prints what start gives before the results, what result gives for each Result, and what end gives after them; None prints nothing. tukuroi itself still prints an error with its traceback, and the diff of a fix with --diff. tukuroi fix - prints the fixed source alone on the standard output, and all of this on the standard error. The names are in any letter case. tukuroi, vscode, custom, json and sarif come with tukuroi, registered the same way. With custom rules turned off, tukuroi prints tukuroi in place of another, with a warning.

A format for programs to read sets the class attribute MACHINE_READABLE = True, as json and sarif do. tukuroi then prints what the format gives without colors, alone on the standard output, and the rest on the standard error (see Output for programs). Without the attribute, a format is for people to read.

Built-in Rules

tukuroi.rules

These rules are all part of the tukuroi.rules package, and are enabled by default unless explicitly listed in the disable configuration option.

class tukuroi.rules.NoAssertTrueForComparisons

Finds incorrect use of assertTrue when the intention is to compare two values. These calls are replaced with assertEqual. Comparisons with True, False and None are replaced with one-argument calls to assertTrue, assertFalse and assertIsNone.

MESSAGE

“assertTrue” does not compare its arguments, use “assertEqual” or other appropriate functions.

AUTOFIX: Yes
VALID
self.assertTrue(a == b)
self.assertTrue(data.is_valid(), "is_valid() method")
INVALID
self.assertTrue(a, 3)

# suggested fix
self.assertEqual(a, 3)
self.assertTrue(hash(s[:4]), 0x1234)

# suggested fix
self.assertEqual(hash(s[:4]), 0x1234)
class tukuroi.rules.NoNamedTuple

Enforce the use of dataclasses.dataclass decorator instead of NamedTuple for cleaner customization and inheritance. It supports default value, combining fields for inheritance, and omitting optional fields at instantiation. See PEP 557. @dataclass is faster at reading an object’s nested properties and executing its methods. (benchmark)

MESSAGE

Instead of NamedTuple, consider using the @dataclass decorator from dataclasses instead for simplicity, efficiency and consistency.

AUTOFIX: Yes
VALID
@dataclass(frozen=True)
class Foo:
    pass
@dataclass(frozen=False)
class Foo:
    pass
INVALID
from typing import NamedTuple

class Foo(NamedTuple):
    pass

# suggested fix
from dataclasses import dataclass

@dataclass(frozen=True)
class Foo:
    pass
from typing import NamedTuple as NT

class Foo(NT):
    pass

# suggested fix
from dataclasses import dataclass

@dataclass(frozen=True)
class Foo:
    pass
class tukuroi.rules.NoStaticIfCondition

Discourages if conditions which evaluate to a static value (e.g. or True, and False, etc).

MESSAGE

Your if condition appears to evaluate to a static value (e.g. or True, and False). Please double check this logic and if it is actually temporary debug code.

VALID
if my_func() or not else_func():
    pass
if function_call(True):
    pass
INVALID
if True:
    do_something()
if crazy_expression or True:
    do_something()
class tukuroi.rules.SortedAttributes

Ever wanted to sort a bunch of class attributes alphabetically? Well now it’s easy! Just add “@sorted-attributes” in the doc string of a class definition and lint will automatically sort all attributes alphabetically.

Feel free to add other methods and such – it should only affect class attributes.

MESSAGE

It appears you are using the @sorted-attributes directive and the class variables are unsorted. See the lint autofix suggestion.

AUTOFIX: Yes
VALID
class MyConstants:
    """
    @sorted-attributes
    """

    A = "zzz123"
    B = "aaa234"


class MyUnsortedConstants:
    B = "aaa234"
    A = "zzz123"
class C:
    """@sorted-attributes"""

    b = 1; a = 2
INVALID
class MyUnsortedConstants:
    """
    @sorted-attributes
    """
    z = "hehehe"
    B = 'aaa234'
    A = 'zzz123'
    cab = "foo bar"
    Daaa = "banana"

    @classmethod
    def get_foo(cls) -> str:
        return "some random thing"

# suggested fix
class MyUnsortedConstants:
    """
    @sorted-attributes
    """
    A = 'zzz123'
    B = 'aaa234'
    Daaa = "banana"
    cab = "foo bar"
    z = "hehehe"

    @classmethod
    def get_foo(cls) -> str:
        return "some random thing"
class C:
    """@sorted-attributes"""

    # about b
    b = 1  # b
    a = 2

# suggested fix
class C:
    """@sorted-attributes"""
    a = 2

    # about b
    b = 1  # b
class tukuroi.rules.UseAssertIn

Discourages use of assertTrue(x in y) and assertFalse(x in y) as it is deprecated (https://docs.python.org/3.8/library/unittest.html#deprecated-aliases). Use assertIn(x, y) and assertNotIn(x, y)) instead.

MESSAGE

Use assertIn/assertNotIn instead of assertTrue/assertFalse for inclusion check. See https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn)

AUTOFIX: Yes
VALID
self.assertIn(a, b)
self.assertIn(f(), b)
INVALID
self.assertTrue(a in b)

# suggested fix
self.assertIn(a, b)
self.assertTrue(f() in b)

# suggested fix
self.assertIn(f(), b)
class tukuroi.rules.UseAssertIsNotNone

Discourages use of assertTrue(x is not None) and assertFalse(x is not None) as it is deprecated (https://docs.python.org/3.8/library/unittest.html#deprecated-aliases). Use assertIsNotNone(x) and assertIsNone(x)) instead.

MESSAGE

“assertTrue” and “assertFalse” are deprecated. Use “assertIsNotNone” and “assertIsNone” instead. See https://docs.python.org/3.8/library/unittest.html#deprecated-aliases

AUTOFIX: Yes
VALID
self.assertIsNotNone(x)
self.assertIsNone(x)
INVALID
self.assertTrue(a is not None)

# suggested fix
self.assertIsNotNone(a)
self.assertTrue(not x is None)

# suggested fix
self.assertIsNotNone(x)
class tukuroi.rules.VariadicCallableSyntax

Callable types with arbitrary parameters should be written as Callable[…, T]

MESSAGE

Callable types with arbitrary parameters should be written as Callable[…, T]

AUTOFIX: Yes
VALID
from typing import Callable

x: Callable[[int], int]
from typing import Callable

x: Callable[[int, int, ...], int]
INVALID
from typing import Callable

x: Callable[[...], int] = ...

# suggested fix
from typing import Callable

x: Callable[..., int] = ...
import typing as t

x: t.Callable[[...], int] = ...

# suggested fix
import typing as t

x: t.Callable[..., int] = ...

tukuroi.rules.strict

Rules stricter than most code needs. tukuroi does not enable them by default, and enabling tukuroi.rules does not enable them: name this package, or a rule of it, in enable.

class tukuroi.rules.strict.NoValueObjectDefault

A value object takes every value of its fields from its caller: no field has a default, which the caller would get without writing it. Explicit is better than implicit.

A value object is a frozen class that is equal to the objects of the same values: one of @dataclass(frozen=True), or of attrs, @attrs.frozen, @attrs.define(frozen=True) or @attr.s(frozen=True). A frozen class with eq=False (or cmp=False of attr.s) is an entity, equal to the objects of its identity only, and may give its id a default. The fields that the caller does not pass keep theirs: field(init=False) (attr.ib(init=False)), and what is not a field: the ClassVar annotations, and the annotations that attrs does not take as fields, those of attr.s without auto_attribs=True, and those of a class with an attr.ib() that has no annotation.

Only eq=False tells an entity from a value object: give it to each frozen entity. A frozen class that is neither, such as settings frozen so that nothing changes them, is reported too: keep a default with # lint-ignore: NoValueObjectDefault at the end of the last line of its field or on the line above the field, or do not enable the rule for the files of the class.

MESSAGE

A field of a value object takes no default: the caller passes every value.

VALID
from dataclasses import dataclass

@dataclass(frozen=True, kw_only=True)
class Money:
    amount: int
    currency: str
import uuid
from dataclasses import dataclass, field

@dataclass(frozen=True, kw_only=True, eq=False)
class Order:
    id: uuid.UUID = field(default_factory=uuid.uuid4)
INVALID
from dataclasses import dataclass

@dataclass(frozen=True, kw_only=True)
class Money:
    amount: int
    currency: str = "JPY"
from dataclasses import dataclass, field

@dataclass(frozen=True, eq=True)
class Money:
    amount: int = field(init=True, default=0)

Rules Replaced by ruff

tukuroi keeps only the built-in rules that ruff does not cover. The other built-in rules of Fixit 2 are removed: use the ruff rules below instead.

The table was checked with ruff 0.17, against the VALID and INVALID cases of each Fixit rule. “Same” means that ruff reports every INVALID case; “close” means that it misses some, or fixes them another way.

Fixit rule

ruff rules

Differences

AvoidOrInExcept

PLW0711, B030

Same.

CollapseIsinstanceChecks

SIM101

Same. ruff also merges a call into a tuple that is already there.

ComparePrimitivesByEqual

F632

Close: ruff does not take an f-string for a literal (a is f"1{b}").

CompareSingletonPrimitivesByIs

E711, E712

Close: ruff misses chained comparisons (x is True == y). E712 fixes x != True to not x, a check of truth, not of identity.

DeprecatedABCImport

UP035

Close: ruff misses import collections.Container and collections.Container as a base class. It also reports the fallback import in except ImportError.

DeprecatedUnittestAsserts

UP005

Same.

NoInheritFromObject

UP004

Same.

NoRedundantArgumentsSuper

UP008

Same.

NoRedundantFString

F541

Same.

NoRedundantLambda

PLW0108

Same.

NoRedundantListComprehension

C419

Same.

NoStringTypeAnnotation

UP037

Same. ruff also reports the annotations that are only read by type checkers.

ReplaceUnionWithOptional

None

ruff goes the other way: UP007 and UP045 rewrite Union[T, None] and Optional[T] to T | None.

RewriteToComprehension

C400, C401, C402, C403, C404

Close: ruff misses pairs given as lists (dict([a, b] for ...)).

RewriteToLiteral

C405, C406, C408, C409, C410

Close: ruff misses dict() of a list of lists.

UseAsyncSleepInAsyncDef

ASYNC251

Same.

UseClsInClassmethod

N804

Close: ruff misses a class method without arguments.

UseFstring

UP031, UP032

Close: UP032 skips .format() with literal arguments. UP031 reports every % format, not only %s.

UseTypesFromTyping

None

It applied only below Python 3.10. tukuroi supports newer versions.

ExplicitFrozenDataclass (fixit.rules.extra)

None

ruff has no rule for it.

UseLintFixmeComment (fixit.rules.extra)

PGH004

Close: PGH004 reports a # noqa without codes only.

Most of these ruff rules are on by default. Turn the others on in the ruff configuration of the project:

[tool.ruff.lint]
extend-select = ["E711", "E712", "N804", "PGH004", "PLW0108"]