Skip to content

Refactor star-list handling, autoimport parsing and worder naming - #965

Open
Ketankhunti wants to merge 14 commits into
python-rope:masterfrom
Ketankhunti:refactor/assignment-cleanups
Open

Ketankhunti wants to merge 14 commits into
python-rope:masterfrom
Ketankhunti:refactor/assignment-cleanups

Conversation

@Ketankhunti

@Ketankhunti Ketankhunti commented Nov 22, 2026 •

Copy link
Copy Markdown

Cleanups in three areas, plus one behaviour fix.

rope/base/worder.py

  • Rename Worder.dumb_finder to fallback_finder. The old name is
    vague; the field holds a plain finder over the original source used
    when the offset falls inside an ignored region.

rope/contrib/autoimport/parse.py

  • Replace the isinstance if-chain in get_type_ast with a dispatch
    table (_NODE_TYPE_MAP). Same semantics; a new node kind now needs
    one table entry instead of another branch.
  • Extract _names_from_importfrom from get_names_from_file. The
    relative from-import loop is now a standalone generator, testable
    in isolation.
  • Fix pre-existing package_name is ... identity comparison to ==.
    This is a behaviour change: same-package relative imports (e.g.
    from .pkg import thing inside package pkg) were never skipped
    before, because the identity check always failed
    (node.module.split(".")[0] creates a new string object). They
    are now skipped, as intended.
  • Remove the unreachable non-alias else branch (ImportFrom.names
    always holds alias nodes).

rope/refactor/importutils/module_imports.py

  • Introduce explaining variables (is_str_constant, is_name_ref,
    is_str_assignment) for the repeated isinstance checks in
    _get_all_star_list.
  • Move the nested _resolve_name to module-level
    _resolve_assigned_names (it never used self); updates the three
    call sites.

Tests: 7 new test cases in ropetest/contrib/autoimport/parsetest.py
(2 relative-import + 3 skip-path params, underlined filtering,
no-process_imports ignore; file total 11 passed; the same-package
case uses a plain "pkg" literal, which guards the == fix since
node.module.split(".")[0] always creates a new string object).
CHANGELOG: entry for #965, noting the same-package import filtering fix.

Verification (after rebase on master):

  • black and isort clean on all touched files.
  • pytest ropetest/contrib/autoimport/ ropetest/refactor/importutilstest.py ropetest/codeanalyzetest.py — 383 passed.
  • Full suite pytest -q — 2188 passed, 12 skipped, 5 xfailed.

cc @lieryan @mcepl — happy to split or adjust.

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.51%. Comparing base (40f4a84) to head (003b5fc).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #965      +/-   ##
==========================================
+ Coverage   95.46%   95.51%   +0.05%     
==========================================
  Files         134      134              
  Lines       26946    26968      +22     
==========================================
+ Hits        25723    25758      +35     
+ Misses       1223     1210      -13     

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

@Ketankhunti

Copy link
Copy Markdown
Author

Hi @mcepl, Can you review this pull request?

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

Thanks! The _names_from_importfrom extraction and _resolve_assigned_names move are welcome. Could you please (1) fix the pre-existing package_name is … → == and make test_same_package_import_is_skipped use a relative import so it actually exercises that check, (2) drop _StarListCollector — it adds indirection without simplifying anything, (3) remove the unreachable non-alias branch rather than testing it with a SimpleNamespace, (4) de-duplicate the relative-import tests, and (5) add a CHANGELOG entry?

Ketankhunti added a commit to Ketankhunti/rope that referenced this pull request Nov 28, 2026
@Ketankhunti

Copy link
Copy Markdown
Author

@mcepl Thanks for the review! All five addressed and pushed:

  1. package_name is ... → == (pre-existing bug).
  2. _StarListCollector dropped; plain result/assignments locals kept with the explaining variables and moved resolver.
  3. Unreachable non-alias else branch removed instead of tested.
  4. Relative-import tests de-duplicated via parametrize; the same-package skip now uses a relative import (from .pkg import thing) with a dynamically built package name, so it covers the check and guards the == fix.
  5. CHANGELOG entry for Refactor star-list handling, autoimport parsing and worder naming #965 added.

Verification: affected packages pytest ropetest/contrib/autoimport/ ropetest/refactor/importutilstest.py ropetest/codeanalyzetest.py — 384 passed; full suite — 2185 passed, 8 skipped, 5 xfailed; black/isort clean.

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

