🧹 check#
Style rules that ruff cannot express, checked on text files and Python sources.
Each rule of RULES can be left out with ignore, and the limits tuned, in pyproject.toml:
[tool.stouputils.check]
ignore = ["tab-indentation", "space-alignment"]
final-newlines = { ".py" = 1, ".json" = 1 }
initial-newlines = { ".md" = 1, ".mcfunction" = 1 }
docstring-max-lines = 20
per-file-ignores = { "tests/**" = ["long-comment"] }
In a Python file, # stp: ignore[rule] silences its own line, or the multi-line string it closes,
and # stouputils: ignore[rule] the whole file.
# Write a Python file with a few style problems
cat > area.py <<'EOF'
PI = 3.14159 # Rounded to 5 decimals
def area(radius: float) -> float:
''' Area of a disk, radius in metres. '''
# Area of a disk,
# in square metres,
# rounded to 2 places
return round(PI * radius ** 2, 2)
EOF
# List what the style rules find in it
stouputils check area.py
cli#
Command line of stouputils check: which files to read, the rules on any text file, and the report.
- BANNED_CHARACTERS: Pattern[str] = re.compile('[\\N{EM DASH}\\N{EN DASH}\\N{HORIZONTAL ELLIPSIS}\\N{MULTIPLICATION SIGN}\\N{RIGHTWARDS ARROW}\\N{LEFT SINGLE QUOTATION MARK}\\N{RIGHT SINGLE QUOTATION MARK}\\N{LEFT DOUBLE QUOTATION MARK}\\N{RIGHT D)[source]#
Typography that marks text as AI-written: long dashes, ellipsis, arrows, curly quotes and box-drawing comment banners.
- expand_paths(
- paths: Iterable[Path],
Files as given, and every file under a directory that git tracks or does not ignore.
Outside a git repository, a directory expands to every file below it whose path has no hidden part.
- check_file(
- path: Path,
- config: CheckConfig,
Every violation in a file that no suppression comment or ignored rule silences, sorted by line.
Binary and non UTF-8 files yield nothing.
python#
Rules on Python sources: indentation, comments, docstrings and module constants.
- CLAUSE_ENDINGS: tuple[str, ...] = ('.', '!', '?', ':', ';', ',')[source]#
Line endings that close a sentence or a clause, where a line break reads naturally.
- CLAUSE_BOUNDARY: Pattern[str] = re.compile('[.!?:;,](?:\\s|$)')[source]#
Punctuation followed by a space, which splits a line into its clauses.
- NEW_ITEM: Pattern[str] = re.compile('\\*{0,2}\\w+(?:\\s+\\([^)]*\\))?:(?:\\s|$)|\\w+(?:\\[.*?\\])?(?: \\| \\w+(?:\\[.*?\\])?)+:\\s|\\w[.)]\\s|(?:noqa|type:|pyright:|ruff:|fmt:|pragma|stp:|stouputils:)')[source]#
Line starts that open an entry of their own: an
Args:entry, a union type, a list item, or a tool directive.
- EXAMPLES_HEADER: Pattern[str] = re.compile('\\s*Examples?:\\s*$')[source]#
Header that doctests do not need, since
>>>already marks them.
- TYPED_ARGUMENT: Pattern[str] = re.compile('\\s*\\*{0,2}(?!Traceback\\b)\\w+:?\\s+\\(.*\\):')[source]#
Args:entry that repeats the type the signature already carries, as inname (int):.
- SPAN_DELIMITERS: tuple[str, ...] = ('``', '`', '"')[source]#
Delimiters of inline code and quotes, the double backtick counted and removed before the single one.
- STRANDED_FRAGMENT: str = 'a line break leaves a few words of a clause alone, break at a clause or sentence boundary'[source]#
Message shared by comments and docstrings.
- SUPPRESSION: Pattern[str] = re.compile('#\\s*(stp|stouputils):\\s*ignore\\b(?:\\[([^\\]]*)\\])?')[source]#
A suppression comment:
stpsilences its own line, or the string it closes, andstouputilsthe whole file.
- CONTROL_FLOW: tuple[type[stmt], ...] = (<class 'ast.If'>, <class 'ast.For'>, <class 'ast.AsyncFor'>, <class 'ast.While'>, <class 'ast.Try'>, <class 'ast.TryStar'>, <class 'ast.With'>, <class 'ast.AsyncWith'>, <class 'ast.Match'>)[source]#
Statements that branch or loop, the ones a dense paragraph holds too many of.
- LAYOUT_TOKENS: frozenset[int] = frozenset({0, 4, 5, 6, 65})[source]#
Tokens carrying no code, which a suppression comment never attaches to.
- python_errors(
- source: str,
- config: CheckConfig,
Violations of the Python rules, in no particular order.
>>> rules = lambda source: sorted((v.line, v.rule) for v in python_errors(source, CheckConfig())) >>> rules("def f():\n\tx = 1\n\ty\t= 2\n") [(3, 'space-alignment')] >>> rules("x = [\n 1,\n]\n"), rules('x = f"""\n {1}\n"""\n') ([(2, 'tab-indentation')], []) >>> [(v.line, v.end_line) for v in python_errors("if x:\n a = 1\n\n b = 2\n", CheckConfig())] [(2, 4)] >>> rules("# Roll once per tick. The\n# caller resets the counter.\n") [(2, 'stranded-fragment')] >>> rules("LIMIT: int = 3 # Retries\n") [(1, 'constant-comment')]
- suppressions(
- source: str,
Suppression comments of a Python source, none when it does not tokenize.
A
stpcomment after a multi-line string covers the whole string, the only way to reach the lines of a docstring.>>> [(s.line, s.lines) for s in suppressions("def f():\n\t'''\n\tlong\n\t''' # stp: ignore[long-docstring]\n")] [(4, range(2, 5))] >>> suppressions("# stouputils: ignore[tab-indentation, long-comment]\n") [Suppression(line=1, rules=('tab-indentation', 'long-comment'), lines=None)] >>> suppressions('x = "# stp: ignore[long-comment]" # stp: ignore\n') [Suppression(line=1, rules=(), lines=range(1, 2))]
- suppression_from_comment(
- match: Match[str],
- line: int,
- statement_start: int,
The suppression a comment matching
SUPPRESSIONdeclares.- Parameters:
line – Line of the comment.
statement_start – First line of the statement the comment ends, which a
stpcomment covers down to its own line.
>>> suppression_from_comment(SUPPRESSION.search("# stp: ignore[long-comment, x]"), 5, statement_start=3) Suppression(line=5, rules=('long-comment', 'x'), lines=range(3, 6))
- statements(
- tree: Module,
Every statement of a module, nested ones included, without descending into expressions.
- indentation_errors(
- source: str,
- string_lines: set[int],
- tab_aligned: set[int],
Lines of code indented with a space, or aligned with a tab between two tokens, one violation per run of them.
Lines continuing a multi-line string are data, so they are left alone, and neither they nor blank lines end a run.
- tab_aligned_lines(
- tokens: list[TokenInfo],
Lines where a tab separates two tokens, which leaves the tabs inside strings and comments alone.
- string_content_lines(
- tokens: list[TokenInfo],
Lines whose leading whitespace belongs to a multi-line string rather than to the code.
- comment_errors(
- tokens: list[TokenInfo],
- config: CheckConfig,
Blocks of comment lines over the limit, and fragments stranded across comment lines.
- docstring_layout_errors(
- tree: Module,
- config: CheckConfig,
A module docstring below line 1, and function or class docstrings over the size limit.
- directive_lines(docstring: str) int[source]#
Lines of the
.. code-block::and.. image::directives of a docstring, which its size limit leaves out.>>> directive_lines("Summary.\n\n.. code-block:: python\n\n\tprint(1)\n\n.. image:: demo.svg\nDone.") 5
- constant_errors(
- tree: Module,
- tokens: list[TokenInfo],
Module constants documented by a trailing comment rather than a docstring below them.
- paragraph_errors(
- tree: Module,
- lines: list[str],
- config: CheckConfig,
Paragraphs too long, branching too often and binding too many names to read at once.
A paragraph is a run of statements of one block. One that only tests and returns reads as a list of cases however long, so a paragraph is reported when it also binds names its reader has to carry to the lines below.
>>> dense = "def f(x):\n\ty, z = x, x\n" + "\tif y:\n\t\tz += 1\n" * 3 + "\treturn z\n" >>> errors = lambda source: [v.span for v in paragraph_errors(ast.parse(source), source.splitlines(), CheckConfig())] >>> errors(dense), errors(dense.replace("\treturn", "\n\treturn")), errors(dense.replace("y, z = x, x", "y = z = x")) (['2-9'], [], ['2-9']) >>> errors(dense.replace("y, z = x, x", "z = x")) []
- statement_blocks(
- tree: Module,
Every statement list of a module, nested ones included, a docstring opening one left out.
- bound_names(paragraph: list[stmt]) set[str][source]#
Names the statements of a paragraph assign at its own level, attributes and items left out.
- paragraphs(
- block: list[stmt],
- lines: list[str],
Runs of consecutive statements that no blank or comment line separates,
linesbeing the source split in lines.
- docstring_errors(
- docstring: str,
- first_line: int,
- config: CheckConfig,
An
Examples:header, types repeated inArgs:, and fragments stranded across lines.Code blocks and doctests are skipped, and a deeper indent continues an entry rather than a sentence.
>>> [v.rule for v in docstring_errors("Args:\n\tlimit (int): Retries\nExamples:\n\t>>> f()", 1, CheckConfig())] ['typed-argument', 'examples-header'] >>> list(docstring_errors(">>> quote = '\"'", 1, CheckConfig())) []
- split_spans(
- lines: Iterable[tuple[int, str]],
Inline code or a quote opened on one line and closed on a later one, reported at the line opening it.
>>> [v.line for v in split_spans([(1, "use ``f(a,"), (2, "b)`` here"), (3, 'and `g` or "h"'), (4, 'from "A'), (5, 'B" on')])] [1, 4]
- code_block_indent(content: str, indent: int) int | None[source]#
Indent that lines must exceed to belong to the code a docstring line opens, None when it opens none.
A doctest owns the lines at its own indent until a blank line, an RST block only the deeper ones.
- strands_fragment(
- previous: str,
- current: str,
- max_words: int,
Whether a line break cuts a clause and leaves at most
max_wordsof its words alone on one side.A break after a comma or a semicolon falls between clauses, which reads fine.
>>> strands_fragment("The wrapper is generic, so they come", "from :py:mod:`cli`. Only the rest is ours.", 3) True >>> strands_fragment("The wrapper is generic,", "so they come from :py:mod:`cli`.", 3) False >>> strands_fragment("Roll once per tick. The", "caller resets the counter.", 3) True >>> strands_fragment("Args:", "limit: Retries", 3) False
rules#
The rules stouputils check knows, the settings a project tunes them with, and the violations they report.
- RULES: dict[str, str] = {'banned-characters': 'Long dashes, ellipsis, multiplication sign, arrows, curly quotes and box-drawing comment banners', 'constant-comment': 'A module constant documented by a trailing comment instead of a docstring below it', 'dense-paragraph': 'A run of statements with no blank or comment line between them, too long, branching and binding too much', 'examples-header': 'An ``Examples:`` header above doctests, which ``>>>`` already marks', 'final-newlines': 'A file not ending with the configured number of newline characters', 'initial-newlines': 'A file not starting with the configured number of newline characters', 'long-comment': 'A block of consecutive comment lines over the limit', 'long-docstring': 'A function or class docstring over the line limit, its code-block and image directives left out', 'module-docstring-position': 'A module docstring below line 1', 'space-alignment': 'Python code aligned with a tab after the first character instead of spaces', 'split-span': 'Inline code or a quote opened on one line of a comment or docstring and closed on another', 'stranded-fragment': 'A line break in a comment or docstring leaving a few words of a clause alone', 'syntax-error': 'A Python file the tokenizer or the parser rejects', 'tab-indentation': 'Python code indented with a space instead of tabs', 'typed-argument': 'An ``Args:`` entry repeating the type the signature carries', 'unused-ignore': 'A suppression comment naming no rule, an unknown one, or one it does not silence'}[source]#
Every rule by the name
ignoretakes, with what it reports.
- class Violation(
- line: int,
- rule: str,
- message: str,
- end_line: int | None = None,
Bases:
objectOne rule broken at one line, or on every checked line of a range.
- class Suppression(
- line: int,
- rules: tuple[str, ...],
- lines: range | None,
Bases:
objectRules a
# stp: ignore[...]or# stouputils: ignore[...]comment silences, and on which lines.>>> suppression = Suppression(line=4, rules=("long-docstring",), lines=range(2, 5)) >>> suppression.covers(Violation(2, "long-docstring", "")), suppression.covers(Violation(2, "long-comment", "")) (True, False) >>> Suppression(line=1, rules=("long-comment",), lines=None).covers(Violation(90, "long-comment", "")) True
- static unused(
- suppressions: Iterable[Suppression],
- violations: Collection[Violation],
An
unused-ignorefor every rule a comment names without silencing anything.>>> found = [Violation(3, "long-docstring", "")] >>> stale = Suppression(line=3, rules=("long-docstring", "long-comment", "tabs"), lines=range(1, 4)) >>> [v.message for v in Suppression.unused([stale], found)] ["'long-comment' silences nothing here", "unknown rule 'tabs'"] >>> [v.message for v in Suppression.unused([Suppression(line=1, rules=(), lines=None)], found)] ['names no rule, write ignore[rule-name]']
- class CheckConfig(
- ignore: Collection[str] = (),
- per_file_ignores: dict[str,
- list[str]]=<factory>,
- root: Path = PosixPath('.'),
- final_newlines: dict[str,
- int]=<factory>,
- initial_newlines: dict[str,
- int]=<factory>,
- docstring_max_lines: int = 15,
- comment_max_lines: int = 2,
- fragment_max_words: int = 3,
- paragraph_max_lines: int = 7,
- paragraph_max_branches: int = 2,
- paragraph_max_bindings: int = 1,
Bases:
objectSettings of the
[tool.stouputils.check]table of apyproject.toml, keys spelled with dashes.>>> CheckConfig(ignore=["tab-indentation", "space-alignment"]).final_newlines {'.py': 2, '.json': 1, '.md': 2, '.yml': 2, '.yaml': 2} >>> CheckConfig().initial_newlines {'.md': 1, '.yml': 1, '.yaml': 1, '.mcfunction': 1} >>> CheckConfig(per_file_ignores={"*.json": ["tabs"]}) Traceback (most recent call last): ... ValueError: Unknown rules in ignore: ['tabs'], the known ones are banned-characters, ...
- per_file_ignores: dict[str, list[str]][source]#
Rules left unchecked in the files a glob matches, relative to
root, or anywhere when it holds no slash.
- root: Path = PosixPath('.')[source]#
Directory of the
pyproject.tomlthe settings come from, whichper_file_ignorespatterns are relative to.
- final_newlines: dict[str, int][source]#
Exact number of newline characters a file ends with, by suffix, replacing the defaults as a whole.
- initial_newlines: dict[str, int][source]#
Exact number of newline characters a file starts with, by suffix, replacing the defaults as a whole.
- docstring_max_lines: int = 15[source]#
Longest docstring of a function or a class, doctests included,
.. code-block::and.. image::directives left out.
- fragment_max_words: int = 3[source]#
Most words a clause cut by a line break may leave alone on one side of it.
- paragraph_max_lines: int = 7[source]#
Most lines a paragraph of statements may span when it also holds more than
paragraph_max_branchesof them.
- paragraph_max_branches: int = 2[source]#
Most branching or looping statements a paragraph over
paragraph_max_linesmay hold.
- paragraph_max_bindings: int = 1[source]#
Most names a paragraph over both other limits may assign at its own level, the state its reader carries along.
- ignored_rules(path: Path) set[str][source]#
Rules left unchecked in one file: the global ones and those of every
per_file_ignorespattern it matches.>>> patterns = {"tests/**": ["final-newlines"], "*.json": ["banned-characters"]} >>> config = CheckConfig(ignore=["long-comment"], per_file_ignores=patterns) >>> sorted(config.ignored_rules(Path("tests/fixture/data.json"))) ['banned-characters', 'final-newlines', 'long-comment'] >>> sorted(config.ignored_rules(Path("src/tests.py"))) ['long-comment']