no-tuple-returns 2026.12.6__tar.gz

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.
@@ -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.
@@ -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
+ [![CI](https://github.com/adamtheturtle/no-tuple-returns/actions/workflows/ci.yml/badge.svg)](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,99 @@
1
+ [![CI](https://github.com/adamtheturtle/no-tuple-returns/actions/workflows/ci.yml/badge.svg)](https://github.com/adamtheturtle/no-tuple-returns/actions/workflows/ci.yml)
2
+
3
+ # no-tuple-returns
4
+
5
+ A Python linter that forbids returning tuples, including tuples inside containers.
6
+ Use named fields when callers need to know what each part of a result means.
7
+
8
+ ```python
9
+ from dataclasses import dataclass
10
+
11
+
12
+ def coordinates():
13
+ return 51.5, -0.1 # NTR001
14
+
15
+
16
+ def route() -> list[tuple[float, float]]: # NTR001
17
+ return [coordinates()]
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Coordinate:
22
+ latitude: float
23
+ longitude: float
24
+
25
+
26
+ def named_route() -> list[Coordinate]:
27
+ return [Coordinate(latitude=51.5, longitude=-0.1)]
28
+ ```
29
+
30
+ ## Installation
31
+
32
+ Install from a release tag with Python 3.11 or later.
33
+
34
+ ```console
35
+ uv tool install 'git+https://github.com/adamtheturtle/no-tuple-returns@2026.12.6'
36
+ ```
37
+
38
+ Wheels and source distributions are also available on the
39
+ [GitHub releases page](https://github.com/adamtheturtle/no-tuple-returns/releases).
40
+
41
+ ## Usage
42
+
43
+ ```console
44
+ no-tuple-returns .
45
+ no-tuple-returns src tests
46
+ no-tuple-returns --output-format json src/example.py
47
+ no-tuple-returns --python-executable .venv/bin/python src
48
+ ```
49
+
50
+ Run it from the project root so imports resolve relative to the project and its
51
+ `src` directory. Set `MYPYPATH` for additional source roots. The
52
+ `--python-executable` option lets the checker find types from packages installed
53
+ in a separate environment.
54
+
55
+ Directory scans respect `.gitignore` and skip hidden entries. A `.pyi` stub takes
56
+ precedence over a same-named implementation during discovery. You can pass the
57
+ implementation file explicitly to check its body. The exit status is `0` for a
58
+ clean check, `1` for violations, and `2` for errors such as a missing path or
59
+ invalid Python syntax.
60
+
61
+ ## What it checks
62
+
63
+ - Return annotations and values in functions, methods, async functions, and stubs.
64
+ - Tuple expressions, tuple subclasses such as `NamedTuple`, and tuples nested
65
+ inside containers, generic types, dataclasses, or `TypedDict` fields.
66
+ - Types inferred from assignments, comprehensions, and calls, including
67
+ types provided by imports. An annotation containing a tuple is reported once
68
+ at the function definition. Otherwise, each offending return is reported.
69
+ - Generator payloads, including values emitted by `yield` and `yield from`.
70
+
71
+ The checker uses mypy's compiler interface for static type inference. It checks
72
+ the files you select and uses imported modules for type information. Regular
73
+ mypy type errors are outside this rule. Values hidden behind `Any` or `object`,
74
+ unknown dependencies, arbitrary object attributes, and runtime mutation can
75
+ limit what static inference finds.
76
+
77
+ ## Suppression
78
+
79
+ Use `# noqa: NTR001` on a `def` line to suppress a function or on a `return` or
80
+ `yield` line to suppress that expression. A standalone `# ruff: noqa: NTR001`
81
+ suppresses the entire file. When using Ruff, register the code prefix so Ruff
82
+ recognizes these directives.
83
+
84
+ ```toml
85
+ [tool.ruff.lint]
86
+ external = ["NTR"]
87
+ ```
88
+
89
+ ## pre-commit and prek
90
+
91
+ ```yaml
92
+ repos:
93
+ - repo: https://github.com/adamtheturtle/no-tuple-returns
94
+ rev: 2026.12.6
95
+ hooks:
96
+ - id: no-tuple-returns
97
+ ```
98
+
99
+ For development and verification commands, see [Contributing](CONTRIBUTING.md).
@@ -0,0 +1,73 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.13.10,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "no-tuple-returns"
7
+ version = "2026.12.6"
8
+ description = "A Python linter that forbids returning tuples, including inside containers."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ keywords = [
14
+ "lint",
15
+ "tuple",
16
+ "type-checking",
17
+ "pre-commit",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Environment :: Console",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Topic :: Software Development :: Quality Assurance",
24
+ ]
25
+ dependencies = ["mypy==2.4.1"]
26
+
27
+ [[project.authors]]
28
+ name = "Adam Dangoor"
29
+ email = "adamdangoor@gmail.com"
30
+
31
+ [project.scripts]
32
+ no-tuple-returns = "no_tuple_returns._cli:main"
33
+
34
+ [project.urls]
35
+ Source = "https://github.com/adamtheturtle/no-tuple-returns"
36
+ Issues = "https://github.com/adamtheturtle/no-tuple-returns/issues"
37
+ Changelog = "https://github.com/adamtheturtle/no-tuple-returns/blob/main/CHANGELOG.md"
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "pytest==9.1.1",
42
+ "pytest-cov==7.1.0",
43
+ "ruff==0.15.8",
44
+ "twine==6.2.0",
45
+ ]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
49
+ addopts = "--strict-config --strict-markers"
50
+
51
+ [tool.ruff]
52
+ target-version = "py311"
53
+ extend-exclude = ["tests/fixtures"]
54
+
55
+ [tool.ruff.lint]
56
+ select = [
57
+ "B",
58
+ "E",
59
+ "F",
60
+ "I",
61
+ "RUF",
62
+ "UP",
63
+ ]
64
+
65
+ [tool.mypy]
66
+ strict = true
67
+ files = [
68
+ "src",
69
+ "tests/test_cli.py",
70
+ ]
71
+
72
+ [tool.coverage.run]
73
+ patch = ["subprocess"]
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.13.10,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "no-tuple-returns"
7
+ version = "2026.12.6"
8
+ description = "A Python linter that forbids returning tuples, including inside containers."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ authors = [{ name = "Adam Dangoor", email = "adamdangoor@gmail.com" }]
14
+ keywords = ["lint", "tuple", "type-checking", "pre-commit"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Environment :: Console",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Topic :: Software Development :: Quality Assurance",
20
+ ]
21
+ # The checker uses mypy's compiler interface. Upgrade with the full CLI suite.
22
+ dependencies = ["mypy==2.4.1"]
23
+
24
+ [project.scripts]
25
+ no-tuple-returns = "no_tuple_returns._cli:main"
26
+
27
+ [project.urls]
28
+ Source = "https://github.com/adamtheturtle/no-tuple-returns"
29
+ Issues = "https://github.com/adamtheturtle/no-tuple-returns/issues"
30
+ Changelog = "https://github.com/adamtheturtle/no-tuple-returns/blob/main/CHANGELOG.md"
31
+
32
+ [dependency-groups]
33
+ dev = ["pytest==9.1.1", "pytest-cov==7.1.0", "ruff==0.15.8", "twine==6.2.0"]
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+ addopts = "--strict-config --strict-markers"
38
+
39
+ [tool.ruff]
40
+ target-version = "py311"
41
+ extend-exclude = ["tests/fixtures"]
42
+
43
+ [tool.ruff.lint]
44
+ select = ["B", "E", "F", "I", "RUF", "UP"]
45
+
46
+ [tool.mypy]
47
+ strict = true
48
+ files = ["src", "tests/test_cli.py"]
49
+
50
+ [tool.coverage.run]
51
+ patch = ["subprocess"]
@@ -0,0 +1 @@
1
+ """Check Python functions for tuple return values."""
@@ -0,0 +1,5 @@
1
+ """Run no-tuple-returns as a module."""
2
+
3
+ from no_tuple_returns._cli import main
4
+
5
+ raise SystemExit(main())
@@ -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
@@ -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))