Skip to content

Preserve imports referenced by quoted type annotations - #969

Open
Aschenbath wants to merge 1 commit into
python-rope:masterfrom
Aschenbath:codex/oss20d-20261122-rope-string-annotations
Open

Aschenbath wants to merge 1 commit into
python-rope:masterfrom
Aschenbath:codex/oss20d-20261122-rope-string-annotations

Conversation

@Aschenbath

Copy link
Copy Markdown

Imports used only in quoted annotations are currently removed by Organize Imports, including from foo import Baz followed by value: "Baz".

Parse annotation strings as AST expressions without evaluating them and collect their referenced names. Cover variable, class, synchronous/asynchronous function signatures and nested generic annotations. Signature annotations are inspected in their enclosing scope. Ordinary strings, invalid annotation text, and strings in conventionally named Literal values / Annotated metadata do not retain imports.

Validation: the initial regression fails before the fix; 157 import utility tests and 249 related move/extract tests pass (one skip and one expected failure). Black and isort checks pass. Existing deprecation/syntax warnings remain. This does not implement general type inference or resolve aliases of Literal and Annotated.

Fixes #369.

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.05882% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.45%. Comparing base (ff8a306) to head (fe2d99e).

Files with missing lines Patch % Lines
rope/refactor/importutils/module_imports.py 94.28% 2 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master     #969   +/-   ##
=======================================
  Coverage   95.44%   95.45%           
=======================================
  Files         134      134           
  Lines       26910    26978   +68     
=======================================
+ Hits        25685    25751   +66     
- Misses       1225     1227    +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@mcepl mcepl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, focused fix for a long-standing annoyance (#369) — approved. Everything below is documentation-level; nothing blocking.

What I verified locally on fe2d99e:

  • Pre-fix check: with only the new tests applied to master, the regression tests fail; all pass with this PR.
  • Full ropetest suite: 2185 passed, 7 skipped, 5 xfailed — matching the PR description.
  • Issue #369's exact reproduction is fixed through the user-facing ImportTools.organize_imports() path, not only the module_imports() API the tests use.
  • expand_stars benefits as well: from pkg1 import * + value: "mod1.Baz" now expands to from pkg1 import mod1.
  • Extra manual probes behave as designed: Annotated["Baz", "meta"] (first element visited, metadata not), nested quoted annotations ("'mod1.Baz'"), invalid annotation syntax (import removed), __future__ import annotations, unions/generics inside quoted strings, async def with positional-only parameters, and forward references to later-defined module-level classes.

Design-wise the change is well-placed: _UnboundNameFinder serves remove_unused_imports, get_used_imports (move/extract flows) and expand_stars alike; signature annotations are inspected in the enclosing scope before _visit_child_scope, matching Python's evaluation semantics; parsing annotation strings with ast.parse(..., mode="eval") keeps it safe (no evaluation); and treating invalid annotation text as "not a forward reference" errs on the correct side for import cleanup.

Thanks!

self._visit_annotation(node.returns)
self._visit_child_scope(node)

_AsyncFunctionDef = _FunctionDef

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is more than string-annotation support: on master, AsyncFunctionDef falls through to generic_visit in RopeNodeVisitor, so an async def body was walked with the enclosing scope's finder and got no local-scope isolation. Verified against master and this PR:

import os

async def f():
    os = "local"
    return os

master wrongly keeps import os; with this PR it is removed, matching the def behaviour. A very welcome fix, but a behaviour change beyond string annotations — please mention it in the PR description and the CHANGELOG (or as its own entry).

):
if argument is not None:
self._visit_annotation(argument.annotation)
self._visit_annotation(node.returns)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: unquoted signature annotations end up being walked twice — once here in the enclosing-scope finder and again through the generic_visit of the arguments node inside _visit_child_scope (pre-existing behaviour). Harmless with the set semantics, but a one-line comment would help future readers.

self._visit_annotation(node.annotation)
self.generic_visit(node)

def _visit_annotation(self, node):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor gap: PEP 695 type aliases still lose the import — type T = "mod1.Baz" (verified; _visit_annotation is never reached from the TypeAlias node). Same user-visible symptom as #369, just in newer syntax. Reasonable to defer, but worth a follow-up issue given 3.12+ is already a supported classifier.

elif isinstance(node, ast.Subscript):
self.visit(node.value)
name = getattr(node.value, "id", getattr(node.value, "attr", None))
if name == "Literal":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the other direction, an aliased Literal re-encounters the original bug in its conservative (import wrongly kept) form: from typing import Literal as L + value: L["mod1.Baz"] — verified. The PR description acknowledges this; if it is acceptable behaviour, please pin it with a test (plain assertion or xfail) so the limitation is documented rather than silently rediscovered later.

self.visit(node)
elif isinstance(node, ast.Subscript):
self.visit(node.value)
name = getattr(node.value, "id", getattr(node.value, "attr", None))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style nit: this nested getattr is rather dense (the eagerly-evaluated default is harmless but opaque). Explicit isinstance(node.value, ast.Name) / ast.Attribute checks, or a small helper, would read better; module-level constants for the "Literal" / "Annotated" special names would help too.

except SyntaxError:
return
for child in ast.walk(parsed):
if hasattr(child, "lineno"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: a one-line comment here would help — only lineno needs rewriting, because that is all _is_node_interesting consults, and col_offset/end_lineno can stay string-relative since the parsed nodes never reach _visit_child_scope. As written it looks like a general AST-relocation ritual.

return
if isinstance(node, ast.Constant) and isinstance(node.value, str):
try:
parsed = ast.parse(node.value, mode="eval").body

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ultra-nit for a possible follow-up: for f-string annotations the literal text fragments get parsed as expressions too, so value: f"wibble {mod1}" conservatively retains an import named wibble even though it only occurs as literal text (verified; master wrongly removes it instead, so the PR is strictly better here). Not worth extra code — perhaps just note the deliberate looseness in a comment.

Comment thread CHANGELOG.md
@@ -1,5 +1,7 @@
# **Upcoming release**

- #369 Keep imports referenced by string annotations when organizing imports.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sibling entries carry contributor attribution (e.g. (@lieryan)); consider (@Aschenbath). Also, this entry currently sits above the #859 block — grouping with the recent entries would read better. And if you take up the _AsyncFunctionDef scope-isolation comment above, it deserves its own bullet.

This branch has not been deployed

No deployments
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.

ImportOrganizer should not remove imports used in string type annotation

2 participants