API Reference¶
Lint Rules¶
- class rattle.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.
- ignore_lint(node)¶
Whether to ignore a violation for a given node.
Returns true if any
# rattle: ignore[...]directive matches the current rule by name, or if the directive has no rule names listed.
- node_comments(node)¶
Yield all comments associated with the given node.
Includes comments from both leading comments and trailing inline comments.
- report(node, message, *, position=None, position_node=None, replacement=None)¶
Report a lint rule violation.
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:
node (CSTNode)
message (str)
position (CodePosition | CodeRange | None)
position_node (CSTNode | None)
replacement (CSTNode | FlattenSentinel[CSTNode] | RemovalSentinel | None)
- Return type:
None
- AUTOFIX = False¶
Whether the lint rule contains an autofix.
Set to
Trueautomatically whenINVALIDcontains at least one test case that provides an expected replacement.
- INVALID: ClassVar[Sequence[str | Invalid]]¶
Test cases that are expected to produce errors, with optional replacements
- METADATA_DEPENDENCIES: ClassVar[Collection[ProviderT]] = ()¶
Required LibCST metadata providers
- NAME: ClassVar[str] = ''¶
Explicit public rule name. Defaults to kebab-case generated from the class name.
- PYTHON_VERSION: str = ''¶
Compatible target Python versions, in PEP 440 version specifier format.
- REFERENCES: ClassVar[Sequence[RuleReference]] = ()¶
External references for documentation, as URLs or
(label, URL)pairs.
- SETTINGS: ClassVar[dict[str, RuleSetting]] = {}¶
Optional typed configuration settings for this lint rule.
- class rattle.RuleSetting(value_type: 'object', default: 'object' = <object object at 0x7b69c7f33d40>, validator: 'Callable[[object], object] | None' = None, description: 'str' = '')¶
- Parameters:
- validate(value, *, setting_name, rule_name)¶
- class rattle.Valid(code: str, options: dict[str, str | int | float | bool | list[Any] | dict[str, Any]] | None = None)¶
- Parameters:
Frontends¶
Simple API¶
- rattle.rattle_paths(paths, *, autofix=False, include_diff=False, allow_cached_dirty_results=False, options=None, parallel=True, metrics_hook=None)¶
Lint multiple files or directories, recursively expanding each path.
Walks all paths given, obeying any
.gitignoreexclusions, finding Python source files. Lints each file found usingrattle_file(), using a process pool when more than one file is being linted.Yields
Resultobjects for each path, lint error, or exception found. Seerattle_bytes()for semantics.If the first given path is STDIN (
Path("-")), then content will be linted from STDIN usingrattle_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 thepyproject.tomlconfiguration - 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. Settingparallel=Falsewill enable interactive fixes. Settingautofix=Truewill always apply fixes automatically during linting.
- rattle.rattle_file(path, *, autofix=False, include_diff=False, options=None, explicit_path=False, 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
rattle_bytes()to lint and apply any fixes to the content. Writes content back to disk if changes are detected.Yields
Resultobjects for each lint error or exception found, or a single empty result if the file is clean. Seerattle_bytes()for semantics.
- rattle.print_result(result, *, show_diff=False, stderr=False, output_format=OutputFormat.rattle, output_template='', brief=False)¶
Print linting results in a simple format designed for human eyes.
Setting
show_diff=Truewill output autofixes or suggested changes in unified diff format, using ANSI colors when possible.Returns
Trueif the result is “dirty” - either a lint error or exception.
- class rattle.LintViolation(rule_name, range, message, node, replacement, diff='', position_node=None)¶
An individual lint error, with an optional replacement and expected diff.
- Parameters:
rule_name (str)
range (CodeRange | None)
message (str)
node (CSTNode)
replacement (CSTNode | FlattenSentinel[CSTNode] | RemovalSentinel | None)
diff (str)
position_node (CSTNode | None)
- replacement: CSTNode | FlattenSentinel[CSTNode] | RemovalSentinel | None¶
- class rattle.Result(path, violation, error=None, source=None, config=None)¶
A single lint result for a given file and lint rule.
- Parameters:
- classmethod from_exception(path, error, *, source=None, config=None)¶
- violation: LintViolation | None¶
Advanced API¶
- rattle.rattle_bytes(path, content, *, config, autofix=False, include_diff=False, rules=None, metrics_hook=None)¶
Lint raw bytes content representing a single path, using the given configuration.
Yields
Resultobjects 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 finalFileContentincluding any fixes applied.Use
capture()to more easily capture return value after iterating through violations. Usegenerator.send(...)with a boolean value to apply individual fixes for each violation.If
autofixisTrue, all violations with replacements will be applied automatically, even ifFalseis sent back to the generator.
- rattle.util.capture¶
alias of
Capture
- class rattle.Config(path=<factory>, root=<factory>, excluded=False, enable_root_import=False, enable=<factory>, disable=<factory>, rule_imports=<factory>, options=<factory>, python_version=<factory>, tags=<factory>, formatter='auto', output_format=OutputFormat.rattle, output_template='')¶
Materialized configuration valid for processing a single file.
- Parameters:
path (Path)
root (Path)
excluded (bool)
enable (list[QualifiedRule | RuleNameSelector])
disable (list[QualifiedRule | RuleNameSelector])
rule_imports (list[QualifiedRule | RuleNameSelector])
options (dict[str, dict[str, str | int | float | bool | list[Any] | dict[str, Any]]])
python_version (Version | None)
tags (Tags)
formatter (str | None)
output_format (OutputFormat)
output_template (str)
- disable: list[QualifiedRule | RuleNameSelector]¶
- enable: list[QualifiedRule | RuleNameSelector]¶
- output_format: OutputFormat = 'rattle'¶
- rule_imports: list[QualifiedRule | RuleNameSelector]¶
- class rattle.Options(debug=None, config_file=None, exclude=(), extend_exclude=(), jobs=None, tags=None, rules=(), output_format=None, output_template=None, print_metrics=False, no_format=False)¶
Command-line options to affect runtime behavior.
- Parameters:
- rules: Sequence[QualifiedRule | RuleNameSelector] = ()¶