Skip to content

Commit c4cc193

Browse files
Provide first component of dotted path to namespace searches (#1575)
* Use first component of dotted path only in namespace searches * Add test and catch KeyError instead of altering search strategy
1 parent 1520834 commit c4cc193

File tree

5 files changed

+15
-7
lines changed

5 files changed

+15
-7
lines changed

astroid/interpreter/_import/util.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,18 @@ def is_namespace(modname: str) -> bool:
1818
# That's unacceptable here, so we fallback to _find_spec_from_path(), which does
1919
# not, but requires instead that each single parent ('astroid', 'nodes', etc.)
2020
# be specced from left to right.
21-
processed_components = []
22-
last_parent = None
23-
for component in modname.split("."):
24-
processed_components.append(component)
25-
working_modname = ".".join(processed_components)
21+
components = modname.split(".")
22+
for i in range(1, len(components) + 1):
23+
working_modname = ".".join(components[:i])
2624
try:
27-
found_spec = _find_spec_from_path(working_modname, last_parent)
25+
# Search under the highest package name
26+
# Only relevant if package not already on sys.path
27+
# See https://github.com/python/cpython/issues/89754 for reasoning
28+
# Otherwise can raise bare KeyError: https://github.com/python/cpython/issues/93334
29+
found_spec = _find_spec_from_path(working_modname, components[0])
2830
except ValueError:
2931
# executed .pth files may not have __spec__
3032
return True
31-
last_parent = working_modname
3233

3334
if found_spec is None:
3435
return False

tests/testdata/python3/data/parent_of_homonym/__init__.py

Whitespace-only changes.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
This submodule should have the same name as a directory in the root of the project that
2+
is _NOT_ a python module. For this reason, it's currently called "doc".

tests/testdata/python3/data/parent_of_homonym/doc/__init__.py

Whitespace-only changes.

tests/unittest_manager.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,11 @@ def test_identify_old_namespace_package_protocol(self) -> None:
120120
util.is_namespace("tests.testdata.python3.data.path_pkg_resources_1")
121121
)
122122

123+
def test_submodule_homonym_with_non_module(self) -> None:
124+
self.assertFalse(
125+
util.is_namespace("tests.testdata.python3.data.parent_of_homonym.doc")
126+
)
127+
123128
def test_implicit_namespace_package(self) -> None:
124129
data_dir = os.path.dirname(resources.find("data/namespace_pep_420"))
125130
contribute = os.path.join(data_dir, "contribute_to_namespace")

0 commit comments

Comments
 (0)