From e66165dff7d59196f0c0496d04e68ddd1b4b913b Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 21 Nov 2026 23:49:05 -0400 Subject: [PATCH 01/14] Rename Worder.dumb_finder to fallback_finder The old name is vague and unprofessional. The field holds a plain finder over the original source used when the offset falls inside an ignored region. Rename both the definition and the single use in _context_call. No behavior change. --- rope/base/worder.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rope/base/worder.py b/rope/base/worder.py index 97ea8d405..11261ba9f 100644 --- a/rope/base/worder.py +++ b/rope/base/worder.py @@ -33,7 +33,7 @@ def __init__(self, code, handle_ignores=False): def _init_ignores(self): ignores = rope.base.simplify.ignored_regions(self.code) - self.dumb_finder = _RealFinder(self.code, self.code) + self.fallback_finder = _RealFinder(self.code, self.code) self.starts = [ignored[0] for ignored in ignores] self.ends = [ignored[1] for ignored in ignores] @@ -43,7 +43,7 @@ def _context_call(self, name, offset): self._init_ignores() start = bisect.bisect(self.starts, offset) if start > 0 and offset < self.ends[start - 1]: - return getattr(self.dumb_finder, name)(offset) + return getattr(self.fallback_finder, name)(offset) return getattr(self.code_finder, name)(offset) def get_primary_at(self, offset): From 7a7fc6bc3e4df3367769ffd0b14a62269262e0ef Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 21 Nov 2026 23:50:09 -0400 Subject: [PATCH 02/14] Replace conditional with dispatch table in get_type_ast Replace the repeated isinstance if-chain with a small type map iterated with isinstance. Same behavior, adding a new node kind now means adding one table entry instead of another branch. --- rope/contrib/autoimport/parse.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/rope/contrib/autoimport/parse.py b/rope/contrib/autoimport/parse.py index d468fe90b..1520dca63 100644 --- a/rope/contrib/autoimport/parse.py +++ b/rope/contrib/autoimport/parse.py @@ -26,14 +26,18 @@ logger = logging.getLogger(__name__) +_NODE_TYPE_MAP = ( + (ast.ClassDef, NameType.Class), + (ast.FunctionDef, NameType.Function), + (ast.Assign, NameType.Variable), +) + + def get_type_ast(node: ast.AST) -> NameType: """Get the lsp type of a node.""" - if isinstance(node, ast.ClassDef): - return NameType.Class - if isinstance(node, ast.FunctionDef): - return NameType.Function - if isinstance(node, ast.Assign): - return NameType.Variable + for node_type, name_type in _NODE_TYPE_MAP: + if isinstance(node, node_type): + return name_type return NameType.Variable # default value From f3bd700faac33f272777bd006b171fc6bf7162eb Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 21 Nov 2026 23:51:18 -0400 Subject: [PATCH 03/14] Extract _names_from_importfrom from get_names_from_file Move the relative from-import loop out of the main child-node loop into its own generator. get_names_from_file keeps Assign and def/class handling; import handling is now testable in isolation. No behavior change. --- rope/contrib/autoimport/parse.py | 36 +++++++++++++++++++------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/rope/contrib/autoimport/parse.py b/rope/contrib/autoimport/parse.py index 1520dca63..9f025399e 100644 --- a/rope/contrib/autoimport/parse.py +++ b/rope/contrib/autoimport/parse.py @@ -73,21 +73,27 @@ def get_names_from_file( get_type_ast(node), ) elif process_imports and isinstance(node, ast.ImportFrom): - # When we process imports, we want to include names in it's own package. - if node.level == 0: - continue - if not node.module or package_name is node.module.split(".")[0]: - continue - for name in node.names: - if isinstance(name, ast.alias): - if name.asname: - real_name = name.asname - else: - real_name = name.name - else: - real_name = name - if underlined or not real_name.startswith("_"): - yield PartialName(real_name, get_type_ast(node)) + yield from _names_from_importfrom(node, package_name, underlined) + + +def _names_from_importfrom( + node: ast.ImportFrom, + package_name: str, + underlined: bool, +) -> Generator[PartialName, None, None]: + """Yield re-exported names from a relative from-import.""" + # When we process imports, we want to include names in it's own package. + if node.level == 0: + return + if not node.module or package_name is node.module.split(".")[0]: + return + for name in node.names: + if isinstance(name, ast.alias): + real_name = name.asname if name.asname else name.name + else: + real_name = name + if underlined or not real_name.startswith("_"): + yield PartialName(real_name, get_type_ast(node)) def get_type_object(imported_object) -> NameType: From 2521bdd62ea42058f84eb9f2076dc08797a802fa Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 21 Nov 2026 23:51:44 -0400 Subject: [PATCH 04/14] Introduce explaining variables in _get_all_star_list Name the repeated isinstance checks as is_str_constant, is_name_ref and is_str_assignment so the star-list branches read as intent instead of type-test soup. No behavior change. --- rope/refactor/importutils/module_imports.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/rope/refactor/importutils/module_imports.py b/rope/refactor/importutils/module_imports.py index f35b22521..faa415476 100644 --- a/rope/refactor/importutils/module_imports.py +++ b/rope/refactor/importutils/module_imports.py @@ -69,22 +69,23 @@ def _resolve_name( elif isinstance(el, ast.Starred): assignments.append(el.value) else: - if isinstance(el, ast.Constant) and isinstance(el.value, str): + is_str_constant = isinstance(el, ast.Constant) and isinstance( + el.value, str + ) + is_name_ref = isinstance(el, ast.Name) + if is_str_constant: result.add(el.value) - elif isinstance(el, ast.Name): + elif is_name_ref: try: name = pymodule.get_attribute(el.id) except exceptions.AttributeNotFoundError: continue else: for av in _resolve_name(name): - if isinstance( - av.ast_node, - ast.Constant, - ) and isinstance( - av.ast_node.value, - str, - ): + is_str_assignment = isinstance( + av.ast_node, ast.Constant + ) and isinstance(av.ast_node.value, str) + if is_str_assignment: result.add(av.ast_node.value) elif isinstance(assignment, ast.Name): try: From 5fe9173277f91649471ae067355233223014c414 Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 21 Nov 2026 23:52:20 -0400 Subject: [PATCH 05/14] Move star-name resolver to module level Move the nested _resolve_name out of ModuleImports._get_all_star_list as _resolve_assigned_names. It never used self; nesting hid it from reuse and tests. Update the three call sites. No behavior change. --- rope/refactor/importutils/module_imports.py | 35 +++++++++++---------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/rope/refactor/importutils/module_imports.py b/rope/refactor/importutils/module_imports.py index faa415476..fb61cf8ce 100644 --- a/rope/refactor/importutils/module_imports.py +++ b/rope/refactor/importutils/module_imports.py @@ -4,6 +4,21 @@ from rope.refactor.importutils import actions, importinfo +def _resolve_assigned_names( + name: Union[pynamesdef.AssignedName, pynames.ImportedName], +) -> List: + """Follow import aliases to the underlying assigned names.""" + while isinstance(name, pynames.ImportedName): + try: + name = name.imported_module.get_object().get_attribute( + name.imported_name, + ) + except exceptions.AttributeNotFoundError: + return [] + assert isinstance(name, pynamesdef.AssignedName) + return name.assignments + + class ModuleImports: def __init__(self, project, pymodule, import_filter=None): self.project = project @@ -30,19 +45,6 @@ def _get_unbound_names(self, defined_pyobject): return visitor.unbound def _get_all_star_list(self, pymodule): - def _resolve_name( - name: Union[pynamesdef.AssignedName, pynames.ImportedName], - ) -> List: - while isinstance(name, pynames.ImportedName): - try: - name = name.imported_module.get_object().get_attribute( - name.imported_name, - ) - except exceptions.AttributeNotFoundError: - return [] - assert isinstance(name, pynamesdef.AssignedName) - return name.assignments - result = set() try: all_star_list = pymodule.get_attribute("__all__") @@ -50,7 +52,7 @@ def _resolve_name( return result assignments = [ - assignment.ast_node for assignment in _resolve_name(all_star_list) + assignment.ast_node for assignment in _resolve_assigned_names(all_star_list) ] # FIXME: Need a better way to recursively infer possible values. @@ -81,7 +83,7 @@ def _resolve_name( except exceptions.AttributeNotFoundError: continue else: - for av in _resolve_name(name): + for av in _resolve_assigned_names(name): is_str_assignment = isinstance( av.ast_node, ast.Constant ) and isinstance(av.ast_node.value, str) @@ -94,7 +96,8 @@ def _resolve_name( continue else: assignments.extend( - assignment.ast_node for assignment in _resolve_name(name) + assignment.ast_node + for assignment in _resolve_assigned_names(name) ) elif isinstance(assignment, ast.BinOp): assignments.append(assignment.left) From beee1f573a2abd9daae0596ee0e92e4aebb3c647 Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 21 Nov 2026 23:54:22 -0400 Subject: [PATCH 06/14] Extract _StarListCollector from ModuleImports Move the pending-assignments stack and collected names out of _get_all_star_list into a small helper class with has_pending, next_assignment, defer, defer_many and add. The method keeps the traversal logic; state lives in the new class. No behavior change. --- rope/refactor/importutils/module_imports.py | 48 +++++++++++++++------ 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/rope/refactor/importutils/module_imports.py b/rope/refactor/importutils/module_imports.py index fb61cf8ce..780e3c80a 100644 --- a/rope/refactor/importutils/module_imports.py +++ b/rope/refactor/importutils/module_imports.py @@ -19,6 +19,29 @@ def _resolve_assigned_names( return name.assignments +class _StarListCollector: + """Hold pending __all__ assignments and collected star names.""" + + def __init__(self, initial_assignments): + self.pending = list(initial_assignments) + self.names = set() + + def has_pending(self): + return bool(self.pending) + + def next_assignment(self): + return self.pending.pop() + + def defer(self, assignment): + self.pending.append(assignment) + + def defer_many(self, assignments): + self.pending.extend(assignments) + + def add(self, name): + self.names.add(name) + + class ModuleImports: def __init__(self, project, pymodule, import_filter=None): self.project = project @@ -45,22 +68,21 @@ def _get_unbound_names(self, defined_pyobject): return visitor.unbound def _get_all_star_list(self, pymodule): - result = set() try: all_star_list = pymodule.get_attribute("__all__") except exceptions.AttributeNotFoundError: - return result + return set() - assignments = [ + collector = _StarListCollector( assignment.ast_node for assignment in _resolve_assigned_names(all_star_list) - ] + ) # FIXME: Need a better way to recursively infer possible values. # Currently pyobjects can recursively infer type, but not values. # Do a very basic 1-level value inference - while assignments: - assignment = assignments.pop() + while collector.has_pending(): + assignment = collector.next_assignment() if isinstance(assignment, ast.List): stack = list(assignment.elts) while stack: @@ -69,14 +91,14 @@ def _get_all_star_list(self, pymodule): stack.append(el.body) stack.append(el.orelse) elif isinstance(el, ast.Starred): - assignments.append(el.value) + collector.defer(el.value) else: is_str_constant = isinstance(el, ast.Constant) and isinstance( el.value, str ) is_name_ref = isinstance(el, ast.Name) if is_str_constant: - result.add(el.value) + collector.add(el.value) elif is_name_ref: try: name = pymodule.get_attribute(el.id) @@ -88,21 +110,21 @@ def _get_all_star_list(self, pymodule): av.ast_node, ast.Constant ) and isinstance(av.ast_node.value, str) if is_str_assignment: - result.add(av.ast_node.value) + collector.add(av.ast_node.value) elif isinstance(assignment, ast.Name): try: name = pymodule.get_attribute(assignment.id) except exceptions.AttributeNotFoundError: continue else: - assignments.extend( + collector.defer_many( assignment.ast_node for assignment in _resolve_assigned_names(name) ) elif isinstance(assignment, ast.BinOp): - assignments.append(assignment.left) - assignments.append(assignment.right) - return result + collector.defer(assignment.left) + collector.defer(assignment.right) + return collector.names def remove_unused_imports(self): can_select = _OneTimeSelector( From 71fabd4d819f798f34fb8da0a5d5af040fcab68b Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Mon, 23 Nov 2026 22:01:29 -0400 Subject: [PATCH 07/14] Add tests for _names_from_importfrom import filtering Cover the extracted helper: relative submodule imports with and without asname, underlined filtering, and the skip paths (absolute imports, same-package imports, bare relative imports, and process_imports=False). Raises patch coverage on parse.py. --- ropetest/contrib/autoimport/parsetest.py | 97 ++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/ropetest/contrib/autoimport/parsetest.py b/ropetest/contrib/autoimport/parsetest.py index cbc9a16e4..50d7febb5 100644 --- a/ropetest/contrib/autoimport/parsetest.py +++ b/ropetest/contrib/autoimport/parsetest.py @@ -28,3 +28,100 @@ def test_find_sys(): def test_find_underlined(): names = list(parse.get_names_from_compiled("os", Source.BUILTIN, underlined=True)) assert Name("_exit", "os", "os", Source.BUILTIN, NameType.Function) in names + + +def test_names_from_relative_import(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from .sub import helper\n", encoding="utf-8") + names = list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + assert PartialName("helper", NameType.Variable) in names + + +def test_names_from_relative_import_with_asname(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from .sub import helper as h\n", encoding="utf-8") + names = list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + assert PartialName("h", NameType.Variable) in names + + +def test_names_from_relative_submodule_import(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from .sub import thing\n", encoding="utf-8") + names = list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + assert PartialName("thing", NameType.Variable) in names + + +def test_absolute_import_is_skipped(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from os import path\n", encoding="utf-8") + assert ( + list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + == [] + ) + + +def test_same_package_import_is_skipped(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from pkg import thing\n", encoding="utf-8") + assert ( + list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + == [] + ) + + +def test_underlined_import_name_is_skipped_by_default(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from .sub import _private\n", encoding="utf-8") + assert ( + list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + == [] + ) + names = list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True, underlined=True + ) + ) + assert PartialName("_private", NameType.Variable) in names + + +def test_bare_relative_import_is_skipped(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from . import helper\n", encoding="utf-8") + assert ( + list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + == [] + ) + + +def test_imports_ignored_without_process_imports(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from . import helper\n", encoding="utf-8") + assert list(parse.get_names_from_file(source, package_name="pkg")) == [] From 9b02e425eda90bcfcbcef377882b858f0b2e06a7 Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Tue, 24 Nov 2026 14:26:12 -0400 Subject: [PATCH 08/14] Cover non-alias branch in _names_from_importfrom Direct unit test with a synthetic node: a plain (non-alias) name must pass through unchanged. Closes the last patch-coverage gap in parse.py. --- ropetest/contrib/autoimport/parsetest.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ropetest/contrib/autoimport/parsetest.py b/ropetest/contrib/autoimport/parsetest.py index 50d7febb5..d051eb7e8 100644 --- a/ropetest/contrib/autoimport/parsetest.py +++ b/ropetest/contrib/autoimport/parsetest.py @@ -1,4 +1,5 @@ import logging +from types import SimpleNamespace from rope.contrib.autoimport import parse from rope.contrib.autoimport.defs import Name, NameType, PartialName, Source @@ -125,3 +126,11 @@ def test_imports_ignored_without_process_imports(tmp_path): source = tmp_path / "mod.py" source.write_text("from . import helper\n", encoding="utf-8") assert list(parse.get_names_from_file(source, package_name="pkg")) == [] + + +def test_names_from_importfrom_with_plain_name(): + # Defensive branch: names are normally ast.alias nodes, but a plain + # name must pass through unchanged. + node = SimpleNamespace(level=1, module="sub", names=["helper"]) + names = list(parse._names_from_importfrom(node, "pkg", False)) + assert PartialName("helper", NameType.Variable) in names From d47e1732b85bb3e037493f8618e68f8478643eb3 Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 28 Nov 2026 16:43:58 -0400 Subject: [PATCH 09/14] Fix string identity comparison in _names_from_importfrom Comparing package_name against the first dotted component used 'is'; use '==' instead. Pre-existing issue. --- rope/contrib/autoimport/parse.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rope/contrib/autoimport/parse.py b/rope/contrib/autoimport/parse.py index 9f025399e..13a1d7dd0 100644 --- a/rope/contrib/autoimport/parse.py +++ b/rope/contrib/autoimport/parse.py @@ -85,7 +85,7 @@ def _names_from_importfrom( # When we process imports, we want to include names in it's own package. if node.level == 0: return - if not node.module or package_name is node.module.split(".")[0]: + if not node.module or package_name == node.module.split(".")[0]: return for name in node.names: if isinstance(name, ast.alias): From 5d8707f9c43c7bf5aae14d81bfa614e0e22446d3 Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 28 Nov 2026 16:44:07 -0400 Subject: [PATCH 10/14] Remove unreachable non-alias branch from _names_from_importfrom ImportFrom.names always holds ast.alias nodes, so the else branch could never execute. Removing dead code instead of testing it. --- rope/contrib/autoimport/parse.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/rope/contrib/autoimport/parse.py b/rope/contrib/autoimport/parse.py index 13a1d7dd0..cd71d1580 100644 --- a/rope/contrib/autoimport/parse.py +++ b/rope/contrib/autoimport/parse.py @@ -90,10 +90,8 @@ def _names_from_importfrom( for name in node.names: if isinstance(name, ast.alias): real_name = name.asname if name.asname else name.name - else: - real_name = name - if underlined or not real_name.startswith("_"): - yield PartialName(real_name, get_type_ast(node)) + if underlined or not real_name.startswith("_"): + yield PartialName(real_name, get_type_ast(node)) def get_type_object(imported_object) -> NameType: From 72984719996359e0624116d79830d7e5ea89572f Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 28 Nov 2026 16:45:12 -0400 Subject: [PATCH 11/14] De-duplicate relative-import tests and cover the package check Collapse the near-identical relative-import tests into parametrized cases. The same-package skip now uses a relative import with a dynamically built package name, so it covers the package check and guards the identity-to-equality fix. Drop the SimpleNamespace test for the removed non-alias branch. --- ropetest/contrib/autoimport/parsetest.py | 93 +++++++----------------- 1 file changed, 28 insertions(+), 65 deletions(-) diff --git a/ropetest/contrib/autoimport/parsetest.py b/ropetest/contrib/autoimport/parsetest.py index d051eb7e8..01642138a 100644 --- a/ropetest/contrib/autoimport/parsetest.py +++ b/ropetest/contrib/autoimport/parsetest.py @@ -1,5 +1,6 @@ import logging -from types import SimpleNamespace + +import pytest from rope.contrib.autoimport import parse from rope.contrib.autoimport.defs import Name, NameType, PartialName, Source @@ -31,59 +32,42 @@ def test_find_underlined(): assert Name("_exit", "os", "os", Source.BUILTIN, NameType.Function) in names -def test_names_from_relative_import(tmp_path): - source = tmp_path / "mod.py" - source.write_text("from .sub import helper\n", encoding="utf-8") - names = list( - parse.get_names_from_file( - source, package_name="pkg", process_imports=True - ) - ) - assert PartialName("helper", NameType.Variable) in names - - -def test_names_from_relative_import_with_asname(tmp_path): +@pytest.mark.parametrize( + ("source_text", "expected"), + [ + ("from .sub import helper\n", "helper"), + ("from .sub import helper as h\n", "h"), + ("from .sub import thing\n", "thing"), + ], +) +def test_names_from_relative_import(tmp_path, source_text, expected): source = tmp_path / "mod.py" - source.write_text("from .sub import helper as h\n", encoding="utf-8") + source.write_text(source_text, encoding="utf-8") names = list( parse.get_names_from_file( source, package_name="pkg", process_imports=True ) ) - assert PartialName("h", NameType.Variable) in names - - -def test_names_from_relative_submodule_import(tmp_path): + assert PartialName(expected, NameType.Variable) in names + + +@pytest.mark.parametrize( + ("source_text", "package_name"), + [ + ("from os import path\n", "pkg"), # absolute import: level == 0 + ("from . import helper\n", "pkg"), # bare relative: no module + # Same package. The name is built dynamically so the check + # relies on equality, not object identity. + ("from .pkg import thing\n", "".join(["p", "k", "g"])), + ], +) +def test_import_is_skipped(tmp_path, source_text, package_name): source = tmp_path / "mod.py" - source.write_text("from .sub import thing\n", encoding="utf-8") - names = list( - parse.get_names_from_file( - source, package_name="pkg", process_imports=True - ) - ) - assert PartialName("thing", NameType.Variable) in names - - -def test_absolute_import_is_skipped(tmp_path): - source = tmp_path / "mod.py" - source.write_text("from os import path\n", encoding="utf-8") + source.write_text(source_text, encoding="utf-8") assert ( list( parse.get_names_from_file( - source, package_name="pkg", process_imports=True - ) - ) - == [] - ) - - -def test_same_package_import_is_skipped(tmp_path): - source = tmp_path / "mod.py" - source.write_text("from pkg import thing\n", encoding="utf-8") - assert ( - list( - parse.get_names_from_file( - source, package_name="pkg", process_imports=True + source, package_name=package_name, process_imports=True ) ) == [] @@ -109,28 +93,7 @@ def test_underlined_import_name_is_skipped_by_default(tmp_path): assert PartialName("_private", NameType.Variable) in names -def test_bare_relative_import_is_skipped(tmp_path): - source = tmp_path / "mod.py" - source.write_text("from . import helper\n", encoding="utf-8") - assert ( - list( - parse.get_names_from_file( - source, package_name="pkg", process_imports=True - ) - ) - == [] - ) - - def test_imports_ignored_without_process_imports(tmp_path): source = tmp_path / "mod.py" source.write_text("from . import helper\n", encoding="utf-8") assert list(parse.get_names_from_file(source, package_name="pkg")) == [] - - -def test_names_from_importfrom_with_plain_name(): - # Defensive branch: names are normally ast.alias nodes, but a plain - # name must pass through unchanged. - node = SimpleNamespace(level=1, module="sub", names=["helper"]) - names = list(parse._names_from_importfrom(node, "pkg", False)) - assert PartialName("helper", NameType.Variable) in names From b002bc65caadc6c601c15d766b23268606cce43f Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Sat, 28 Nov 2026 16:46:29 -0400 Subject: [PATCH 12/14] Drop _StarListCollector, use plain locals in _get_all_star_list The helper class added indirection without simplifying the traversal; plain result/assignments locals (with the explaining variables and the moved resolver intact) read better. No behavior change. --- rope/refactor/importutils/module_imports.py | 48 ++++++--------------- 1 file changed, 13 insertions(+), 35 deletions(-) diff --git a/rope/refactor/importutils/module_imports.py b/rope/refactor/importutils/module_imports.py index 780e3c80a..fb61cf8ce 100644 --- a/rope/refactor/importutils/module_imports.py +++ b/rope/refactor/importutils/module_imports.py @@ -19,29 +19,6 @@ def _resolve_assigned_names( return name.assignments -class _StarListCollector: - """Hold pending __all__ assignments and collected star names.""" - - def __init__(self, initial_assignments): - self.pending = list(initial_assignments) - self.names = set() - - def has_pending(self): - return bool(self.pending) - - def next_assignment(self): - return self.pending.pop() - - def defer(self, assignment): - self.pending.append(assignment) - - def defer_many(self, assignments): - self.pending.extend(assignments) - - def add(self, name): - self.names.add(name) - - class ModuleImports: def __init__(self, project, pymodule, import_filter=None): self.project = project @@ -68,21 +45,22 @@ def _get_unbound_names(self, defined_pyobject): return visitor.unbound def _get_all_star_list(self, pymodule): + result = set() try: all_star_list = pymodule.get_attribute("__all__") except exceptions.AttributeNotFoundError: - return set() + return result - collector = _StarListCollector( + assignments = [ assignment.ast_node for assignment in _resolve_assigned_names(all_star_list) - ) + ] # FIXME: Need a better way to recursively infer possible values. # Currently pyobjects can recursively infer type, but not values. # Do a very basic 1-level value inference - while collector.has_pending(): - assignment = collector.next_assignment() + while assignments: + assignment = assignments.pop() if isinstance(assignment, ast.List): stack = list(assignment.elts) while stack: @@ -91,14 +69,14 @@ def _get_all_star_list(self, pymodule): stack.append(el.body) stack.append(el.orelse) elif isinstance(el, ast.Starred): - collector.defer(el.value) + assignments.append(el.value) else: is_str_constant = isinstance(el, ast.Constant) and isinstance( el.value, str ) is_name_ref = isinstance(el, ast.Name) if is_str_constant: - collector.add(el.value) + result.add(el.value) elif is_name_ref: try: name = pymodule.get_attribute(el.id) @@ -110,21 +88,21 @@ def _get_all_star_list(self, pymodule): av.ast_node, ast.Constant ) and isinstance(av.ast_node.value, str) if is_str_assignment: - collector.add(av.ast_node.value) + result.add(av.ast_node.value) elif isinstance(assignment, ast.Name): try: name = pymodule.get_attribute(assignment.id) except exceptions.AttributeNotFoundError: continue else: - collector.defer_many( + assignments.extend( assignment.ast_node for assignment in _resolve_assigned_names(name) ) elif isinstance(assignment, ast.BinOp): - collector.defer(assignment.left) - collector.defer(assignment.right) - return collector.names + assignments.append(assignment.left) + assignments.append(assignment.right) + return result def remove_unused_imports(self): can_select = _OneTimeSelector( From 3b5765bd5a32b9ae16df21fefc502c20083bbb27 Mon Sep 17 00:00:00 2001 From: Ketan Khunti Date: Sun, 29 Nov 2026 19:14:56 -0400 Subject: [PATCH 13/14] Address review feedback on #965 - Remove duplicate test case in test_names_from_relative_import (helper and thing tested the same thing); keep helper and helper as h. - Use a plain "pkg" literal for the same-package skip test; node.module.split(".")[0] always creates a new string, so the literal already guards the == fix. --- ropetest/contrib/autoimport/parsetest.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ropetest/contrib/autoimport/parsetest.py b/ropetest/contrib/autoimport/parsetest.py index 01642138a..deb140ab3 100644 --- a/ropetest/contrib/autoimport/parsetest.py +++ b/ropetest/contrib/autoimport/parsetest.py @@ -37,7 +37,6 @@ def test_find_underlined(): [ ("from .sub import helper\n", "helper"), ("from .sub import helper as h\n", "h"), - ("from .sub import thing\n", "thing"), ], ) def test_names_from_relative_import(tmp_path, source_text, expected): @@ -56,9 +55,10 @@ def test_names_from_relative_import(tmp_path, source_text, expected): [ ("from os import path\n", "pkg"), # absolute import: level == 0 ("from . import helper\n", "pkg"), # bare relative: no module - # Same package. The name is built dynamically so the check - # relies on equality, not object identity. - ("from .pkg import thing\n", "".join(["p", "k", "g"])), + # Same package: guards the == fix in _names_from_importfrom. + # A plain "pkg" literal is enough here, since + # node.module.split(".")[0] always creates a new string object. + ("from .pkg import thing\n", "pkg"), ], ) def test_import_is_skipped(tmp_path, source_text, package_name): From 003b5fc3c362345f9f3946f1de2d14fa88b2bc2d Mon Sep 17 00:00:00 2001 From: ketan5050 Date: Mon, 30 Nov 2026 12:26:23 +0000 Subject: [PATCH 14/14] Move #965 changelog entry to a fragment mcepl asked for this on #965 (2026-11-30): #985 replaces direct CHANGELOG.md edits with per-PR fragments in changelog.d/, and the PR base is now changelog-news-fragments. The CHANGELOG.md edit was also the merge conflict against the new base. --- changelog.d/965.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 changelog.d/965.md diff --git a/changelog.d/965.md b/changelog.d/965.md new file mode 100644 index 000000000..0814fdcf3 --- /dev/null +++ b/changelog.d/965.md @@ -0,0 +1,5 @@ +- #965 Clean up star-list handling, autoimport parsing and worder naming, + and fix same-package import filtering in autoimport: comparing + `package_name` with `is` instead of `==` meant same-package imports + were not recognised as such, so they leaked into autoimport results + instead of being skipped. (@Ketankhunti)