API Reference

Lint Rules

class fixit.LintRule

Lint rule implemented using LibCST.

To build a new lint rule, subclass this and Implement a CST visitor. When a lint rule violation should be reported, use the report() method.

get_visitors()

Returns a mapping of all the visit_<Type[CSTNode]>, visit_<Type[CSTNode]>_<attribute>, leave_<Type[CSTNode]> and leave_<Type[CSTNode]>_<attribute>` methods defined by this visitor, excluding all empty stubs.

Return type:

Mapping[str, Callable[[CSTNode], None]]

ignore_lint(node)

Whether to ignore a violation for a given node.

Returns true if any # lint-ignore or # lint-fixme directives match the current rule by name, or if the directives have no rule names listed.

Parameters:

node (CSTNode) –

Return type:

bool

node_comments(node)

Yield all comments associated with the given node.

Includes comments from both leading comments and trailing inline comments.

Parameters:

node (CSTNode) –

Return type:

Generator[str, None, None]

report(node, message=None, *, position=None, replacement=None)

Report a lint rule violation.

If message is not provided, self.MESSAGE will be used as a violation message. If neither of them are available, this method raises ValueError.

The optional position parameter can override the location where the violation is reported. By default, the entire span of node is used. If position is a CodePosition, only a single character is marked.

The optional replacement parameter can be used to provide an auto-fix for this lint violation. Replacing node with replacement should make the lint violation go away.

Parameters:
Return type:

None

AUTOFIX = False

Whether the lint rule contains an autofix.

Set to True automatically when INVALID contains at least one test case that provides an expected replacment.

INVALID: ClassVar[List[str | Invalid]]

Test cases that are expected to produce errors, with optional replacements

METADATA_DEPENDENCIES: ClassVar[Collection[ProviderT]] = (<class 'libcst.metadata.position_provider.PositionProvider'>,)

Required LibCST metadata providers

PYTHON_VERSION: str = ''

Compatible target Python versions, in PEP 440 version specifier format.

TAGS: Set[str] = {}

Arbitrary classification tags for use in configuration/selection

VALID: ClassVar[List[str | Valid]]

Test cases that should produce no errors/reports

name: str

Friendly name of this lint rule class, without any “Rule” suffix.

class fixit.Valid(code: str)
Parameters:

code (str) –

code: str
class fixit.Invalid(code: str, range: libcst._position.CodeRange | None = None, expected_message: str | None = None, expected_replacement: str | None = None)
Parameters:
  • code (str) –

  • range (CodeRange | None) –

  • expected_message (str | None) –

  • expected_replacement (str | None) –

code: str
expected_message: str | None = None
expected_replacement: str | None = None
range: CodeRange | None = None

Frontends

Simple API

fixit.fixit_paths(paths, *, autofix=False, options=None, parallel=True)

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 fixit_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 fixit_bytes() for semantics.

If the first given path is STDIN (Path("-")), then content will be linted from STDIN using fixit_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 fixit.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.

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.

Parameters:
Return type:

Generator[Result, bool, None]

fixit.fixit_file(path, *, autofix=False, options=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 fixit_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 fixit_bytes() for semantics.

Parameters:
Return type:

Generator[Result, bool, None]

fixit.print_result(result, *, show_diff=False, stderr=False)

Print linting results in a simple format designed for human eyes.

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 fixit.LintViolation(rule_name, range, message, node, replacement, diff='')

An individual lint error, with an optional replacement and expected diff.

Parameters:
property autofixable: bool

Whether the violation includes a suggested replacement.

diff: str
message: str
node: CSTNode
range: CodeRange
replacement: CSTNode | FlattenSentinel[CSTNode] | RemovalSentinel | None
rule_name: str
class fixit.Result(path, violation, error=None)

A single lint result for a given file and lint rule.

Parameters:
error: Tuple[Exception, str] | None = None
path: Path
violation: LintViolation | None

Advanced API

fixit.FileContent

alias of bytes

fixit.fixit_bytes(path, content, *, config, autofix=False)

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.

Parameters:
Return type:

Generator[Result, bool, bytes | None]

class fixit.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( fixit_bytes(...) )
for result in generator:  # LintViolation
    ...
    generator.respond(...)  # optional

result = generator.result  # FileContent
Parameters:

generator (Generator[Yield, Send, Return]) –

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 fixit.Config(path=<factory>, root=<factory>, enable_root_import=False, enable=<factory>, disable=<factory>, options=<factory>, python_version=<factory>, tags=<factory>, formatter=None)

Materialized configuration valid for processing a single file.

Parameters:
disable: List[QualifiedRule]
enable: List[QualifiedRule]
enable_root_import: bool | Path = False
formatter: str | None = None
options: Dict[str, Dict[str, str | int | float]]
path: Path
python_version: Version | None
root: Path
tags: Tags
class fixit.Options(debug, config_file, tags=None, rules=())

Command-line options to affect runtime behavior

Parameters:
config_file: Path | None
debug: bool | None
rules: Sequence[QualifiedRule] = ()
tags: Tags | None = None
class fixit.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) –

local: str | None = None
module: str
name: str | None = None
root: Path | None = None
class fixit.Tags(include: Tuple[str, ...] = (), exclude: Tuple[str, ...] = ())
Parameters:
static parse(value)
Parameters:

value (str | None) –

Return type:

Tags

exclude: Tuple[str, ...] = ()
include: Tuple[str, ...] = ()

Formatters

class fixit.Formatter

Fixit post-transform code style and formatting interface.

format(module, path)

Format the given Module and return it as UTF-8 encoded bytes.

Parameters:
Return type:

bytes

STYLE: str

Short name to identify this formatting style in user configuration. For example: "black".