Repository navigation
Refactor star-list handling, autoimport parsing and worder naming - #965
Ketankhunti wants to merge 14 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Hi @mcepl, Can you review this pull request? |
mcepl
left a comment
There was a problem hiding this comment.
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?
|
@mcepl Thanks for the review! All five addressed and pushed:
Verification: affected packages |
mcepl
left a comment
There was a problem hiding this comment.
Thanks @Ketankhunti, that covers everything I asked for. A few small things before this can go in:
- Rebase on master. The PR currently conflicts with master. It looks like only
CHANGELOG.mdis affected. Once it's rebased I'll approve the workflow runs so the full test suite, Black and CodeQL run on it. - Fix the description and CHANGELOG wording. Changing
isto==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". - Remove the duplicate test case. In
test_names_from_relative_import, thehelperandthingcases test exactly the same thing. Please keep just one, alongside theas hcase. - The
"".join(["p", "k", "g"])isn't needed.node.module.split(".")[0]always creates a new string object, so the oldischeck 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. - Optional: squash the history into a few logical commits, since some of them add code that a later one removes (
_StarListCollector, theSimpleNamespacetest). If not, I'll squash-merge.
After that and green CI, I'm happy to merge.
- 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.
70d2736 to
ca2928c
Compare
|
Hi @mcepl, thanks for the review — all addressed and pushed:
Verification: affected packages Could you approve the workflow runs when you get a chance? |
|
@Ketankhunti, one more housekeeping request, sorry: #985 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 nothingThen create - #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 git add changelog.d/965.md
git commit -m "Add changelog fragment for #965"
git push --force-with-leaseUntil #985 lands on |
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.
- 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.
6e36373 to
f45c3ec
Compare
|
Hi @mcepl, done — thanks for the heads-up on the new system:
Verification: affected packages Could you approve the workflow runs when you get a chance? |
| if not node.module or package_name == node.module.split(".")[0]: | ||
| return | ||
| for name in node.names: | ||
| if isinstance(name, ast.alias): |
There was a problem hiding this comment.
This can just go:
| 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): |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
Likewise, these cases are actually testing three different things and shouldn't have been merged.
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| _NODE_TYPE_MAP = ( |
There was a problem hiding this comment.
_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
left a comment
There was a problem hiding this comment.
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 toison this branch, all 11 tests in
parsetest.pystill 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 thinginside packagepkgyieldsthing
withisand is skipped with==.
Please:
- add a test case
from .pkg.sub import thingwith
package_name="pkg"(that one fails withisand passes with
==), and drop the "always creates a new string object" comment; - correct
changelog.d/965.mdand 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_MAPshould be a list of tuples, not a tuple of tuples.- With the
elsebranch gone,if isinstance(name, ast.alias):is a
silent no-op filter (ImportFrom.namesonly holdsaliasnodes);
drop it or turn it into anassert. - Split the parametrised tests back into separately named tests with
a clear Arrange/Act/Assert structure; theas hcase and the three
skip cases each test a different thing.
3. Minor
(ast.Assign, NameType.Variable)in_NODE_TYPE_MAPis redundant
with the defaultVariable. Honestly, for three entries the
originalifchain 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(...) -> Listcould 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).
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.
f45c3ec to
003b5fc
Compare
|
@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 |
Cleanups in three areas, plus one behaviour fix.
rope/base/worder.py
Worder.dumb_findertofallback_finder. The old name isvague; the field holds a plain finder over the original source used
when the offset falls inside an ignored region.
rope/contrib/autoimport/parse.py
isinstanceif-chain inget_type_astwith a dispatchtable (
_NODE_TYPE_MAP). Same semantics; a new node kind now needsone table entry instead of another branch.
_names_from_importfromfromget_names_from_file. Therelative from-import loop is now a standalone generator, testable
in isolation.
package_name is ...identity comparison to==.This is a behaviour change: same-package relative imports (e.g.
from .pkg import thinginside packagepkg) were never skippedbefore, because the identity check always failed
(
node.module.split(".")[0]creates a new string object). Theyare now skipped, as intended.
aliaselse branch (ImportFrom.namesalways holds
aliasnodes).rope/refactor/importutils/module_imports.py
is_str_constant,is_name_ref,is_str_assignment) for the repeatedisinstancechecks in_get_all_star_list._resolve_nameto module-level_resolve_assigned_names(it never usedself); updates the threecall 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 sincenode.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):
blackandisortclean on all touched files.pytest ropetest/contrib/autoimport/ ropetest/refactor/importutilstest.py ropetest/codeanalyzetest.py— 383 passed.pytest -q— 2188 passed, 12 skipped, 5 xfailed.cc @lieryan @mcepl — happy to split or adjust.