Skip to content

Commit

Permalink
Provide first component of dotted path to namespace searches (#1575)
Browse files Browse the repository at this point in the history
* Use first component of dotted path only in namespace searches

* Add test and catch KeyError instead of altering search strategy
  • Loading branch information
jacobtylerwalls authored May 30, 2022
1 parent 1520834 commit c4cc193
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 7 deletions.
15 changes: 8 additions & 7 deletions astroid/interpreter/_import/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,18 @@ def is_namespace(modname: str) -> bool:
# That's unacceptable here, so we fallback to _find_spec_from_path(), which does
# not, but requires instead that each single parent ('astroid', 'nodes', etc.)
# be specced from left to right.
processed_components = []
last_parent = None
for component in modname.split("."):
processed_components.append(component)
working_modname = ".".join(processed_components)
components = modname.split(".")
for i in range(1, len(components) + 1):
working_modname = ".".join(components[:i])
try:
found_spec = _find_spec_from_path(working_modname, last_parent)
# Search under the highest package name
# Only relevant if package not already on sys.path
# See https:/python/cpython/issues/89754 for reasoning
# Otherwise can raise bare KeyError: https:/python/cpython/issues/93334
found_spec = _find_spec_from_path(working_modname, components[0])
except ValueError:
# executed .pth files may not have __spec__
return True
last_parent = working_modname

if found_spec is None:
return False
Expand Down
Empty file.
2 changes: 2 additions & 0 deletions tests/testdata/python3/data/parent_of_homonym/doc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This submodule should have the same name as a directory in the root of the project that
is _NOT_ a python module. For this reason, it's currently called "doc".
Empty file.
5 changes: 5 additions & 0 deletions tests/unittest_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ def test_identify_old_namespace_package_protocol(self) -> None:
util.is_namespace("tests.testdata.python3.data.path_pkg_resources_1")
)

def test_submodule_homonym_with_non_module(self) -> None:
self.assertFalse(
util.is_namespace("tests.testdata.python3.data.parent_of_homonym.doc")
)

def test_implicit_namespace_package(self) -> None:
data_dir = os.path.dirname(resources.find("data/namespace_pep_420"))
contribute = os.path.join(data_dir, "contribute_to_namespace")
Expand Down

0 comments on commit c4cc193

Please sign in to comment.