Repository navigation
Preserve imports referenced by quoted type annotations - #969
Aschenbath wants to merge 1 commit into
Conversation
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
mcepl
left a comment
There was a problem hiding this comment.
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
ropetestsuite: 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 themodule_imports()API the tests use. expand_starsbenefits as well:from pkg1 import *+value: "mod1.Baz"now expands tofrom 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 defwith 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 |
There was a problem hiding this comment.
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 osmaster 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) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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": |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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"): |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| @@ -1,5 +1,7 @@ | |||
| # **Upcoming release** | |||
|
|
|||
| - #369 Keep imports referenced by string annotations when organizing imports. | |||
There was a problem hiding this comment.
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.
Imports used only in quoted annotations are currently removed by Organize Imports, including
from foo import Bazfollowed byvalue: "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
Literalvalues /Annotatedmetadata 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
LiteralandAnnotated.Fixes #369.