Thanks @Ketankhunti, that covers everything I asked for. A few small things before this can go in:

  1. Rebase on master. The PR currently conflicts with master. It looks like only CHANGELOG.md is affected. Once it's rebased I'll approve the workflow runs so the full test suite, Black and CodeQL run on it.
  2. Fix the description and CHANGELOG wording. Changing is to == is a real behaviour change: before, same-package relative imports were never skipped because the identity check always failed. Please drop "no functional change" from the PR description and mention the fix in the CHANGELOG line, e.g. "…and fix same-package import filtering in autoimport".
  3. Remove the duplicate test case. In test_names_from_relative_import, the helper and thing cases test exactly the same thing. Please keep just one, alongside the as h case.
  4. The "".join(["p", "k", "g"]) isn't needed. node.module.split(".")[0] always creates a new string object, so the old is check would fail even with a plain "pkg" literal. A literal is enough; if you keep the comment, it should say the test guards the == fix in general.
  5. Optional: squash the history into a few logical commits, since some of them add code that a later one removes (_StarListCollector, the SimpleNamespace test). If not, I'll squash-merge.

After that and green CI, I'm happy to merge.

Ketankhunti added a commit to Ketankhunti/rope that referenced this pull request Nov 29, 2026
Ketankhunti added a commit to Ketankhunti/rope that referenced this pull request Nov 29, 2026
- 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.
@Ketankhunti
Ketankhunti force-pushed the refactor/assignment-cleanups branch from 70d2736 to ca2928c Compare November 29, 2026 23:15
@Ketankhunti

Copy link
Copy Markdown
Author

Hi @mcepl, thanks for the review — all addressed and pushed:

  1. Rebased on master. The CHANGELOG conflict is resolved; the Refactor star-list handling, autoimport parsing and worder naming #965 entry is now under Upcoming release (1.16.0 shipped in the meantime).
  2. Description and CHANGELOG wording fixed. Dropped "no functional change" from the description. Both now say the is to == change is a behaviour fix: same-package relative imports were never skipped before, because the identity check always failed.
  3. Duplicate test removed. In test_names_from_relative_import, kept helper and helper as h, dropped thing.
  4. "".join(["p", "k", "g"]) removed. The same-package test now uses a plain "pkg" literal, with a comment noting it guards the == fix, since node.module.split(".")[0] always creates a new string object.
  5. Squash: left the history as-is — happy for you to squash-merge.

Verification: affected packages pytest ropetest/contrib/autoimport/ ropetest/refactor/importutilstest.py ropetest/codeanalyzetest.py — 383 passed; full suite pytest -q — 2188 passed, 12 skipped, 5 xfailed; black/isort clean.

Could you approve the workflow runs when you get a chance?

@Ketankhunti
Ketankhunti requested a review from mcepl November 30, 2026 00:55
@mcepl
mcepl changed the base branch from master to changelog-news-fragments November 30, 2026 10:08
@mcepl

mcepl commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

@Ketankhunti, one more housekeeping request, sorry: #985
replaces direct edits of CHANGELOG.md with per-PR fragments in
changelog.d/, so that parallel PRs stop conflicting on the top
of CHANGELOG.md. Please rebase this PR on top of #985 and move
your entry from CHANGELOG.md into changelog.d/965.md:

git remote add upstream https://github.com/python-rope/rope.git  # if not there yet
git fetch upstream pull/985/head:changelog-news-fragments
git rebase changelog-news-fragments
# whenever the rebase stops on a CHANGELOG.md conflict:
git checkout changelog-news-fragments -- CHANGELOG.md
git rebase --continue
# make sure CHANGELOG.md is now untouched by this PR:
git diff changelog-news-fragments -- CHANGELOG.md   # should print nothing

Then create changelog.d/965.md (by hand, or with
python bin/news.py 965, which opens it in your editor)
containing your existing
entry, with continuation lines indented by two spaces:

- #965 Clean up star-list handling, autoimport parsing and worder
  naming, and fix same-package import filtering in autoimport
  (@Ketankhunti)

Feel free to make it a bit longer and more explanatory than the
one-liner, e.g. briefly saying that same-package relative imports
were never skipped before because of the is identity check. See
changelog.d/README.md on the #985 branch for details.

git add changelog.d/965.md
git commit -m "Add changelog fragment for #965"
git push --force-with-lease

Until #985 lands on master, the PR diff will also show the
#985 commits; that is expected and will disappear once #985 is
merged. Thanks!

Ketankhunti added a commit to Ketankhunti/rope that referenced this pull request Nov 30, 2026
mcepl asked for this on python-rope#965 (2026-11-30): python-rope#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.
Ketankhunti added a commit to Ketankhunti/rope that referenced this pull request Nov 30, 2026
- 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.
Ketankhunti added a commit to Ketankhunti/rope that referenced this pull request Nov 30, 2026
mcepl asked for this on python-rope#965 (2026-11-30): python-rope#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.
@Ketankhunti
Ketankhunti force-pushed the refactor/assignment-cleanups branch from 6e36373 to f45c3ec Compare November 30, 2026 23:20
@Ketankhunti

Copy link
Copy Markdown
Author

