Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.


- #859 Fix `find_definition`/Rename not resolving `async def` methods called via `self` (@gadievron)
- #895 patchedast Starred and keyword now consumes their syntactically expected and ** (@lieryan)
- #896 patchedast cleanup and refactoring (@lieryan)
Expand Down
47 changes: 47 additions & 0 deletions rope/refactor/importutils/module_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,11 +437,58 @@ def _visit_child_scope(self, node):
visitor.visit(child)

def _FunctionDef(self, node):
# Signature annotations resolve outside the function's local scope.
arguments = node.args
for argument in (
arguments.posonlyargs
+ arguments.args
+ arguments.kwonlyargs
+ [arguments.vararg, arguments.kwarg]
):
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_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).


def _ClassDef(self, node):
self._visit_child_scope(node)

def _AnnAssign(self, node):
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.

if node is None:
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.

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.

child.lineno = node.lineno
self._visit_annotation(parsed)
elif isinstance(node, (ast.Name, ast.Attribute)):
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.

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.

# These strings are values, not forward references.
self.visit(node.slice)
elif name == "Annotated" and isinstance(node.slice, ast.Tuple):
self._visit_annotation(node.slice.elts[0])
for metadata in node.slice.elts[1:]:
self.visit(metadata)
else:
self._visit_annotation(node.slice)
else:
for child in ast.iter_child_nodes(node):
self._visit_annotation(child)

def _Name(self, node):
if self._get_root()._is_node_interesting(node) and not self.is_bound(node.id):
self.add_unbound(node.id)
Expand Down
53 changes: 53 additions & 0 deletions ropetest/refactor/importutilstest.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,59 @@ def test_simple_removing_unused_imports(self):
module_with_imports.remove_unused_imports()
self.assertEqual("", module_with_imports.get_changed_source())

def test_imports_used_in_string_annotations(self):
annotations = [
'value: "mod1.Baz"\n',
'class C:\n value: "mod1.Baz"\n',
'def f(value: "mod1.Baz"):\n pass\n',
'def f() -> "mod1.Baz":\n pass\n',
'async def f(value: "mod1.Baz") -> "mod1.Baz":\n pass\n',
'def f(mod1: "mod1.Baz", /, *, other: "mod1.Baz"):\n pass\n',
'value: list["mod1.Baz"]\n',
'value: "list[mod1.Baz]"\n',
'def f(*values: "mod1.Baz", **named: "mod1.Baz"):\n pass\n',
]
for annotation in annotations:
with self.subTest(annotation=annotation):
source = "from pkg1 import mod1\n\n" + annotation
self.mod.write(source)
pymod = self.project.get_module("mod")
imports = self.import_tools.module_imports(pymod)
imports.remove_unused_imports()
self.assertEqual(source, imports.get_changed_source())

def test_imported_class_used_in_string_annotation(self):
self.mod1.write("class Baz:\n pass\n")
source = 'from pkg1.mod1 import Baz\n\nvalue: "Baz"\n'
self.mod.write(source)
imports = self.import_tools.module_imports(self.project.get_module("mod"))
imports.remove_unused_imports()
self.assertEqual(source, imports.get_changed_source())

def test_imports_not_used_by_ordinary_strings(self):
self.mod.write('from pkg1 import mod1\n\nvalue = "mod1.Baz"\n')
imports = self.import_tools.module_imports(self.project.get_module("mod"))
imports.remove_unused_imports()
self.assertNotIn("from pkg1", imports.get_changed_source())

def test_imports_not_used_by_literal_annotation_values(self):
self.mod.write(
'from typing import Literal, Annotated\n'
'from pkg1 import mod1\n\n'
'value: Literal["mod1"]\n'
'other: Annotated[int, "mod1"]\n'
)
imports = self.import_tools.module_imports(self.project.get_module("mod"))
imports.remove_unused_imports()
self.assertNotIn("from pkg1", imports.get_changed_source())
self.assertIn("from typing import", imports.get_changed_source())

def test_invalid_string_annotation_does_not_crash_import_cleanup(self):
self.mod.write('from pkg1 import mod1\n\nvalue: "invalid ["\n')
imports = self.import_tools.module_imports(self.project.get_module("mod"))
imports.remove_unused_imports()
self.assertNotIn("from pkg1", imports.get_changed_source())

def test_simple_removing_unused_imports_for_froms(self):
self.mod1.write(dedent("""\
def a_func():
Expand Down
Loading