assert-python-definition-is-used 20260823031322__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.
@@ -0,0 +1 @@
1
+ """Assert that every public Python definition in a tree is named somewhere else."""
@@ -0,0 +1,5 @@
1
+ """Entry point for running as python -m assert_python_definition_is_used."""
2
+
3
+ from .cli import main
4
+
5
+ main()
@@ -0,0 +1,408 @@
1
+ """Command-line interface for assert-python-definition-is-used."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import fnmatch
7
+ import glob
8
+ import os
9
+ import sys
10
+ from dataclasses import dataclass, field
11
+ from typing import TYPE_CHECKING
12
+
13
+ from .scanner import Definition, Finding, public_definitions, unused_definitions
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Sequence
17
+
18
+ EXIT_SUCCESS = 0
19
+ EXIT_FINDINGS = 1
20
+ EXIT_ERROR = 2
21
+
22
+ GLOB_CHARACTERS = ("*", "?", "[")
23
+
24
+
25
+ @dataclass
26
+ class ScanResult:
27
+ """The outcome of one run over a set of trees."""
28
+
29
+ findings: list[Finding] = field(default_factory=list)
30
+ definitions_read: int = 0
31
+ files_scanned: int = 0
32
+ had_error: bool = False
33
+
34
+
35
+ def create_parser() -> argparse.ArgumentParser:
36
+ """Create the argument parser for the CLI."""
37
+ parser = argparse.ArgumentParser(
38
+ prog="assert-python-definition-is-used",
39
+ description=(
40
+ "Assert that every public top-level definition in the given trees is named "
41
+ "somewhere else. A definition whose last caller was deleted keeps its tests, "
42
+ "keeps its coverage and is never called again, so nothing else reports it."
43
+ ),
44
+ )
45
+
46
+ parser.add_argument(
47
+ "trees",
48
+ nargs="+",
49
+ metavar="TREE",
50
+ help=(
51
+ "One or more file paths, directory paths, or glob patterns holding the "
52
+ "definitions to check. Directories are read recursively for *.py files."
53
+ ),
54
+ )
55
+
56
+ parser.add_argument(
57
+ "--consumer",
58
+ action="append",
59
+ default=None,
60
+ metavar="PATH",
61
+ dest="consumers",
62
+ help=(
63
+ "A tree to search for uses, repeatable. Defaults to the definition trees, "
64
+ "so pass it for every other place a caller may live."
65
+ ),
66
+ )
67
+
68
+ parser.add_argument(
69
+ "--own-tests",
70
+ metavar="TEMPLATE",
71
+ help=(
72
+ "A path template containing {package} whose files do not count as users, "
73
+ "such as 'test/lib/python/test_{package}'. Without it a module held at full "
74
+ "coverage by its own tests always reads as used."
75
+ ),
76
+ )
77
+
78
+ parser.add_argument(
79
+ "--count-defining-file",
80
+ action="store_true",
81
+ help=(
82
+ "Count a name written elsewhere in its own defining file as a use. Off by "
83
+ "default, because a docstring example, an __all__ entry and a call from a "
84
+ "function that is itself dead all read alike."
85
+ ),
86
+ )
87
+
88
+ parser.add_argument(
89
+ "--exclude",
90
+ metavar="PATTERNS",
91
+ help="Comma-separated glob patterns to exclude files, from both trees.",
92
+ )
93
+
94
+ output_group = parser.add_mutually_exclusive_group()
95
+ output_group.add_argument(
96
+ "--quiet",
97
+ action="store_true",
98
+ help="Suppress all output. Exit code indicates success (0) or findings (1).",
99
+ )
100
+ output_group.add_argument(
101
+ "--count",
102
+ action="store_true",
103
+ help="Output only the count of findings.",
104
+ )
105
+ output_group.add_argument(
106
+ "--verbose",
107
+ action="store_true",
108
+ help="Show trees read, definitions found, findings and a summary.",
109
+ )
110
+
111
+ behavior_group = parser.add_mutually_exclusive_group()
112
+ behavior_group.add_argument(
113
+ "--fail-fast",
114
+ action="store_true",
115
+ help="Exit immediately after finding the first unused definition.",
116
+ )
117
+ behavior_group.add_argument(
118
+ "--warn-only",
119
+ action="store_true",
120
+ help="Always exit with code 0, even if findings exist.",
121
+ )
122
+
123
+ return parser
124
+
125
+
126
+ def parse_patterns(patterns_str: str | None) -> list[str]:
127
+ """Parse a comma-separated patterns string.
128
+
129
+ Args:
130
+ patterns_str: Comma-separated patterns, or None.
131
+
132
+ Returns:
133
+ The patterns, empty when the input is None or blank.
134
+ """
135
+ if not patterns_str:
136
+ return []
137
+ return [pattern.strip() for pattern in patterns_str.split(",") if pattern.strip()]
138
+
139
+
140
+ def _is_glob_pattern(path: str) -> bool:
141
+ """Check whether a path holds glob wildcard characters."""
142
+ return any(character in path for character in GLOB_CHARACTERS)
143
+
144
+
145
+ def _walk_python_files(directory: str) -> list[str]:
146
+ """Find every *.py file under a directory, ignoring hidden directories."""
147
+ found: list[str] = []
148
+ for root, directories, filenames in os.walk(directory):
149
+ directories[:] = [name for name in directories if not name.startswith(".")]
150
+ found.extend(
151
+ os.path.join(root, filename) for filename in filenames if filename.endswith(".py")
152
+ )
153
+ return found
154
+
155
+
156
+ def _expand(path: str) -> tuple[list[str], bool]:
157
+ """Expand one path, directory or glob into the files it names.
158
+
159
+ Args:
160
+ path: A file path, directory path or glob pattern.
161
+
162
+ Returns:
163
+ The files it names, and whether it named anything at all.
164
+ """
165
+ if _is_glob_pattern(path):
166
+ matched = glob.glob(path, recursive=True, include_hidden=True)
167
+ found: list[str] = []
168
+ for entry in matched:
169
+ if os.path.isfile(entry):
170
+ found.append(entry)
171
+ elif os.path.isdir(entry):
172
+ found.extend(_walk_python_files(entry))
173
+ return (found, bool(matched))
174
+ if os.path.isfile(path):
175
+ return ([path], True)
176
+ if os.path.isdir(path):
177
+ return (_walk_python_files(path), True)
178
+ return ([], False)
179
+
180
+
181
+ def package_of(path: str, tree: str) -> str | None:
182
+ """Name the package a file belongs to, relative to the tree holding it.
183
+
184
+ A file sitting directly in the tree belongs to no package, and so has no
185
+ test directory of its own to discount.
186
+
187
+ Args:
188
+ path: The file path.
189
+ tree: The tree the file was found under.
190
+
191
+ Returns:
192
+ The first path component below the tree, or None.
193
+ """
194
+ relative = os.path.relpath(os.path.normpath(path), os.path.normpath(tree))
195
+ parts = relative.split(os.sep)
196
+ if len(parts) < 2 or parts[0] in ("", os.pardir):
197
+ return None
198
+ return parts[0]
199
+
200
+
201
+ def _tree_root(path: str) -> str:
202
+ """Reduce a tree argument to the directory its files hang from."""
203
+ if os.path.isdir(path):
204
+ return path
205
+ stripped = path.split("*")[0].split("?")[0].split("[")[0]
206
+ directory = os.path.dirname(stripped)
207
+ return directory if directory else "."
208
+
209
+
210
+ def should_skip(path: str, exclude_patterns: list[str]) -> bool:
211
+ """Check whether a file matches any exclude pattern.
212
+
213
+ Args:
214
+ path: The file path to check.
215
+ exclude_patterns: Glob patterns to exclude.
216
+
217
+ Returns:
218
+ True when the path or its basename matches a pattern.
219
+ """
220
+ return any(
221
+ fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(os.path.basename(path), pattern)
222
+ for pattern in exclude_patterns
223
+ )
224
+
225
+
226
+ def _collect(paths: Sequence[str], exclude_patterns: list[str]) -> tuple[dict[str, str], list[str]]:
227
+ """Expand paths into files, keeping the tree each file came from.
228
+
229
+ Args:
230
+ paths: File paths, directory paths or glob patterns.
231
+ exclude_patterns: Glob patterns to exclude.
232
+
233
+ Returns:
234
+ A mapping of normalised file path to the tree it came from, and the
235
+ paths that named nothing.
236
+ """
237
+ trees: dict[str, str] = {}
238
+ missing: list[str] = []
239
+ for path in paths:
240
+ found, matched = _expand(path)
241
+ if not matched:
242
+ missing.append(path)
243
+ continue
244
+ root = _tree_root(path)
245
+ for entry in found:
246
+ normalised = os.path.normpath(entry)
247
+ if normalised.endswith(".py") and not should_skip(normalised, exclude_patterns):
248
+ trees.setdefault(normalised, root)
249
+ return (trees, missing)
250
+
251
+
252
+ def _read(path: str, result: ScanResult, verbose: bool) -> str | None:
253
+ """Read one file, recording an error on the result if it cannot be read."""
254
+ try:
255
+ with open(path, encoding="utf-8") as handle:
256
+ return handle.read()
257
+ except OSError as error:
258
+ print(f"Error reading {path}: {error}", file=sys.stderr)
259
+ result.had_error = True
260
+ if verbose:
261
+ print(f"Skipping (unreadable): {path}")
262
+ return None
263
+
264
+
265
+ def read_sources(
266
+ paths: dict[str, str], result: ScanResult, verbose: bool = False
267
+ ) -> dict[str, str]:
268
+ """Read every file, keyed by path.
269
+
270
+ Args:
271
+ paths: A mapping of file path to the tree it came from.
272
+ result: The result to record read errors on.
273
+ verbose: Whether to name each file read.
274
+
275
+ Returns:
276
+ A mapping of file path to content, skipping the unreadable.
277
+ """
278
+ sources: dict[str, str] = {}
279
+ for path in sorted(paths):
280
+ content = _read(path, result, verbose)
281
+ if content is not None:
282
+ sources[path] = content
283
+ return sources
284
+
285
+
286
+ def read_definitions(
287
+ paths: dict[str, str],
288
+ sources: dict[str, str],
289
+ result: ScanResult,
290
+ verbose: bool = False,
291
+ ) -> list[Definition]:
292
+ """Parse every definition file for its public top-level definitions.
293
+
294
+ Args:
295
+ paths: A mapping of definition file path to the tree it came from.
296
+ sources: Every readable file, keyed by path.
297
+ result: The result to record parse errors and counts on.
298
+ verbose: Whether to name each file scanned.
299
+
300
+ Returns:
301
+ Every public definition found, in path order.
302
+ """
303
+ definitions: list[Definition] = []
304
+ for path in sorted(paths):
305
+ if path not in sources:
306
+ continue
307
+ if verbose:
308
+ print(f"Scanning: {path}")
309
+ try:
310
+ found = public_definitions(path, sources[path], package_of(path, paths[path]))
311
+ except SyntaxError as error:
312
+ print(f"Syntax error in {path}: {error}", file=sys.stderr)
313
+ result.had_error = True
314
+ continue
315
+ result.files_scanned += 1
316
+ definitions.extend(found)
317
+ result.definitions_read = len(definitions)
318
+ return definitions
319
+
320
+
321
+ def output_findings(findings: list[Finding], count_mode: bool = False) -> None:
322
+ """Print findings in the requested format.
323
+
324
+ Args:
325
+ findings: The findings to print.
326
+ count_mode: Print only how many there are.
327
+ """
328
+ if count_mode:
329
+ print(len(findings))
330
+ return
331
+ for finding in findings:
332
+ print(finding)
333
+
334
+
335
+ def determine_exit_code(result: ScanResult, warn_only: bool = False) -> int:
336
+ """Choose the exit code for a result.
337
+
338
+ Args:
339
+ result: The scan result.
340
+ warn_only: Always succeed when true.
341
+
342
+ Returns:
343
+ 0 for success, 1 for findings, 2 for errors.
344
+ """
345
+ if warn_only:
346
+ return EXIT_SUCCESS
347
+ if result.findings:
348
+ return EXIT_FINDINGS
349
+ if result.had_error:
350
+ return EXIT_ERROR
351
+ return EXIT_SUCCESS
352
+
353
+
354
+ def _report(result: ScanResult, args: argparse.Namespace) -> None:
355
+ """Print whatever the chosen output mode asks for."""
356
+ if args.verbose:
357
+ print()
358
+ print(f"Files scanned: {result.files_scanned}")
359
+ print(f"Definitions read: {result.definitions_read}")
360
+ print(f"Findings: {len(result.findings)}")
361
+ for finding in result.findings:
362
+ print(f" Unused: {finding}")
363
+ if result.had_error:
364
+ print("Errors occurred during scanning.")
365
+ return
366
+ if not args.quiet:
367
+ output_findings(result.findings, args.count)
368
+
369
+
370
+ def main(argv: Sequence[str] | None = None) -> None:
371
+ """Run the CLI.
372
+
373
+ Args:
374
+ argv: Command-line arguments, defaulting to sys.argv[1:].
375
+ """
376
+ args = create_parser().parse_args(argv)
377
+ exclude_patterns = parse_patterns(args.exclude)
378
+ result = ScanResult()
379
+
380
+ definition_paths, missing = _collect(args.trees, exclude_patterns)
381
+ consumer_paths, consumer_missing = _collect(args.consumers or args.trees, exclude_patterns)
382
+ missing.extend(consumer_missing)
383
+
384
+ for path in missing:
385
+ print(f"Error: Path not found: {path}", file=sys.stderr)
386
+ if not definition_paths and missing:
387
+ sys.exit(EXIT_ERROR)
388
+ if missing:
389
+ result.had_error = True
390
+
391
+ if args.verbose:
392
+ print(f"Reading {len(definition_paths)} definition file(s)...")
393
+ print(f"Searching {len(consumer_paths)} consumer file(s) for uses.")
394
+ if exclude_patterns:
395
+ print(f"Excluding patterns: {', '.join(exclude_patterns)}")
396
+ print()
397
+
398
+ sources = read_sources({**consumer_paths, **definition_paths}, result, args.verbose)
399
+ definitions = read_definitions(definition_paths, sources, result, args.verbose)
400
+ consumers = {path: content for path, content in sources.items() if path in consumer_paths}
401
+
402
+ findings = unused_definitions(
403
+ definitions, consumers, args.own_tests, args.count_defining_file
404
+ )
405
+ result.findings = findings[:1] if (args.fail_fast and findings) else findings
406
+
407
+ _report(result, args)
408
+ sys.exit(determine_exit_code(result, args.warn_only))
File without changes
@@ -0,0 +1,204 @@
1
+ """Core logic for finding public definitions that nothing else names."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import re
7
+ from dataclasses import dataclass
8
+ from functools import lru_cache
9
+ from typing import TYPE_CHECKING
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Iterator
13
+
14
+ DEFINITION_NODES = (ast.AsyncFunctionDef, ast.ClassDef, ast.FunctionDef)
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Definition:
19
+ """A public top-level definition found in a source file."""
20
+
21
+ path: str
22
+ line_number: int
23
+ name: str
24
+ package: str | None
25
+
26
+ def __str__(self) -> str:
27
+ """Format as path:line:name."""
28
+ return f"{self.path}:{self.line_number}:{self.name}"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Finding:
33
+ """A definition that nothing outside its own file and tests names."""
34
+
35
+ definition: Definition
36
+
37
+ @property
38
+ def path(self) -> str:
39
+ """The file the definition sits in."""
40
+ return self.definition.path
41
+
42
+ @property
43
+ def line_number(self) -> int:
44
+ """The line the definition starts on."""
45
+ return self.definition.line_number
46
+
47
+ @property
48
+ def name(self) -> str:
49
+ """The name of the definition."""
50
+ return self.definition.name
51
+
52
+ def __str__(self) -> str:
53
+ """Format as path:line:name."""
54
+ return str(self.definition)
55
+
56
+
57
+ def is_public(name: str) -> bool:
58
+ """Check whether a name is public, meaning it has no leading underscore."""
59
+ return not name.startswith("_")
60
+
61
+
62
+ def public_definitions(path: str, content: str, package: str | None = None) -> list[Definition]:
63
+ """Find every public top-level definition in a source file.
64
+
65
+ Only top-level statements are read. A method on a class and a function
66
+ nested inside another function are reached through the name of the thing
67
+ that holds them, so neither is a definition this tool can speak about.
68
+
69
+ Args:
70
+ path: The file path, used for reporting.
71
+ content: The file content to parse.
72
+ package: The package the file belongs to, if any.
73
+
74
+ Returns:
75
+ The public definitions, in the order they appear.
76
+
77
+ Raises:
78
+ SyntaxError: If the content cannot be parsed as Python.
79
+ """
80
+ tree = ast.parse(content, filename=path)
81
+ return [
82
+ Definition(path=path, line_number=node.lineno, name=node.name, package=package)
83
+ for node in tree.body
84
+ if isinstance(node, DEFINITION_NODES) and is_public(node.name)
85
+ ]
86
+
87
+
88
+ @lru_cache(maxsize=4096)
89
+ def _word_pattern(name: str) -> re.Pattern[str]:
90
+ """Compile, and remember, a whole-word pattern for a name."""
91
+ return re.compile(rf"\b{re.escape(name)}\b")
92
+
93
+
94
+ def names_in_line(name: str, line: str) -> bool:
95
+ """Check whether a line names an identifier as a whole word."""
96
+ return _word_pattern(name).search(line) is not None
97
+
98
+
99
+ def names_in_content(name: str, content: str, skipped_line: int | None = None) -> bool:
100
+ """Check whether content names an identifier as a whole word.
101
+
102
+ Args:
103
+ name: The identifier to look for.
104
+ content: The text to search.
105
+ skipped_line: A 1-indexed line to ignore, if any.
106
+
107
+ Returns:
108
+ True if any line other than the skipped one names the identifier.
109
+ """
110
+ if skipped_line is None:
111
+ return names_in_line(name, content)
112
+ return any(
113
+ names_in_line(name, line)
114
+ for number, line in enumerate(content.splitlines(), 1)
115
+ if number != skipped_line
116
+ )
117
+
118
+
119
+ def own_tests_directory(template: str | None, package: str | None) -> str | None:
120
+ """Render the directory holding a package's own tests.
121
+
122
+ Args:
123
+ template: A path template containing ``{package}``, or None.
124
+ package: The package name to substitute, or None.
125
+
126
+ Returns:
127
+ The rendered directory with a trailing separator, or None when there
128
+ is no template or the file belongs to no package.
129
+ """
130
+ if template is None or package is None:
131
+ return None
132
+ rendered = template.format(package=package)
133
+ return rendered if rendered.endswith("/") else rendered + "/"
134
+
135
+
136
+ def _searchable(
137
+ sources: dict[str, str],
138
+ definition: Definition,
139
+ own_tests: str | None,
140
+ count_defining_file: bool,
141
+ ) -> Iterator[tuple[str, int | None]]:
142
+ """Yield each file to search, with the line to ignore within it."""
143
+ for path, content in sources.items():
144
+ if own_tests is not None and path.startswith(own_tests):
145
+ continue
146
+ if path == definition.path:
147
+ if not count_defining_file:
148
+ continue
149
+ yield content, definition.line_number
150
+ else:
151
+ yield content, None
152
+
153
+
154
+ def is_used(
155
+ definition: Definition,
156
+ sources: dict[str, str],
157
+ own_tests: str | None = None,
158
+ count_defining_file: bool = False,
159
+ ) -> bool:
160
+ """Check whether anything names a definition.
161
+
162
+ Args:
163
+ definition: The definition to look for.
164
+ sources: Every consumer file, keyed by path, mapped to its content.
165
+ own_tests: A directory whose files do not count as users, if any.
166
+ count_defining_file: Whether a name written elsewhere in the defining
167
+ file counts as a use. A docstring example, an ``__all__`` entry and
168
+ a call from a function that is itself dead all read alike, so this
169
+ is off by default.
170
+
171
+ Returns:
172
+ True if any file names the definition.
173
+ """
174
+ return any(
175
+ names_in_content(definition.name, content, skipped)
176
+ for content, skipped in _searchable(sources, definition, own_tests, count_defining_file)
177
+ )
178
+
179
+
180
+ def unused_definitions(
181
+ definitions: list[Definition],
182
+ sources: dict[str, str],
183
+ own_tests_template: str | None = None,
184
+ count_defining_file: bool = False,
185
+ ) -> list[Finding]:
186
+ """Find the definitions nothing names.
187
+
188
+ Args:
189
+ definitions: The definitions to check.
190
+ sources: Every consumer file, keyed by path, mapped to its content.
191
+ own_tests_template: A path template containing ``{package}`` whose
192
+ files do not count as users, if any.
193
+ count_defining_file: Whether a name written elsewhere in the defining
194
+ file counts as a use.
195
+
196
+ Returns:
197
+ A finding for each definition nothing names.
198
+ """
199
+ findings = []
200
+ for definition in definitions:
201
+ own_tests = own_tests_directory(own_tests_template, definition.package)
202
+ if not is_used(definition, sources, own_tests, count_defining_file):
203
+ findings.append(Finding(definition=definition))
204
+ return findings
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: assert-python-definition-is-used
3
+ Version: 20260823031322
4
+ Summary: CLI tool to assert that every public Python definition in a tree is used somewhere else
5
+ Author-email: 10U Labs <dev@10ulabs.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/10U-Labs/assert-python-definition-is-used
8
+ Project-URL: Repository, https://github.com/10U-Labs/assert-python-definition-is-used
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE.txt
23
+ Dynamic: license-file
24
+
25
+ # assert-python-definition-is-used
26
+
27
+ Assert that every public Python definition in a tree is named somewhere
28
+ else.
29
+
30
+ ## Why
31
+
32
+ A function whose last caller is deleted does not disappear. Its tests
33
+ still pass, the coverage gate over its module stays green, and static
34
+ analysis keeps reading it, so the tree grows a layer of code that is
35
+ maintained and never called. Nothing in a normal toolchain reports it:
36
+ coverage measures whether lines run, not whether anything wants them,
37
+ and a module held at 100% by its own tests manufactures exactly the
38
+ evidence that makes it look used.
39
+
40
+ This tool asks the other question. For every public top-level `def` and
41
+ `class` in the trees you point it at, it asks whether anything else
42
+ names it, and reports the ones nothing does.
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ pip install assert-python-definition-is-used
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ```bash
53
+ # Every definition in lib/python must be named somewhere in the repo
54
+ assert-python-definition-is-used lib/python \
55
+ --consumer lib/python --consumer scripts --consumer src --consumer test
56
+
57
+ # The same, but a module's own tests no longer count as a caller
58
+ assert-python-definition-is-used lib/python \
59
+ --consumer lib/python --consumer scripts --consumer src --consumer test \
60
+ --own-tests 'test/lib/python/test_{package}'
61
+ ```
62
+
63
+ Those two runs are the pair worth having. The first is a cheap outer
64
+ bound that catches a definition whose tests were deleted along with its
65
+ caller. The second is the one that finds code kept alive only by the
66
+ tests written for it, which is what a coverage gate hides.
67
+
68
+ ### Options
69
+
70
+ | Option | Effect |
71
+ | --- | --- |
72
+ | `--consumer PATH` | A tree to search for uses. Repeatable. |
73
+ | `--own-tests TEMPLATE` | Template whose files are not users. |
74
+ | `--count-defining-file` | Count a use in the defining file. |
75
+ | `--exclude PATTERNS` | Comma-separated globs to leave out of both trees. |
76
+ | `--quiet` | Print nothing; report through the exit code. |
77
+ | `--count` | Print only how many findings there were. |
78
+ | `--verbose` | Print the trees read, each file scanned, and a summary. |
79
+ | `--fail-fast` | Stop at the first finding. |
80
+ | `--warn-only` | Always exit 0. |
81
+
82
+ ### Exit codes
83
+
84
+ | Code | Meaning |
85
+ | --- | --- |
86
+ | 0 | Nothing unused |
87
+ | 1 | Something unused |
88
+ | 2 | A tree was missing, unreadable, or would not parse |
89
+
90
+ ## What counts as a use
91
+
92
+ A use is the definition's name written as a whole word in any file the
93
+ consumer trees reach. That is deliberately blunt, and it has two
94
+ consequences worth knowing before you read the output.
95
+
96
+ By default a name written elsewhere in its own defining file does not
97
+ count. A docstring example, an `__all__` entry and a call from a
98
+ sibling that is itself dead all look the same as a live caller, so
99
+ crediting them hides real findings. Pass `--count-defining-file` for the
100
+ looser rule. When the stricter rule reports a definition that a live
101
+ sibling in the same file genuinely calls, the finding is that the
102
+ definition is public and should not be: rename it with a leading
103
+ underscore, which takes it out of scope.
104
+
105
+ Matching on a bare name also means a definition reads as used when any
106
+ other file happens to contain that word, including a file that defines
107
+ its own unrelated function of the same name. The count is a lower bound
108
+ rather than an exact figure.
109
+
110
+ Only top-level `def` and `class` statements are read. A method and a
111
+ nested function are reached through the name of the thing that holds
112
+ them, so neither is something this tool can speak about. Names starting
113
+ with an underscore are skipped.
114
+
115
+ ## Packages and their own tests
116
+
117
+ `--own-tests` takes a path template rather than a fixed layout, because
118
+ the convention differs between repositories. The `{package}` field is
119
+ the first directory below the definition tree:
120
+
121
+ ```text
122
+ lib/python/aws_clients/__init__.py -> package is "aws_clients"
123
+ ```
124
+
125
+ So `--own-tests 'test/lib/python/test_{package}'` discounts uses under
126
+ `test/lib/python/test_aws_clients/`, and
127
+ `--own-tests 'test/lib/python/{package}'` discounts uses under
128
+ `test/lib/python/aws_clients/`.
129
+
130
+ A file sitting directly in the definition tree belongs to no package
131
+ and so has no test directory to discount. Uses of its definitions count
132
+ wherever they appear.
133
+
134
+ ## GitHub Actions
135
+
136
+ ```yaml
137
+ - name: Assert every definition is used outside its own tests
138
+ uses: 10U-Labs/assert-python-definition-is-used@latest
139
+ with:
140
+ consumers: lib/python scripts src test
141
+ own-tests: test/lib/python/test_{package}
142
+ trees: lib/python
143
+ verbose: true
144
+ ```
145
+
146
+ ## License
147
+
148
+ Apache-2.0
@@ -0,0 +1,11 @@
1
+ assert_python_definition_is_used/__init__.py,sha256=9sLJ1H1UCMAsSDXvYdE4fhLuia4rmenVQ-ZS4_TFUq0,84
2
+ assert_python_definition_is_used/__main__.py,sha256=WHvRaaHXV42YBDfprj8MRY9TaxRWeXTU4zWiBztAMHk,108
3
+ assert_python_definition_is_used/cli.py,sha256=inxqRtBmHi1OnwgsAV7_aKL1lEqKITcFIPzt42C4QZ0,12889
4
+ assert_python_definition_is_used/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ assert_python_definition_is_used/scanner.py,sha256=iw09-UtGb877djejhzih3WPeOq_nU01w7BgcjKDaqgM,6508
6
+ assert_python_definition_is_used-20260823031322.dist-info/licenses/LICENSE.txt,sha256=7C7FkuzwSQFE_PL6st5x2YyMN1aiyjZ9ti1s5X45no8,10761
7
+ assert_python_definition_is_used-20260823031322.dist-info/METADATA,sha256=u5RC8Nx716Vn34B1y9_LBXQ7hxHeZMSv_M7cqUmY8eg,5581
8
+ assert_python_definition_is_used-20260823031322.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ assert_python_definition_is_used-20260823031322.dist-info/entry_points.txt,sha256=0hRlDENoZVXrGPiF4uyrOB4JczdxiKI8FjlruCVZnGs,95
10
+ assert_python_definition_is_used-20260823031322.dist-info/top_level.txt,sha256=kUSqtiu2F8Pw2YUxnQH6dg37fioaCpUu0hlXL5m2hbg,33
11
+ assert_python_definition_is_used-20260823031322.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ assert-python-definition-is-used = assert_python_definition_is_used.cli:main
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2024 10U Labs LLC
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ assert_python_definition_is_used