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
5 changes: 5 additions & 0 deletions changelog.d/965.md
Original file line number Diff line number Diff line change
@@ -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)
4 changes: 2 additions & 2 deletions rope/base/worder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand All @@ -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):
Expand Down
50 changes: 29 additions & 21 deletions rope/contrib/autoimport/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,18 @@
logger = logging.getLogger(__name__)


_NODE_TYPE_MAP = (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_NODE_TYPE_MAP should be list[tuple[ast node, name type]]. tuple are not just immutable list.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list. https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences

List is used when you want a homogenous collection of items. Tuple is used when you want an anonymous class which is usually heterogenous.

(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


Expand Down Expand Up @@ -69,21 +73,25 @@ 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 == node.module.split(".")[0]:
return
for name in node.names:
if isinstance(name, ast.alias):

@lieryan lieryan Dec 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can just go:

Suggested change
if isinstance(name, ast.alias):
if not isinstance(name, ast.alias):
continue

?

But probably might just skip the isinstance check entirely if it always has an ast.alias even when there's no alias? Maybe just turn it into assert isinstance(name, ast.alias) and see if it actually breaks anything?

real_name = name.asname if name.asname else name.name
if underlined or not real_name.startswith("_"):
yield PartialName(real_name, get_type_ast(node))


def get_type_object(imported_object) -> NameType:
Expand Down
54 changes: 29 additions & 25 deletions rope/refactor/importutils/module_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -30,27 +45,14 @@ 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__")
except exceptions.AttributeNotFoundError:
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.
Expand All @@ -69,22 +71,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,
):
for av in _resolve_assigned_names(name):
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:
Expand All @@ -93,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)
Expand Down
69 changes: 69 additions & 0 deletions ropetest/contrib/autoimport/parsetest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging

import pytest

from rope.contrib.autoimport import parse
from rope.contrib.autoimport.defs import Name, NameType, PartialName, Source

Expand Down Expand Up @@ -28,3 +30,70 @@ 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


@pytest.mark.parametrize(
("source_text", "expected"),
[
("from .sub import helper\n", "helper"),
("from .sub import helper as h\n", "h"),
],
)
def test_names_from_relative_import(tmp_path, source_text, expected):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is excessive abstraction in test, which is a code smell. Tests naturally have lots of repetitive code, but it's not always correct or good idea to replace the test cases with a loop/parameterized test.

Agreed with mcepl that, Test 1 (test_names_from_relative_import) and 3 (test_names_from_relative_submodule_import) are duplicate and only one should be kept.

But test 2 (test_names_from_relative_import_with_asname) is a completely different test case and should not have been merged.

If you want to reduce duplication, usually extracting a fixture/assert helper functions with descriptive names would be more appropriate instead of merging the tests.

Also, generally well written tests would be structured with AAA pattern: Arrange (setup/fixture), Act, Assert. This structure should be clearly visible in the main test's body. Generally, helper functions should not cross those boundaries, e.g. a helper function should not be part of an Act and Assert at the same time.

So in this test, for example, this is the AAA structure:

# arrange
source = tmp_path / "mod.py"
source.write_text(source_text, encoding="utf-8")

# act
names = list(
    parse.get_names_from_file(
        source, package_name="pkg", process_imports=True
    )
)

# assert
assert PartialName(expected, NameType.Variable) in names

source = tmp_path / "mod.py"
source.write_text(source_text, encoding="utf-8")
names = list(
parse.get_names_from_file(
source, package_name="pkg", process_imports=True
)
)
assert PartialName(expected, NameType.Variable) in names


@pytest.mark.parametrize(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise, these cases are actually testing three different things and shouldn't have been merged.

("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: 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):
source = tmp_path / "mod.py"
source.write_text(source_text, encoding="utf-8")
assert (
list(
parse.get_names_from_file(
source, package_name=package_name, 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_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")) == []
Loading