Hi @mcepl, done — thanks for the heads-up on the new system:

Verification: affected packages pytest ropetest/contrib/autoimport/ ropetest/refactor/importutilstest.py ropetest/codeanalyzetest.py — 383 passed; black/isort clean.

Could you approve the workflow runs when you get a chance?

@lieryan lieryan left a comment

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.

Thanks the refactoring looks fine and the is check definitely looks wrong and is the correct call to fix it, just a couple things to address here.

Also, yes, please rebase and drop the _StarListCollector commits as per @mcepl.

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?

("from .sub import thing\n", "thing"),
],
)
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

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.

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.

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

Thanks @Ketankhunti, the refactoring itself is fine, but I have to
walk back something I said earlier, and it affects the headline fix.

1. The is → == fix: wrong rationale, and the test doesn't guard it

In my previous review I claimed that node.module.split(".")[0]
always creates a new string object. That is wrong, sorry. In CPython
str.split returns the original object when the separator is not
found; identifiers from the AST are interned by the parser, pathlib
interns path parts (so package.name is interned), and the "pkg"
literal in the test is interned too. So for undotted module names the
old is check actually worked.

I verified this:

  • On prettytable/__init__.py (from .prettytable import …) master
    and this PR give the same result: the import is skipped in both.
  • Reverting == back to is on this branch, all 11 tests in
    parsetest.py still pass
    , so ("from .pkg import thing\n", "pkg")
    does not guard the fix at all.
  • The old code only misbehaves for dotted relative modules:
    from .pkg.sub import thing inside package pkg yields thing
    with is and is skipped with ==.

Please:

  • add a test case from .pkg.sub import thing with
    package_name="pkg" (that one fails with is and passes with
    ==), and drop the "always creates a new string object" comment;
  • correct changelog.d/965.md and the PR description: only dotted
    same-package relative imports (from .pkg.sub import …) leaked
    before, not same-package imports in general.

(Pre-existing and out of scope here, but worth noting: the check
compares the first component of a relative module with the
top-level package name, so it only ever fires for the
pkg/__init__.py: from .pkg import X pattern — prettytable,
imagesize, pathspec, pytoolconfig, … — and then hides
from pkg import X from autoimport. That deserves a separate issue.)

2. @lieryan's review is still unaddressed

  • _NODE_TYPE_MAP should be a list of tuples, not a tuple of tuples.
  • With the else branch gone, if isinstance(name, ast.alias): is a
    silent no-op filter (ImportFrom.names only holds alias nodes);
    drop it or turn it into an assert.
  • Split the parametrised tests back into separately named tests with
    a clear Arrange/Act/Assert structure; the as h case and the three
    skip cases each test a different thing.

3. Minor

  • (ast.Assign, NameType.Variable) in _NODE_TYPE_MAP is redundant
    with the default Variable. Honestly, for three entries the
    original if chain was just as clear.
  • The Black-wrapped is_str_constant = isinstance(el, ast.Constant) and isinstance(\n el.value, str\n) reads worse than the original;
    the explaining variables add little there.
  • _resolve_assigned_names(...) -> List could carry the element type.
  • Comment typo carried over: "it's own package" → "its own package".

Once 1 and 2 are addressed and CI is green, I'm happy to squash-merge
(after #985 lands and this PR is retargeted to master).

@mcepl
mcepl deleted the branch python-rope:changelog-news-fragments December 1, 2026 22:17
@mcepl mcepl closed this Dec 1, 2026
@mcepl mcepl reopened this Dec 2, 2026
@mcepl
mcepl changed the base branch from changelog-news-fragments to master December 2, 2026 00:10
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.
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.
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.
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.
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.
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.
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.
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.
Comparing package_name against the first dotted component used
'is'; use '==' instead. Pre-existing issue.
ImportFrom.names always holds ast.alias nodes, so the else branch
could never execute. Removing dead code instead of testing it.
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.
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.
- 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.
mcepl asked for this on python-rope#965 (2026-11-30): python-rope#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.
@mcepl
mcepl force-pushed the refactor/assignment-cleanups branch from f45c3ec to 003b5fc Compare December 2, 2026 00:14
@mcepl

mcepl commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Ketankhunti, heads-up: this PR was stacked on the branch of #985, so when #985 was merged and its branch deleted, GitHub closed this PR automatically. I've reopened it, retargeted it to master, and force-pushed your branch rebased onto the current master. Nothing was lost (all 14 commits are there, and so is changelog.d/965.md). Your local copy is now out of date, though, so before you make any more changes please commit or stash any local work and run git fetch origin && git reset --hard origin/refactor/assignment-cleanups (or whatever your fork's remote is called) rather than pulling or pushing over it. Sorry for the trouble!

This branch has not been deployed

No deployments
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.

3 participants