Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(dead-code): count Outer.Inner uses of Python nested classes (#2994)

Raghav Chamadiya865d244357dd
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 045c9136c..d3c396585 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -38,6 +38,7 @@ from .constants import (
_DELIBERATELY_UNUSED_ANNOTATIONS,
_FRAMEWORK_DECORATOR_SUFFIXES,
_FRAMEWORK_DECORATORS,
+ _FRAMEWORK_INNER_CLASS_NAMES,
_NAMESPACE_IMPORT_LANGUAGES,
_NEVER_PACKAGE_DIRS,
_PREPROCESSED_LANGUAGES,
@@ -786,6 +787,22 @@ def _is_public_top_level(sym: dict, kinds: AbstractSet[str] | None) -> bool:
return kinds is None or sym.get("kind") in kinds
+def _nested_class_used(node_data: dict, sym: dict) -> bool:
+ """Whether a nested class is one a framework reads or its module names.
+
+ ``ingestion/python_local_refs.py`` records a nested class its module reaches
+ (``Outer.Inner``, or ``Inner`` inside ``Outer``) under its ``Outer.Inner``
+ name, since a bare inner name like ``ErrorModel`` repeats across classes.
+ """
+ parent = sym.get("parent_name")
+ if not parent:
+ return False
+ name = sym.get("name", "")
+ if name in _FRAMEWORK_INNER_CLASS_NAMES.get(sym.get("language", ""), ()):
+ return True
+ return f"{parent}.{name}" in (node_data.get("local_refs") or ())
+
+
def _symbol_span(data: dict) -> dict[str, int | None]:
"""``lines``/``start_line``/``end_line`` for a symbol finding.
@@ -1480,6 +1497,9 @@ class DeadCodeAnalyzer:
if self._name_matches_dynamic(sym_name, dynamic_patterns):
return True
+ if _nested_class_used(node_data, sym):
+ return True
+
# TS/JS: type names referenced in type positions of the same file.
local_type_uses = node_data.get("local_type_uses")
if local_type_uses and sym_name in local_type_uses:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index 463654114..76b0e98f2 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -1014,6 +1014,14 @@ _DELIBERATELY_UNUSED_ANNOTATIONS: tuple[tuple[str, str], ...] = (
("SuppressWarnings", "unused"),
)
+# Inner class names a framework reads off the class that declares them, so no
+# code ever names them. Python: the ``class Meta`` options block that Django
+# models and forms, DRF serializers, marshmallow and factory_boy read through
+# their metaclass. Keyed by language; matched only on a nested class.
+_FRAMEWORK_INNER_CLASS_NAMES: dict[str, frozenset[str]] = {
+ "python": frozenset({"Meta"}),
+}
+
# Default dynamic patterns (plugins, handlers, etc.)
_DEFAULT_DYNAMIC_PATTERNS: tuple[str, ...] = (
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 69ba70e79..efa852045 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -1426,7 +1426,10 @@ class ASTParser:
local_refs: frozenset[str] = frozenset()
if lang == "python":
top_level_names = {s.name for s in symbols if s.name and not s.parent_name}
- local_refs = extract_python_local_refs(src, top_level_names)
+ nested_classes = {
+ (s.parent_name, s.name) for s in symbols if s.kind == "class" and s.parent_name
+ }
+ local_refs = extract_python_local_refs(src, top_level_names, nested_classes)
if len(symbols) > _SYMBOL_COUNT_WARN_THRESHOLD:
log.warning(
diff --git a/packages/core/src/repowise/core/ingestion/python_local_refs.py b/packages/core/src/repowise/core/ingestion/python_local_refs.py
index 2bd0b9543..a89f5ab6a 100644
--- a/packages/core/src/repowise/core/ingestion/python_local_refs.py
+++ b/packages/core/src/repowise/core/ingestion/python_local_refs.py
@@ -45,6 +45,8 @@ annotations — reliably.
from __future__ import annotations
import ast
+from collections.abc import Iterator
+from collections.abc import Set as AbstractSet
__all__ = ["extract_python_local_refs"]
@@ -52,6 +54,7 @@ __all__ = ["extract_python_local_refs"]
def extract_python_local_refs(
source: str,
defined_names: frozenset[str] | set[str],
+ nested_classes: AbstractSet[tuple[str, str]] = frozenset(),
) -> frozenset[str]:
"""Return the subset of *defined_names* referenced elsewhere in *source*.
@@ -66,6 +69,10 @@ def extract_python_local_refs(
name). Restricting to defined names keeps the result a small rescue set
and bounds the walk's bookkeeping.
+ *nested_classes* holds the ``(outer, inner)`` pairs of classes declared in
+ another class's body. Each one the module reaches is returned as
+ ``"outer.inner"`` (see ``_nested_class_refs``).
+
Returns an empty set when there are no candidate names or the source is
not parseable as Python 3 (Python 2 source, syntax tree-sitter
tolerated but ``ast`` rejects, etc.) — a missed rescue simply falls
@@ -87,6 +94,8 @@ def extract_python_local_refs(
for stmt in tree.body:
owner = _bound_name(stmt)
_collect_refs(stmt, defined_names, owner, referenced)
+ if nested_classes:
+ referenced |= _nested_class_refs(tree, nested_classes)
return frozenset(referenced)
@@ -150,6 +159,13 @@ def _collect_forward_refs(
a self-referential annotation (``class Node: next: "Node"``) does not
rescue an otherwise-dead class.
"""
+ for ref, _ in _forward_ref_nodes(annotation):
+ if isinstance(ref, ast.Name) and ref.id != owner and ref.id in defined_names:
+ out.add(ref.id)
+
+
+def _forward_ref_nodes(annotation: ast.expr) -> Iterator[tuple[ast.AST, int]]:
+ """Each node of each quoted forward ref in *annotation*, with the quote's line."""
for sub in ast.walk(annotation):
if not (isinstance(sub, ast.Constant) and isinstance(sub.value, str)):
continue
@@ -158,5 +174,60 @@ def _collect_forward_refs(
except (SyntaxError, ValueError):
continue
for ref in ast.walk(inner):
- if isinstance(ref, ast.Name) and ref.id != owner and ref.id in defined_names:
- out.add(ref.id)
+ yield ref, sub.lineno
+
+
+def _nested_class_refs(tree: ast.Module, nested: AbstractSet[tuple[str, str]]) -> set[str]:
+ """``"Outer.Inner"`` for each nested class the module uses outside its own body.
+
+ A use is ``Outer.Inner`` (or ``pkg.Outer.Inner``) anywhere in the module,
+ or ``Inner`` / ``self.Inner`` / ``cls.Inner`` inside ``Outer``, in code or
+ in a quoted annotation. Another module's ``Outer.Inner`` carries only
+ ``Outer`` on its import edge and is not seen here; that ceiling would need
+ attribute chains on import edges.
+ """
+ spans = [
+ (outer.name, inner.name, _lines(outer), _lines(inner))
+ for outer in ast.walk(tree)
+ if isinstance(outer, ast.ClassDef)
+ for inner in outer.body
+ if isinstance(inner, ast.ClassDef) and (outer.name, inner.name) in nested
+ ]
+ found: set[str] = set()
+ for ref, line in _loaded_refs(tree):
+ found.update(
+ f"{outer}.{inner}"
+ for outer, inner, outer_lines, inner_lines in spans
+ if not _within(line, inner_lines)
+ and _names_nested(ref, outer, inner, _within(line, outer_lines))
+ )
+ return found
+
+
+def _lines(node: ast.stmt) -> tuple[int, int]:
+ return node.lineno, node.end_lineno or node.lineno
+
+
+def _within(line: int, lines: tuple[int, int]) -> bool:
+ return lines[0] <= line <= lines[1]
+
+
+def _loaded_refs(tree: ast.Module) -> Iterator[tuple[ast.AST, int]]:
+ """Each loaded name or attribute with its line, quoted annotations included."""
+ for sub in ast.walk(tree):
+ if isinstance(sub, (ast.Name, ast.Attribute)) and isinstance(sub.ctx, ast.Load):
+ yield sub, sub.lineno
+ annotation = _annotation_of(sub)
+ if annotation is not None:
+ yield from _forward_ref_nodes(annotation)
+
+
+def _names_nested(ref: ast.AST, outer: str, inner: str, in_outer: bool) -> bool:
+ """Whether *ref* names the class *inner* nested in *outer*."""
+ if isinstance(ref, ast.Name):
+ return in_outer and ref.id == inner
+ if not isinstance(ref, ast.Attribute) or ref.attr != inner:
+ return False
+ head = ref.value
+ head_name = head.id if isinstance(head, ast.Name) else getattr(head, "attr", None)
+ return head_name == outer or (in_outer and head_name in ("self", "cls"))
diff --git a/tests/unit/dead_code/test_python_nested_classes.py b/tests/unit/dead_code/test_python_nested_classes.py
new file mode 100644
index 000000000..375d99c1e
--- /dev/null
+++ b/tests/unit/dead_code/test_python_nested_classes.py
@@ -0,0 +1,159 @@
+"""Python nested classes reached as ``Outer.Inner`` are not unused exports.
+
+Shaped on healthchecks: pydantic models nested in a transport class
+(``Zulip.ErrorModel.model_validate_json(...)``, ``results: list[Signal.Result]``),
+a Django ``TextChoices`` used bare in its model's body, and Django ``class Meta``
+options blocks, which the model metaclass reads and no code names.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.python_local_refs import extract_python_local_refs
+from tests.unit.dead_code._helpers import _build_graph
+
+_SOURCE = b"""
+from __future__ import annotations
+
+
+class Signal(Transport):
+ class Result(BaseModel):
+ type: str
+
+ class Response(BaseModel):
+ results: list[Signal.Result]
+
+ class Reply(BaseModel):
+ def again(self) -> "Signal.Reply": ...
+
+ class Cached(BaseModel):
+ pass
+
+ class Unused(BaseModel):
+ def me(self) -> Signal.Unused: ...
+
+ def notify(self):
+ return self.Cached
+
+
+class Zulip(Transport):
+ class ErrorModel(BaseModel):
+ msg: str
+
+ @classmethod
+ def raise_for_response(cls, response):
+ return Zulip.ErrorModel.model_validate_json(response.content)
+
+
+class Member(Model):
+ class Role(TextChoices):
+ READONLY = "r", "Read-only"
+
+ role = CharField(default=Role.READONLY)
+
+ class Meta:
+ ordering = ["role"]
+"""
+
+
+def _unused_exports(path: str, src: bytes) -> set[tuple[str | None, str]]:
+ info = FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="python",
+ size_bytes=len(src),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed = ASTParser().parse_file(info, src)
+ symbols = [
+ {
+ "name": s.name,
+ "kind": s.kind,
+ "visibility": s.visibility,
+ "parent_name": s.parent_name,
+ "language": "python",
+ "decorators": [],
+ "start_line": s.start_line,
+ "end_line": s.end_line,
+ }
+ for s in parsed.symbols
+ ]
+ g = _build_graph(
+ nodes={
+ path: {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "local_refs": parsed.local_refs,
+ "symbol_count": len(symbols),
+ "symbols": symbols,
+ },
+ "app/main.py": {
+ "is_entry_point": True,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[("app/main.py", path, {"imported_names": ["Signal", "Zulip", "Member"]})],
+ )
+ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False}
+ )
+ by_name = {s["name"]: s for s in symbols}
+ return {
+ (by_name[f.symbol_name]["parent_name"], f.symbol_name)
+ for f in report.findings
+ if f.kind == DeadCodeKind.UNUSED_EXPORT
+ }
+
+
+def test_nested_class_named_through_its_outer_class_is_used():
+ unused = _unused_exports("app/transport.py", _SOURCE)
+ # ``Signal.Result`` annotation, ``self.Cached``, ``Zulip.ErrorModel`` call
+ # chain, bare ``Role`` in its model's body, framework ``Meta``.
+ for used in ("Result", "Cached", "ErrorModel", "Role"):
+ assert not any(name == used for _, name in unused), used
+ assert ("Member", "Meta") not in unused
+
+
+def test_nested_class_named_only_in_its_own_body_stays_reported():
+ unused = _unused_exports("app/transport.py", _SOURCE)
+ # ``Reply`` and ``Unused`` only name themselves; ``Response`` is never named.
+ assert {("Signal", "Reply"), ("Signal", "Unused"), ("Signal", "Response")} <= unused
+
+
+def test_top_level_meta_class_is_not_a_framework_options_block():
+ src = b"class Meta:\n pass\n"
+ assert (None, "Meta") in _unused_exports("app/transport.py", src)
+
+
+def test_local_refs_record_nested_class_uses_by_qualified_name():
+ src = """
+class Outer:
+ class Inner:
+ pass
+
+class Other:
+ class Inner:
+ pass
+
+def use():
+ return pkg.Outer.Inner
+"""
+ refs = extract_python_local_refs(
+ src, {"Outer", "Other", "use"}, {("Outer", "Inner"), ("Other", "Inner")}
+ )
+ assert "Outer.Inner" in refs
+ # Same inner name under another class: not reached, not recorded.
+ assert "Other.Inner" not in refs