Skip to content

Stop the Python lowering dropping the sub-expressions that read names - #5

Merged
ethanzhoucool merged 2 commits into
mainfrom
claude/fix-python-dropped-names
Nov 3, 2026
Merged

ethanzhoucool merged 2 commits into
mainfrom
claude/fix-python-dropped-names

Conversation

@ethanzhoucool

Copy link
Copy Markdown
Owner

Summary

Many Python visitors in adapters/python.py build their IR node but never visit what's inside it. A name that is read only inside one of those constructs never produces a NAME node, so the symbol table reports it as "Assigned but never read". Calls in the same places are missing from the call graph.

It shows up on the default page: the Python sample the web UI loads first gets a false finding, `start` is assigned here and not read again. start is used on the next two lines, in {start: 0} and [(0, start)].

Each of these produced a false "unused" on main (the test_python_reads_are_not_reported_as_unused cases):

logger.info(msg)          # logger: method receiver never visited
return xs[i]              # i: the index of a subscript never visited
xs[i] = v; obj.x = v      # xs, i, obj: assignment targets never visited
return [a, b] / a, b / {k: v} / [*xs]   # collection elements never visited
return f"hi {name}"       # f-string slots never visited
return fn(x)              # fn: a callback parameter, the callee is only the call's name
assert x > 0, why;  raise ValueError(msg) from err;  yield x;  del d[k];  match cmd: case ... if verbose
LIMIT = 5; def take(n=LIMIT)    # defaults, decorators (@app.route), base classes

Two related problems:

  • memo[n] = ... inside a function counted as a new local memo, which gave a false "Shadows an outer name" on the classic memoisation pattern.
  • while ... else: dropped its else body entirely.

Changes

  • adapters/python.py
    • Collections, f-strings, Starred, Assert, Raise, Yield and match (subject and guards) now visit their children.
    • Subscript visits its index or slice. Call visits the receiver of a method call, or the whole callee expression when it isn't a bare name (helper().strip(), handlers[name](x)).
    • A new target_reads() returns what an assignment / aug-assign / del target reads (subscript containers and indexes, attribute objects). Plain names and unpacked names stay bindings.
    • A new definition_time_reads() emits decorators, parameter defaults and base classes as siblings before the def/class. They run in the enclosing scope, so @app.route("/") reads app at module level and is not reported as a call that index makes.
    • while visits its orelse.
  • analysis/symbols.py
    • A subscript store (memo[n] = ...) is no longer a binding.
    • A plain CALL with no receiver counts as a read of its callee. Tree-sitter languages already emitted a NAME for this; Python keeps the callee only in the call's meta.

Effect on output: the walkthrough text for the bundled samples is unchanged. Halstead counts go up, since they now see every operand (Python sample MI 45.2 → 44.1). At developer level only, a multi-line literal now annotates its element lines (e.g. str literal 'host'). JS, Java and C++ already did that.

Testing

  • pytest on Python 3.13, 3.12 and 3.11: 174 passed, 3 skipped. ruff check explain_my_code tests is clean. mypy reports the same 26 errors as before.
  • New tests in tests/test_analysis.py. 26 of them fail on main:
    • test_python_reads_are_not_reported_as_unused: 21 constructs.
    • test_storing_into_a_container_does_not_shadow_it.
    • test_python_call_graph_sees_nested_calls: chained call, call in a list, while/else, raised call.
    • test_decorator_calls_belong_to_the_enclosing_scope: passes on main too. It guards against a naive fix that would hang decorator calls under the function.
  • The existing test_unused_local_is_reported still passes, so real unused locals are still reported.
  • Large-input check: 197 KB of Python goes from 0.69 s to 0.75 s end to end, because there are more IR nodes.

Notes

Not changed: tuple-unpacking assignments (a, b = pair) still bind nothing in the symbol table. That's a missed report, not a false one, so I left it alone.


Generated by Claude Code

claude and others added 2 commits November 2, 2026 06:49
Many Python visitors built their IR node without visiting what was
inside it: list/tuple/dict/set literals, f-string slots, `*xs`, the
index of a subscript, the receiver of a method call, the target of
`xs[i] = v`, `del d[k]`, `assert`, `raise`, `yield`, `match` subjects,
`while ... else`, and the decorators, defaults and bases of a
definition. Every name read only in one of those places was reported
as "Assigned but never read", including `start` in the Python sample
the web UI loads by default, `logger` in `logger.info(msg)`, `i` in
`return xs[i]`, `name` in `f"hi {name}"`, and every callback parameter
called as `fn(x)`. Calls in the same places were missing from the call
graph, and `memo[n] = ...` was read as a new local shadowing `memo`.

The visitors now descend into those children. Decorators, defaults and
base classes are emitted before the definition, since they run in the
enclosing scope, so `@app.route(...)` is not a call `index` makes. A
subscript store no longer counts as a binding, and a plain call counts
as a read of its callee.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW
@ethanzhoucool
ethanzhoucool marked this pull request as ready for review November 3, 2026 17:15
@ethanzhoucool
ethanzhoucool merged commit 96b3bda into main Nov 3, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants