From fe2d99e50e94b924b27aad1d5192f33cb85a60ef Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Sun, 22 Nov 2026 20:13:02 +0800 Subject: [PATCH] Preserve imports referenced by quoted type annotations --- CHANGELOG.md | 2 + rope/refactor/importutils/module_imports.py | 47 ++++++++++++++++++ ropetest/refactor/importutilstest.py | 53 +++++++++++++++++++++ 3 files changed, 102 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88e4748e2..f4b5b7014 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # **Upcoming release** +- #369 Keep imports referenced by string annotations when organizing imports. + - #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) diff --git a/rope/refactor/importutils/module_imports.py b/rope/refactor/importutils/module_imports.py index f35b22521..d146f337a 100644 --- a/rope/refactor/importutils/module_imports.py +++ b/rope/refactor/importutils/module_imports.py @@ -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) self._visit_child_scope(node) + _AsyncFunctionDef = _FunctionDef + 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): + if node is None: + return + if isinstance(node, ast.Constant) and isinstance(node.value, str): + try: + parsed = ast.parse(node.value, mode="eval").body + except SyntaxError: + return + for child in ast.walk(parsed): + if hasattr(child, "lineno"): + 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)) + if name == "Literal": + # 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) diff --git a/ropetest/refactor/importutilstest.py b/ropetest/refactor/importutilstest.py index a2ebd49d1..7ac5050ba 100644 --- a/ropetest/refactor/importutilstest.py +++ b/ropetest/refactor/importutilstest.py @@ -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():