Skip to content

Preserve imports referenced by quoted type annotations - #969

Merged
mcepl merged 3 commits into
python-rope:masterfrom
Aschenbath:codex/oss20d-20261122-rope-string-annotations
Dec 3, 2026
Merged

mcepl merged 3 commits into
python-rope:masterfrom
Aschenbath:codex/oss20d-20261122-rope-string-annotations

Conversation

@Aschenbath

Copy link
Copy Markdown
Contributor

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.29730% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.48%. Comparing base (ff8a306) to head (7877b78).
⚠️ Report is 42 commits behind head on master.

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.48%   +0.03%     
==========================================
  Files         134      134              
  Lines       26910    27127     +217     
==========================================
+ Hits        25685    25902     +217     
  Misses       1225     1225              

☔ 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 previously approved these changes Nov 23, 2026

@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!

Comment thread CHANGELOG.md Resolved
Since python-rope#985 changelog entries are collected from per-PR files in
changelog.d/ instead of editing CHANGELOG.md directly, which
avoids conflicts between pull requests. Move the entry to
changelog.d/969.md and credit the author.
mcepl
mcepl previously approved these changes Dec 3, 2026

@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.

Re-approving after moving the changelog entry to changelog.d/969.md.

Treating AsyncFunctionDef like FunctionDef gives async def bodies
their own scope when organizing imports, so an import shadowed by
a local variable in an async def is now removed, as for def. This
is a user-visible change beyond string annotations, so give it its
own changelog entry.

Only the names Literal and Annotated are special-cased, so an
aliased Literal (from typing import Literal as L) still makes its
value look like a forward reference and keeps the unused import.
Pin this known limitation with an expectedFailure test so it is
documented rather than rediscovered; the fix is tracked in python-rope#993.

Refs: python-rope#993

@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.

Re-approving: changelog now covers the async def scoping change, the aliased Literal limitation is pinned with an expectedFailure test, and the remaining review points are tracked in #993 (hint, @Aschenbath 😼 ).

@mcepl
mcepl merged commit c30cb17 into python-rope:master Dec 3, 2026
38 of 42 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.

ImportOrganizer should not remove imports used in string type annotation

2 participants