flake8-sections 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flake8_sections/__init__.py +1 -0
- flake8_sections/checker.py +138 -0
- flake8_sections/nodes.py +85 -0
- flake8_sections/py.typed +0 -0
- flake8_sections-0.1.0.dist-info/METADATA +77 -0
- flake8_sections-0.1.0.dist-info/RECORD +9 -0
- flake8_sections-0.1.0.dist-info/WHEEL +4 -0
- flake8_sections-0.1.0.dist-info/entry_points.txt +3 -0
- flake8_sections-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""flake8 plugin that checks blank lines between the logical sections of a function body."""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""flake8 checker for blank lines between the sections of a function body."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import ast
|
|
5
|
+
import itertools
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import ClassVar
|
|
9
|
+
|
|
10
|
+
from flake8.options.manager import OptionManager
|
|
11
|
+
|
|
12
|
+
from flake8_sections.nodes import COMPOUND, FUNCTION, KINDS, blocks, end, feeds, is_attribute_init, is_docstring, start
|
|
13
|
+
|
|
14
|
+
DEFAULT_MAX_SECTION_LINES = 9
|
|
15
|
+
|
|
16
|
+
SEC101 = "SEC101 missing blank line before {kind} statement"
|
|
17
|
+
SEC102 = "SEC102 missing blank line after {kind} block on line {line}"
|
|
18
|
+
SEC103 = "SEC103 missing blank line before return"
|
|
19
|
+
SEC201 = "SEC201 {count} lines without a blank line; split into sections (max {limit})"
|
|
20
|
+
SEC301 = "SEC301 blank line after def"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class Finding:
|
|
25
|
+
line: int
|
|
26
|
+
col: int
|
|
27
|
+
message: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Checker:
|
|
31
|
+
max_section_lines: ClassVar[int] = DEFAULT_MAX_SECTION_LINES
|
|
32
|
+
|
|
33
|
+
def __init__(self, tree: ast.AST, lines: list[str]) -> None:
|
|
34
|
+
self.tree = tree
|
|
35
|
+
self.lines = lines
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def add_options(cls, parser: OptionManager) -> None:
|
|
39
|
+
parser.add_option(
|
|
40
|
+
"--max-section-lines",
|
|
41
|
+
type=int,
|
|
42
|
+
default=DEFAULT_MAX_SECTION_LINES,
|
|
43
|
+
parse_from_config=True,
|
|
44
|
+
help="longest run of non-blank lines allowed in a function body (default %(default)s)",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def parse_options(cls, options: argparse.Namespace) -> None:
|
|
49
|
+
cls.max_section_lines = options.max_section_lines
|
|
50
|
+
|
|
51
|
+
def run(self) -> Iterator[tuple[int, int, str, type["Checker"]]]:
|
|
52
|
+
for node in ast.walk(self.tree):
|
|
53
|
+
if isinstance(node, FUNCTION):
|
|
54
|
+
for finding in self._check_function(node):
|
|
55
|
+
yield finding.line, finding.col, finding.message, type(self)
|
|
56
|
+
|
|
57
|
+
def _blank(self, lineno: int) -> bool:
|
|
58
|
+
return not self.lines[lineno - 1].strip()
|
|
59
|
+
|
|
60
|
+
def _blank_between(self, first: int, last: int) -> bool:
|
|
61
|
+
return any(self._blank(n) for n in range(first, last + 1))
|
|
62
|
+
|
|
63
|
+
def _check_function(self, func: ast.FunctionDef | ast.AsyncFunctionDef) -> Iterator[Finding]:
|
|
64
|
+
first = func.body[0]
|
|
65
|
+
above = start(first) - 1
|
|
66
|
+
while above > func.lineno and (self._blank(above) or self.lines[above - 1].lstrip().startswith("#")):
|
|
67
|
+
if self._blank(above):
|
|
68
|
+
yield Finding(start(first), first.col_offset, SEC301)
|
|
69
|
+
break
|
|
70
|
+
|
|
71
|
+
above -= 1
|
|
72
|
+
|
|
73
|
+
body = func.body[1:] if is_docstring(first) else func.body
|
|
74
|
+
yield from self._check_block(body)
|
|
75
|
+
|
|
76
|
+
def _check_block(self, block: list[ast.stmt]) -> Iterator[Finding]:
|
|
77
|
+
for prev, nxt in itertools.pairwise(block):
|
|
78
|
+
if not self._blank_between(end(prev) + 1, start(nxt) - 1):
|
|
79
|
+
finding = self._check_gap(prev, nxt, pair_only=len(block) == 2)
|
|
80
|
+
if finding:
|
|
81
|
+
yield finding
|
|
82
|
+
|
|
83
|
+
yield from self._check_runs(block)
|
|
84
|
+
|
|
85
|
+
for stmt in block:
|
|
86
|
+
if not isinstance(stmt, (*FUNCTION, ast.ClassDef)):
|
|
87
|
+
for inner in blocks(stmt):
|
|
88
|
+
yield from self._check_block(inner)
|
|
89
|
+
|
|
90
|
+
def _check_gap(self, prev: ast.stmt, nxt: ast.stmt, *, pair_only: bool) -> Finding | None:
|
|
91
|
+
if isinstance(prev, COMPOUND):
|
|
92
|
+
return Finding(start(nxt), nxt.col_offset, SEC102.format(kind=KINDS[type(prev)], line=prev.lineno))
|
|
93
|
+
|
|
94
|
+
if isinstance(nxt, COMPOUND) and not feeds(prev, nxt):
|
|
95
|
+
return Finding(start(nxt), nxt.col_offset, SEC101.format(kind=KINDS[type(nxt)]))
|
|
96
|
+
|
|
97
|
+
if isinstance(nxt, ast.Return) and (feeds(prev, nxt) or not pair_only):
|
|
98
|
+
return Finding(nxt.lineno, nxt.col_offset, SEC103)
|
|
99
|
+
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
def _check_runs(self, block: list[ast.stmt]) -> Iterator[Finding]:
|
|
103
|
+
run: list[ast.stmt] = []
|
|
104
|
+
|
|
105
|
+
for stmt in block:
|
|
106
|
+
simple = not isinstance(stmt, COMPOUND)
|
|
107
|
+
if simple and run and not self._blank_between(end(run[-1]) + 1, stmt.lineno - 1):
|
|
108
|
+
run.append(stmt)
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
finding = self._check_run(run)
|
|
112
|
+
if finding:
|
|
113
|
+
yield finding
|
|
114
|
+
|
|
115
|
+
run = [stmt] if simple else []
|
|
116
|
+
|
|
117
|
+
finding = self._check_run(run)
|
|
118
|
+
if finding:
|
|
119
|
+
yield finding
|
|
120
|
+
|
|
121
|
+
def _check_run(self, run: list[ast.stmt]) -> Finding | None:
|
|
122
|
+
if len(run) < 2 or is_attribute_init(run):
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
inside_strings = {
|
|
126
|
+
n
|
|
127
|
+
for stmt in run
|
|
128
|
+
for node in ast.walk(stmt)
|
|
129
|
+
if isinstance(node, ast.Constant | ast.JoinedStr) and node.end_lineno and node.end_lineno > node.lineno
|
|
130
|
+
for n in range(node.lineno + 1, node.end_lineno + 1)
|
|
131
|
+
}
|
|
132
|
+
lines = range(run[0].lineno, end(run[-1]) + 1)
|
|
133
|
+
count = sum(not self._blank(n) and n not in inside_strings for n in lines)
|
|
134
|
+
|
|
135
|
+
if count <= self.max_section_lines:
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
return Finding(run[0].lineno, run[0].col_offset, SEC201.format(count=count, limit=self.max_section_lines))
|
flake8_sections/nodes.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""AST helpers for locating statements and the names they assign."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
|
|
6
|
+
KINDS: dict[type[ast.stmt], str] = {
|
|
7
|
+
ast.If: "if",
|
|
8
|
+
ast.For: "for",
|
|
9
|
+
ast.AsyncFor: "for",
|
|
10
|
+
ast.While: "while",
|
|
11
|
+
ast.With: "with",
|
|
12
|
+
ast.AsyncWith: "with",
|
|
13
|
+
ast.Try: "try",
|
|
14
|
+
ast.TryStar: "try",
|
|
15
|
+
ast.Match: "match",
|
|
16
|
+
ast.FunctionDef: "def",
|
|
17
|
+
ast.AsyncFunctionDef: "def",
|
|
18
|
+
ast.ClassDef: "class",
|
|
19
|
+
}
|
|
20
|
+
COMPOUND = tuple(KINDS)
|
|
21
|
+
FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def start(stmt: ast.stmt) -> int:
|
|
25
|
+
if isinstance(stmt, (*FUNCTION, ast.ClassDef)) and stmt.decorator_list:
|
|
26
|
+
return stmt.decorator_list[0].lineno
|
|
27
|
+
|
|
28
|
+
return stmt.lineno
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def end(stmt: ast.stmt) -> int:
|
|
32
|
+
return stmt.end_lineno or stmt.lineno
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def blocks(stmt: ast.stmt) -> Iterator[list[ast.stmt]]:
|
|
36
|
+
for field in ("body", "orelse", "finalbody"):
|
|
37
|
+
block = getattr(stmt, field, None)
|
|
38
|
+
if block:
|
|
39
|
+
yield block
|
|
40
|
+
|
|
41
|
+
for handler in getattr(stmt, "handlers", []):
|
|
42
|
+
yield handler.body
|
|
43
|
+
|
|
44
|
+
for case in getattr(stmt, "cases", []):
|
|
45
|
+
yield case.body
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def assigned_names(stmt: ast.stmt) -> set[str]:
|
|
49
|
+
match stmt:
|
|
50
|
+
case ast.Assign(targets=targets):
|
|
51
|
+
nodes: list[ast.expr] = targets
|
|
52
|
+
case ast.AnnAssign(target=target) | ast.AugAssign(target=target):
|
|
53
|
+
nodes = [target]
|
|
54
|
+
case _:
|
|
55
|
+
return set()
|
|
56
|
+
|
|
57
|
+
if any(isinstance(n, ast.Attribute | ast.Subscript) for t in nodes for n in ast.walk(t)):
|
|
58
|
+
return set()
|
|
59
|
+
|
|
60
|
+
return {n.id for t in nodes for n in ast.walk(t) if isinstance(n, ast.Name)}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def feeds(prev: ast.stmt, nxt: ast.stmt) -> bool:
|
|
64
|
+
used = {n.id for n in ast.walk(nxt) if isinstance(n, ast.Name)}
|
|
65
|
+
|
|
66
|
+
return bool(assigned_names(prev) & used)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_docstring(stmt: ast.stmt) -> bool:
|
|
70
|
+
return isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, str)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_attribute_init(run: list[ast.stmt]) -> bool:
|
|
74
|
+
bases: set[str] = set()
|
|
75
|
+
|
|
76
|
+
for stmt in run:
|
|
77
|
+
match stmt:
|
|
78
|
+
case ast.Assign(targets=[ast.Attribute(value=ast.Name(id=base))]):
|
|
79
|
+
bases.add(base)
|
|
80
|
+
case ast.AnnAssign(target=ast.Attribute(value=ast.Name(id=base))):
|
|
81
|
+
bases.add(base)
|
|
82
|
+
case _:
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
return len(bases) == 1
|
flake8_sections/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: flake8-sections
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: flake8 plugin that checks blank lines between the logical sections of a function body
|
|
5
|
+
Keywords: flake8,flake8-plugin,linter,pep8,blank-lines,readability
|
|
6
|
+
Author: axiom-nz
|
|
7
|
+
Author-email: axiom-nz <2497193+axiom-nz@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Framework :: Flake8
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
23
|
+
Requires-Dist: flake8>=7.5.0
|
|
24
|
+
Requires-Python: >=3.12
|
|
25
|
+
Project-URL: Repository, https://github.com/axiom-nz/flake8-sections
|
|
26
|
+
Project-URL: Issues, https://github.com/axiom-nz/flake8-sections/issues
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# flake8-sections
|
|
30
|
+
|
|
31
|
+
A flake8 plugin that checks the blank lines between the logical sections of a function body.
|
|
32
|
+
It only looks inside functions; module and class level spacing is left to ruff's E30x rules.
|
|
33
|
+
|
|
34
|
+
| Code | Finds |
|
|
35
|
+
|---|---|
|
|
36
|
+
| SEC101 | No blank line before a compound statement (`if`, `for`, `while`, `with`, `try`, `match`, nested `def`/`class`). Exempt when the previous statement assigns a name the statement uses anywhere (`first = ...` over `if not first:`, `acc = 0` over `for`). |
|
|
37
|
+
| SEC102 | No blank line after a compound block. Covers consecutive `if`s and a `return` after a block. |
|
|
38
|
+
| SEC103 | No blank line before `return`, unless it opens its block or the block is two statements (`print(...)` then `return 7`). `x = ...` then `return x` is still flagged. |
|
|
39
|
+
| SEC201 | A run of more than `--max-section-lines` (default 9) non-blank lines of two or more simple statements. A multi-line string counts as one line. A single long statement, the docstring and a `self.x = ...` init list are exempt. |
|
|
40
|
+
| SEC301 | A blank line between `def` and the first statement. |
|
|
41
|
+
|
|
42
|
+
Consecutive `assert`s and other simple statements are only limited by SEC201.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install flake8-sections
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Use alongside ruff
|
|
51
|
+
|
|
52
|
+
Select only `SEC`, so flake8's own pycodestyle and pyflakes checks don't duplicate ruff:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
uvx --with flake8-sections flake8 --require-plugins flake8-sections --select=SEC src tests
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
pre-commit:
|
|
59
|
+
|
|
60
|
+
```yaml
|
|
61
|
+
- repo: local
|
|
62
|
+
hooks:
|
|
63
|
+
- id: flake8-sections
|
|
64
|
+
name: flake8-sections
|
|
65
|
+
entry: flake8 --require-plugins flake8-sections --select=SEC
|
|
66
|
+
language: python
|
|
67
|
+
types: [python]
|
|
68
|
+
additional_dependencies: [flake8-sections]
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Add `external = ["SEC"]` under `[tool.ruff.lint]` so RUF102 (preview) accepts `# noqa: SEC102` comments. Without `--require-plugins`, flake8 exits 0 when the plugin is missing.
|
|
72
|
+
|
|
73
|
+
## Develop
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
uv run pytest && uv run ruff check && uv run mypy && uv run flake8 --select=SEC src tests
|
|
77
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
flake8_sections/__init__.py,sha256=3ixpW3YlmnLfZNCAS8Pnmrm8gAU3fYPTUCssbhguP54,93
|
|
2
|
+
flake8_sections/checker.py,sha256=9J5AaJPr7u2Xycv4aozZa4N5o0B9OOIHkS5EsqOKX7s,5047
|
|
3
|
+
flake8_sections/nodes.py,sha256=cIlRwfqc0a9VMkg8b56wxMu83M-qFXKz9LjYD7F76Hs,2366
|
|
4
|
+
flake8_sections/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
flake8_sections-0.1.0.dist-info/licenses/LICENSE,sha256=ZR6ziqllXtkE8ez1s6hf0X787aaxk-2BltLSm-cmfZ8,1065
|
|
6
|
+
flake8_sections-0.1.0.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
|
|
7
|
+
flake8_sections-0.1.0.dist-info/entry_points.txt,sha256=_vpVRv7v3s19sUagx7PGC8r3wrlmnh_dnrubfLF0ywM,58
|
|
8
|
+
flake8_sections-0.1.0.dist-info/METADATA,sha256=yQX7XTMt3k_WlCMrIgZffD-7vDLtwBO8FSqoJ_aLwCE,3219
|
|
9
|
+
flake8_sections-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 axiom-nz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|