no-tuple-returns 2026.12.6__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.
- no_tuple_returns/__init__.py +1 -0
- no_tuple_returns/__main__.py +5 -0
- no_tuple_returns/_check.py +139 -0
- no_tuple_returns/_cli.py +55 -0
- no_tuple_returns/_inference.py +247 -0
- no_tuple_returns/_noqa.py +38 -0
- no_tuple_returns-2026.12.6.dist-info/METADATA +119 -0
- no_tuple_returns-2026.12.6.dist-info/RECORD +11 -0
- no_tuple_returns-2026.12.6.dist-info/WHEEL +4 -0
- no_tuple_returns-2026.12.6.dist-info/entry_points.txt +3 -0
- no_tuple_returns-2026.12.6.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Check Python functions for tuple return values."""
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Select Python sources and report tuple return contracts and values."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from itertools import zip_longest
|
|
6
|
+
from os import devnull
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from mypy import nodes, types
|
|
10
|
+
from mypy.build import BuildSource, build
|
|
11
|
+
from mypy.find_sources import create_source_list
|
|
12
|
+
from mypy.options import Options
|
|
13
|
+
from mypy.traverser import (
|
|
14
|
+
YieldFromCollector,
|
|
15
|
+
all_return_statements,
|
|
16
|
+
all_yield_expressions,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from no_tuple_returns._inference import ReturnTypes, contains_tuple, definitions
|
|
20
|
+
from no_tuple_returns._noqa import suppressions
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, order=True)
|
|
24
|
+
class Diagnostic:
|
|
25
|
+
path: str
|
|
26
|
+
line: int
|
|
27
|
+
column: int
|
|
28
|
+
message: str
|
|
29
|
+
code: str = "NTR001"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def check(paths: list[Path], python_executable: Path | None) -> list[Diagnostic]:
|
|
33
|
+
options = Options()
|
|
34
|
+
options.export_types = True
|
|
35
|
+
options.preserve_asts = True
|
|
36
|
+
options.check_untyped_defs = True
|
|
37
|
+
options.incremental = False
|
|
38
|
+
options.cache_dir = devnull
|
|
39
|
+
options.exclude_gitignore = True
|
|
40
|
+
options.explicit_package_bases = True
|
|
41
|
+
if Path("src").is_dir():
|
|
42
|
+
options.mypy_path = [str(Path("src").resolve())]
|
|
43
|
+
if python_executable is not None:
|
|
44
|
+
options.python_executable = str(python_executable.absolute())
|
|
45
|
+
|
|
46
|
+
for path in paths:
|
|
47
|
+
if path.is_file() and path.suffix not in {".py", ".pyi"}:
|
|
48
|
+
raise ValueError(f"{path} is not a Python source file")
|
|
49
|
+
if not path.exists():
|
|
50
|
+
raise ValueError(f"{path} does not exist")
|
|
51
|
+
sources = create_source_list(
|
|
52
|
+
[str(path) for path in paths], options, allow_empty_dir=True
|
|
53
|
+
)
|
|
54
|
+
unique = {Path(source.path).resolve(): source for source in sources if source.path}
|
|
55
|
+
by_module: dict[str, list[BuildSource]] = defaultdict(list)
|
|
56
|
+
for source in unique.values():
|
|
57
|
+
by_module[source.module].append(source)
|
|
58
|
+
# The compiler accepts one source per module. When a caller explicitly
|
|
59
|
+
# supplies both an implementation and its stub, check them in separate runs.
|
|
60
|
+
return sorted(
|
|
61
|
+
{
|
|
62
|
+
report
|
|
63
|
+
for batch in zip_longest(*by_module.values())
|
|
64
|
+
for report in _check_batch(
|
|
65
|
+
[source for source in batch if source is not None], options
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _check_batch(sources: list[BuildSource], options: Options) -> list[Diagnostic]:
|
|
72
|
+
# Ordinary typing errors are outside this lint rule. Fatal analysis errors
|
|
73
|
+
# (including syntax errors) propagate to the CLI.
|
|
74
|
+
result = build(sources, options)
|
|
75
|
+
inferred = ReturnTypes(result.types)
|
|
76
|
+
reports = []
|
|
77
|
+
for source in sources:
|
|
78
|
+
if source.path is None:
|
|
79
|
+
continue
|
|
80
|
+
path = Path(source.path)
|
|
81
|
+
display_path = path.as_posix()
|
|
82
|
+
ignored = suppressions(path)
|
|
83
|
+
if ignored.whole_file:
|
|
84
|
+
continue
|
|
85
|
+
for function in definitions(result.files[source.module].defs):
|
|
86
|
+
# Methods synthesized by mypy (such as dataclass __replace__)
|
|
87
|
+
# have no source column.
|
|
88
|
+
if function.column < 0 or function.line in ignored.lines:
|
|
89
|
+
continue
|
|
90
|
+
signature = types.get_proper_type(function.type)
|
|
91
|
+
if isinstance(signature, types.CallableType) and contains_tuple(
|
|
92
|
+
signature.ret_type
|
|
93
|
+
):
|
|
94
|
+
reports.append(
|
|
95
|
+
Diagnostic(
|
|
96
|
+
display_path,
|
|
97
|
+
function.line,
|
|
98
|
+
function.column + 1,
|
|
99
|
+
f"`{function.name}` declares a return type containing a tuple",
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
continue
|
|
103
|
+
|
|
104
|
+
statements: list[nodes.ReturnStmt | nodes.YieldExpr | nodes.YieldFromExpr]
|
|
105
|
+
statements = list(all_return_statements(function))
|
|
106
|
+
if function.is_generator or function.is_async_generator:
|
|
107
|
+
statements.extend(
|
|
108
|
+
yielded for yielded, _ in all_yield_expressions(function)
|
|
109
|
+
)
|
|
110
|
+
delegated = YieldFromCollector()
|
|
111
|
+
function.accept(delegated)
|
|
112
|
+
statements.extend(
|
|
113
|
+
yielded for yielded, _ in delegated.yield_from_expressions
|
|
114
|
+
)
|
|
115
|
+
for statement in statements:
|
|
116
|
+
expression = statement.expr
|
|
117
|
+
if expression is None or any(
|
|
118
|
+
line in ignored.lines
|
|
119
|
+
for line in range(
|
|
120
|
+
statement.line,
|
|
121
|
+
max(statement.line, expression.end_line or 0) + 1,
|
|
122
|
+
)
|
|
123
|
+
):
|
|
124
|
+
continue
|
|
125
|
+
has_tuple = (
|
|
126
|
+
inferred.iterates_tuples
|
|
127
|
+
if isinstance(statement, nodes.YieldFromExpr)
|
|
128
|
+
else inferred.contains_tuple
|
|
129
|
+
)
|
|
130
|
+
if has_tuple(expression, frozenset({function})):
|
|
131
|
+
reports.append(
|
|
132
|
+
Diagnostic(
|
|
133
|
+
display_path,
|
|
134
|
+
statement.line,
|
|
135
|
+
statement.column + 1,
|
|
136
|
+
f"`{function.name}` returns a value containing a tuple",
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
return reports
|
no_tuple_returns/_cli.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
import tokenize
|
|
7
|
+
from dataclasses import asdict
|
|
8
|
+
from importlib.metadata import version
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from mypy.errors import CompileError
|
|
12
|
+
from mypy.find_sources import InvalidSourceList
|
|
13
|
+
|
|
14
|
+
from no_tuple_returns._check import check
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main() -> int:
|
|
18
|
+
parser = argparse.ArgumentParser(
|
|
19
|
+
prog="no-tuple-returns", description="Forbid tuples in Python return values."
|
|
20
|
+
)
|
|
21
|
+
parser.add_argument("--version", action="version", version=version(parser.prog))
|
|
22
|
+
parser.add_argument(
|
|
23
|
+
"--output-format", choices=["concise", "json"], default="concise"
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"--python-executable",
|
|
27
|
+
type=Path,
|
|
28
|
+
help="Python interpreter whose installed type information should be used",
|
|
29
|
+
)
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"paths", nargs="*", type=Path, help="Python files or directories"
|
|
32
|
+
)
|
|
33
|
+
args = parser.parse_args()
|
|
34
|
+
try:
|
|
35
|
+
diagnostics = check(args.paths or [Path(".")], args.python_executable)
|
|
36
|
+
except (
|
|
37
|
+
CompileError,
|
|
38
|
+
InvalidSourceList,
|
|
39
|
+
OSError,
|
|
40
|
+
SyntaxError,
|
|
41
|
+
ValueError,
|
|
42
|
+
tokenize.TokenError,
|
|
43
|
+
) as error:
|
|
44
|
+
print(f"no-tuple-returns: {error}", file=sys.stderr)
|
|
45
|
+
return 2
|
|
46
|
+
|
|
47
|
+
if args.output_format == "json":
|
|
48
|
+
print(json.dumps([asdict(diagnostic) for diagnostic in diagnostics]))
|
|
49
|
+
else:
|
|
50
|
+
for report in diagnostics:
|
|
51
|
+
print(
|
|
52
|
+
f"{report.path}:{report.line}:{report.column}: "
|
|
53
|
+
f"{report.code} {report.message}"
|
|
54
|
+
)
|
|
55
|
+
return int(bool(diagnostics))
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Read the type graph and source nodes produced by mypy."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
4
|
+
from typing import Final
|
|
5
|
+
|
|
6
|
+
from mypy import nodes, types
|
|
7
|
+
from mypy.expandtype import expand_type_by_instance
|
|
8
|
+
from mypy.maptype import map_instance_to_supertype
|
|
9
|
+
from mypy.traverser import all_return_statements
|
|
10
|
+
|
|
11
|
+
_TUPLE: Final = "builtins.tuple"
|
|
12
|
+
_ITERABLE: Final = "typing.Iterable"
|
|
13
|
+
_MAPPING: Final = "typing.Mapping"
|
|
14
|
+
_PAYLOAD_ARGUMENTS: Final = {
|
|
15
|
+
"typing.Generator": (0, 2),
|
|
16
|
+
"typing.AsyncGenerator": (0,),
|
|
17
|
+
"typing.Coroutine": (2,),
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def contains_tuple(
|
|
22
|
+
value_type: types.Type | None,
|
|
23
|
+
seen: frozenset[nodes.TypeAlias | nodes.TypeInfo] = frozenset(),
|
|
24
|
+
) -> bool:
|
|
25
|
+
if isinstance(value_type, types.TypeAliasType) and value_type.alias is not None:
|
|
26
|
+
if value_type.alias in seen:
|
|
27
|
+
return False
|
|
28
|
+
seen = seen | {value_type.alias}
|
|
29
|
+
proper = types.get_proper_type(value_type)
|
|
30
|
+
if isinstance(proper, types.TupleType):
|
|
31
|
+
return True
|
|
32
|
+
if isinstance(proper, types.Instance):
|
|
33
|
+
if proper.type.has_base(_TUPLE):
|
|
34
|
+
return True
|
|
35
|
+
fields = proper.type.metadata.get("dataclass")
|
|
36
|
+
if fields is not None:
|
|
37
|
+
return proper.type not in seen and any(
|
|
38
|
+
contains_tuple(field_type, seen | {proper.type})
|
|
39
|
+
for field_type in _dataclass_field_types(proper, fields["attributes"])
|
|
40
|
+
)
|
|
41
|
+
arguments: Iterable[types.Type] = proper.args
|
|
42
|
+
if proper.type.fullname in _PAYLOAD_ARGUMENTS:
|
|
43
|
+
arguments = (
|
|
44
|
+
proper.args[index]
|
|
45
|
+
for index in _PAYLOAD_ARGUMENTS[proper.type.fullname]
|
|
46
|
+
if index < len(proper.args)
|
|
47
|
+
)
|
|
48
|
+
elif proper.type not in seen:
|
|
49
|
+
# Container bases expose items even for views such as dict.items().
|
|
50
|
+
base = next(
|
|
51
|
+
(
|
|
52
|
+
base
|
|
53
|
+
for name in (_MAPPING, _ITERABLE)
|
|
54
|
+
for base in proper.type.mro
|
|
55
|
+
if base.fullname == name
|
|
56
|
+
),
|
|
57
|
+
None,
|
|
58
|
+
)
|
|
59
|
+
if base is not None:
|
|
60
|
+
arguments = map_instance_to_supertype(proper, base).args
|
|
61
|
+
seen = seen | {proper.type}
|
|
62
|
+
return any(contains_tuple(argument, seen) for argument in arguments)
|
|
63
|
+
if isinstance(proper, types.TypedDictType):
|
|
64
|
+
return any(contains_tuple(item, seen) for item in proper.items.values())
|
|
65
|
+
if isinstance(proper, types.UnionType):
|
|
66
|
+
return any(contains_tuple(item, seen) for item in proper.items)
|
|
67
|
+
if isinstance(proper, types.TypeVarType):
|
|
68
|
+
return any(
|
|
69
|
+
contains_tuple(item, seen)
|
|
70
|
+
for item in (proper.values or [proper.upper_bound])
|
|
71
|
+
)
|
|
72
|
+
return False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _dataclass_field_types(
|
|
76
|
+
instance: types.Instance, attributes: Iterable[Mapping[str, object]]
|
|
77
|
+
) -> Iterator[types.Type]:
|
|
78
|
+
for field in attributes:
|
|
79
|
+
name = field["name"]
|
|
80
|
+
if field["is_init_var"] or not isinstance(name, str):
|
|
81
|
+
continue
|
|
82
|
+
symbol = instance.type.get(name)
|
|
83
|
+
if symbol is None or not isinstance(symbol.node, nodes.Var):
|
|
84
|
+
continue
|
|
85
|
+
member = symbol.node
|
|
86
|
+
if member.type is not None:
|
|
87
|
+
owner = map_instance_to_supertype(instance, member.info)
|
|
88
|
+
yield expand_type_by_instance(member.type, owner)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _iterable_item_contains_tuple(value_type: types.Type | None) -> bool:
|
|
92
|
+
proper = types.get_proper_type(value_type)
|
|
93
|
+
if isinstance(proper, types.UnionType):
|
|
94
|
+
return any(_iterable_item_contains_tuple(item) for item in proper.items)
|
|
95
|
+
if isinstance(proper, types.TupleType):
|
|
96
|
+
return any(contains_tuple(item) for item in proper.items)
|
|
97
|
+
if isinstance(proper, types.Instance):
|
|
98
|
+
for base in proper.type.mro:
|
|
99
|
+
if base.fullname == _ITERABLE:
|
|
100
|
+
return any(
|
|
101
|
+
contains_tuple(item)
|
|
102
|
+
for item in map_instance_to_supertype(proper, base).args
|
|
103
|
+
)
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def function_for(node: nodes.Node | None) -> nodes.FuncDef | None:
|
|
108
|
+
if isinstance(node, nodes.Decorator):
|
|
109
|
+
return node.func
|
|
110
|
+
if isinstance(node, nodes.FuncDef):
|
|
111
|
+
return node
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def definitions(statements: Iterable[nodes.Statement]) -> Iterator[nodes.FuncDef]:
|
|
116
|
+
for statement in statements:
|
|
117
|
+
function = function_for(statement)
|
|
118
|
+
if function is not None:
|
|
119
|
+
yield function
|
|
120
|
+
yield from definitions(function.body.body)
|
|
121
|
+
elif isinstance(statement, nodes.OverloadedFuncDef):
|
|
122
|
+
yield from definitions(statement.items)
|
|
123
|
+
if statement.impl is not None:
|
|
124
|
+
yield from definitions([statement.impl])
|
|
125
|
+
else:
|
|
126
|
+
for body in _blocks(statement):
|
|
127
|
+
if not body.is_unreachable:
|
|
128
|
+
yield from definitions(body.body)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _blocks(statement: nodes.Statement) -> Iterable[nodes.Block]:
|
|
132
|
+
match statement:
|
|
133
|
+
case nodes.IfStmt():
|
|
134
|
+
return [*statement.body, *_optional_block(statement.else_body)]
|
|
135
|
+
case nodes.TryStmt():
|
|
136
|
+
return [
|
|
137
|
+
statement.body,
|
|
138
|
+
*statement.handlers,
|
|
139
|
+
*_optional_block(statement.else_body),
|
|
140
|
+
*_optional_block(statement.finally_body),
|
|
141
|
+
]
|
|
142
|
+
case nodes.ForStmt() | nodes.WhileStmt():
|
|
143
|
+
return [statement.body, *_optional_block(statement.else_body)]
|
|
144
|
+
case nodes.WithStmt():
|
|
145
|
+
return [statement.body]
|
|
146
|
+
case nodes.MatchStmt():
|
|
147
|
+
return statement.bodies
|
|
148
|
+
case nodes.ClassDef():
|
|
149
|
+
return [statement.defs]
|
|
150
|
+
case _:
|
|
151
|
+
return []
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _optional_block(block: nodes.Block | None) -> Iterable[nodes.Block]:
|
|
155
|
+
return [] if block is None else [block]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class ReturnTypes:
|
|
159
|
+
def __init__(self, expression_types: Mapping[nodes.Expression, types.Type]) -> None:
|
|
160
|
+
self._types = expression_types
|
|
161
|
+
|
|
162
|
+
def contains_tuple(
|
|
163
|
+
self,
|
|
164
|
+
expression: nodes.Expression,
|
|
165
|
+
active: frozenset[nodes.FuncDef],
|
|
166
|
+
) -> bool:
|
|
167
|
+
if isinstance(expression, nodes.TupleExpr) or contains_tuple(
|
|
168
|
+
self._types.get(expression)
|
|
169
|
+
):
|
|
170
|
+
return True
|
|
171
|
+
if isinstance(expression, (nodes.ListExpr, nodes.SetExpr)):
|
|
172
|
+
return self.iterates_tuples(expression, active)
|
|
173
|
+
return self._untyped_call_contains_tuple(expression, active) or any(
|
|
174
|
+
self.contains_tuple(part, active) for part in _payload(expression)
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def iterates_tuples(
|
|
178
|
+
self, expression: nodes.Expression, active: frozenset[nodes.FuncDef]
|
|
179
|
+
) -> bool:
|
|
180
|
+
# Iterating or unpacking a tuple exposes its members.
|
|
181
|
+
if isinstance(expression, (nodes.TupleExpr, nodes.ListExpr, nodes.SetExpr)):
|
|
182
|
+
return any(
|
|
183
|
+
self.iterates_tuples(item.expr, active)
|
|
184
|
+
if isinstance(item, nodes.StarExpr)
|
|
185
|
+
else self.contains_tuple(item, active)
|
|
186
|
+
for item in expression.items
|
|
187
|
+
)
|
|
188
|
+
return _iterable_item_contains_tuple(self._types.get(expression))
|
|
189
|
+
|
|
190
|
+
def _untyped_call_contains_tuple(
|
|
191
|
+
self, expression: nodes.Expression, active: frozenset[nodes.FuncDef]
|
|
192
|
+
) -> bool:
|
|
193
|
+
# Follow direct calls to visible untyped functions, using a call stack
|
|
194
|
+
# so recursive helpers terminate.
|
|
195
|
+
if not isinstance(
|
|
196
|
+
types.get_proper_type(self._types.get(expression)), types.AnyType
|
|
197
|
+
):
|
|
198
|
+
return False
|
|
199
|
+
call = (
|
|
200
|
+
expression.expr if isinstance(expression, nodes.AwaitExpr) else expression
|
|
201
|
+
)
|
|
202
|
+
if not isinstance(call, nodes.CallExpr) or not isinstance(
|
|
203
|
+
call.callee, nodes.RefExpr
|
|
204
|
+
):
|
|
205
|
+
return False
|
|
206
|
+
target = call.callee.node
|
|
207
|
+
if (
|
|
208
|
+
not isinstance(target, nodes.FuncDef)
|
|
209
|
+
or target.is_decorated
|
|
210
|
+
or target.is_generator
|
|
211
|
+
or target in active
|
|
212
|
+
):
|
|
213
|
+
return False
|
|
214
|
+
return any(
|
|
215
|
+
statement.expr is not None
|
|
216
|
+
and self.contains_tuple(statement.expr, active | {target})
|
|
217
|
+
for statement in all_return_statements(target)
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _payload(expression: nodes.Expression) -> Iterable[nodes.Expression]:
|
|
222
|
+
# Inference may widen heterogeneous literals to object. Check their
|
|
223
|
+
# actual members, without descending into arbitrary call arguments.
|
|
224
|
+
match expression:
|
|
225
|
+
case nodes.DictExpr():
|
|
226
|
+
return [
|
|
227
|
+
part
|
|
228
|
+
for key, value in expression.items
|
|
229
|
+
for part in (key, value)
|
|
230
|
+
if part is not None
|
|
231
|
+
]
|
|
232
|
+
case nodes.ConditionalExpr():
|
|
233
|
+
return [expression.if_expr, expression.else_expr]
|
|
234
|
+
case nodes.AssignmentExpr():
|
|
235
|
+
return [expression.value]
|
|
236
|
+
case nodes.CallExpr(analyzed=nodes.CastExpr(expr=nodes.Expression() as value)):
|
|
237
|
+
return [value]
|
|
238
|
+
case nodes.ListComprehension() | nodes.SetComprehension():
|
|
239
|
+
return [expression.generator.left_expr]
|
|
240
|
+
case nodes.GeneratorExpr():
|
|
241
|
+
return [expression.left_expr]
|
|
242
|
+
case nodes.DictionaryComprehension():
|
|
243
|
+
return [
|
|
244
|
+
item for item in (expression.key, expression.value) if item is not None
|
|
245
|
+
]
|
|
246
|
+
case _:
|
|
247
|
+
return []
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Read suppression directives from Python comment tokens."""
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import re
|
|
5
|
+
import tokenize
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
_DIRECTIVE = re.compile(r"^#\s*(?:(?:ruff|flake8)\s*:\s*)?noqa\b(.*)", re.I)
|
|
10
|
+
_GLOBAL = re.compile(r"^#\s*(?:ruff|flake8)\s*:", re.I)
|
|
11
|
+
_CODE = re.compile(r"\b[A-Z]+[0-9]+\b")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Suppressions:
|
|
16
|
+
whole_file: bool
|
|
17
|
+
lines: frozenset[int]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def suppressions(path: Path) -> Suppressions:
|
|
21
|
+
with tokenize.open(path) as source_file:
|
|
22
|
+
source = source_file.read()
|
|
23
|
+
lines = set()
|
|
24
|
+
for token in tokenize.generate_tokens(io.StringIO(source).readline):
|
|
25
|
+
if token.type != tokenize.COMMENT:
|
|
26
|
+
continue
|
|
27
|
+
match = _DIRECTIVE.match(token.string)
|
|
28
|
+
if match is None:
|
|
29
|
+
continue
|
|
30
|
+
tail = match[1].lstrip()
|
|
31
|
+
if tail.startswith(":") and "NTR001" not in _CODE.findall(
|
|
32
|
+
tail[1:].split("#", 1)[0].upper()
|
|
33
|
+
):
|
|
34
|
+
continue
|
|
35
|
+
if _GLOBAL.match(token.string) and not token.line[: token.start[1]].strip():
|
|
36
|
+
return Suppressions(whole_file=True, lines=frozenset())
|
|
37
|
+
lines.add(token.start[0])
|
|
38
|
+
return Suppressions(whole_file=False, lines=frozenset(lines))
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: no-tuple-returns
|
|
3
|
+
Version: 2026.12.6
|
|
4
|
+
Summary: A Python linter that forbids returning tuples, including inside containers.
|
|
5
|
+
Keywords: lint,tuple,type-checking,pre-commit
|
|
6
|
+
Author: Adam Dangoor
|
|
7
|
+
Author-email: Adam Dangoor <adamdangoor@gmail.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
14
|
+
Requires-Dist: mypy==2.4.1
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Project-URL: Source, https://github.com/adamtheturtle/no-tuple-returns
|
|
17
|
+
Project-URL: Issues, https://github.com/adamtheturtle/no-tuple-returns/issues
|
|
18
|
+
Project-URL: Changelog, https://github.com/adamtheturtle/no-tuple-returns/blob/main/CHANGELOG.md
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
[](https://github.com/adamtheturtle/no-tuple-returns/actions/workflows/ci.yml)
|
|
22
|
+
|
|
23
|
+
# no-tuple-returns
|
|
24
|
+
|
|
25
|
+
A Python linter that forbids returning tuples, including tuples inside containers.
|
|
26
|
+
Use named fields when callers need to know what each part of a result means.
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def coordinates():
|
|
33
|
+
return 51.5, -0.1 # NTR001
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def route() -> list[tuple[float, float]]: # NTR001
|
|
37
|
+
return [coordinates()]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class Coordinate:
|
|
42
|
+
latitude: float
|
|
43
|
+
longitude: float
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def named_route() -> list[Coordinate]:
|
|
47
|
+
return [Coordinate(latitude=51.5, longitude=-0.1)]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
Install from a release tag with Python 3.11 or later.
|
|
53
|
+
|
|
54
|
+
```console
|
|
55
|
+
uv tool install 'git+https://github.com/adamtheturtle/no-tuple-returns@2026.12.6'
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Wheels and source distributions are also available on the
|
|
59
|
+
[GitHub releases page](https://github.com/adamtheturtle/no-tuple-returns/releases).
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
```console
|
|
64
|
+
no-tuple-returns .
|
|
65
|
+
no-tuple-returns src tests
|
|
66
|
+
no-tuple-returns --output-format json src/example.py
|
|
67
|
+
no-tuple-returns --python-executable .venv/bin/python src
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Run it from the project root so imports resolve relative to the project and its
|
|
71
|
+
`src` directory. Set `MYPYPATH` for additional source roots. The
|
|
72
|
+
`--python-executable` option lets the checker find types from packages installed
|
|
73
|
+
in a separate environment.
|
|
74
|
+
|
|
75
|
+
Directory scans respect `.gitignore` and skip hidden entries. A `.pyi` stub takes
|
|
76
|
+
precedence over a same-named implementation during discovery. You can pass the
|
|
77
|
+
implementation file explicitly to check its body. The exit status is `0` for a
|
|
78
|
+
clean check, `1` for violations, and `2` for errors such as a missing path or
|
|
79
|
+
invalid Python syntax.
|
|
80
|
+
|
|
81
|
+
## What it checks
|
|
82
|
+
|
|
83
|
+
- Return annotations and values in functions, methods, async functions, and stubs.
|
|
84
|
+
- Tuple expressions, tuple subclasses such as `NamedTuple`, and tuples nested
|
|
85
|
+
inside containers, generic types, dataclasses, or `TypedDict` fields.
|
|
86
|
+
- Types inferred from assignments, comprehensions, and calls, including
|
|
87
|
+
types provided by imports. An annotation containing a tuple is reported once
|
|
88
|
+
at the function definition. Otherwise, each offending return is reported.
|
|
89
|
+
- Generator payloads, including values emitted by `yield` and `yield from`.
|
|
90
|
+
|
|
91
|
+
The checker uses mypy's compiler interface for static type inference. It checks
|
|
92
|
+
the files you select and uses imported modules for type information. Regular
|
|
93
|
+
mypy type errors are outside this rule. Values hidden behind `Any` or `object`,
|
|
94
|
+
unknown dependencies, arbitrary object attributes, and runtime mutation can
|
|
95
|
+
limit what static inference finds.
|
|
96
|
+
|
|
97
|
+
## Suppression
|
|
98
|
+
|
|
99
|
+
Use `# noqa: NTR001` on a `def` line to suppress a function or on a `return` or
|
|
100
|
+
`yield` line to suppress that expression. A standalone `# ruff: noqa: NTR001`
|
|
101
|
+
suppresses the entire file. When using Ruff, register the code prefix so Ruff
|
|
102
|
+
recognizes these directives.
|
|
103
|
+
|
|
104
|
+
```toml
|
|
105
|
+
[tool.ruff.lint]
|
|
106
|
+
external = ["NTR"]
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## pre-commit and prek
|
|
110
|
+
|
|
111
|
+
```yaml
|
|
112
|
+
repos:
|
|
113
|
+
- repo: https://github.com/adamtheturtle/no-tuple-returns
|
|
114
|
+
rev: 2026.12.6
|
|
115
|
+
hooks:
|
|
116
|
+
- id: no-tuple-returns
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
For development and verification commands, see [Contributing](CONTRIBUTING.md).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
no_tuple_returns/__init__.py,sha256=j4Vvo4OpZiwOdYcGysZcEncplq4DC7UmNSXxz_ZMhrk,54
|
|
2
|
+
no_tuple_returns/__main__.py,sha256=Zzgh1BRtcBBXRE42557Ah8SymKkXxTlUwV2fjwD9vy0,106
|
|
3
|
+
no_tuple_returns/_check.py,sha256=tUoqY49kGurEUmkzb4d9rnQ4CrU2UK5VEixQtSRRB7w,5270
|
|
4
|
+
no_tuple_returns/_cli.py,sha256=YPNGXg7OSEShwiGo5_uG4dBTn3TtuOJAaBoTNLMK9_8,1627
|
|
5
|
+
no_tuple_returns/_inference.py,sha256=SzIi8R8cB-AXTNyCeOWAtIf1bPTwtu28H5LOLaVkRAk,9346
|
|
6
|
+
no_tuple_returns/_noqa.py,sha256=ew2ewlIFZ7MjOIIZw4oNVW8zPnSk6TCErZrUP5CyefY,1234
|
|
7
|
+
no_tuple_returns-2026.12.6.dist-info/licenses/LICENSE,sha256=cnfgEzv8YMudbgPysNfgAdqeOo4zf0y2C3Ctw4RgEE4,1069
|
|
8
|
+
no_tuple_returns-2026.12.6.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
|
|
9
|
+
no_tuple_returns-2026.12.6.dist-info/entry_points.txt,sha256=DWA8MKXBf2knammkbGOfSN0vOUHKu4NzQoUL7Y3lbWU,65
|
|
10
|
+
no_tuple_returns-2026.12.6.dist-info/METADATA,sha256=qx1YPjNfPPjQiV_N17bRUPyj5CyiBjov-Fm8XQsFmAg,4135
|
|
11
|
+
no_tuple_returns-2026.12.6.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Adam Dangoor
|
|
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.
|