Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-93334: Fix homonym edge case in PathFinder.find_spec() #98100

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
6 changes: 5 additions & 1 deletion Lib/importlib/_bootstrap_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -1367,7 +1367,11 @@ def _find_parent_path_names(self):

def _get_parent_path(self):
parent_module_name, path_attr_name = self._find_parent_path_names()
return getattr(sys.modules[parent_module_name], path_attr_name)
try:
module = sys.modules[parent_module_name]
except KeyError:
return sys.path
brettcannon marked this conversation as resolved.
Show resolved Hide resolved
return getattr(module, path_attr_name)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
return getattr(module, path_attr_name)
else:
return getattr(module, path_attr_name)


def _recalculate(self):
# If the parent's path has changed, recalculate _path
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_importlib/namespace_pkgs/homonym/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This directory should not be a package, but should share a name with an
brettcannon marked this conversation as resolved.
Show resolved Hide resolved
unrelated subpackage.
1 change: 1 addition & 0 deletions Lib/test/test_importlib/namespace_pkgs/project4/homonym.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
attr = 'homonym'
brettcannon marked this conversation as resolved.
Show resolved Hide resolved
11 changes: 11 additions & 0 deletions Lib/test/test_importlib/test_namespace_pkgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,17 @@ def test_module_before_namespace_package(self):
self.assertEqual(a_test.attr, 'in module')


class DirectoryHomonym(NamespacePackageTest):
paths = ['']

def test_namespace_package_submodule_homonym(self):
submodule_path = 'project4.homonym'
got = importlib.machinery.PathFinder.find_spec(submodule_path)
self.assertEqual(got.name, submodule_path)
self.assertIsNone(got.loader)
self.assertNotIn('project4', got.submodule_search_locations[0])


class ReloadTests(NamespacePackageTest):
paths = ['portion1']

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Prevent :exc:`KeyError` thrown by :meth:`importlib.machinery.PathFinder.find_spec`
when a directory that is not a module shares a name with a namespace package
submodule, and where a ``path`` argument is not provided.
Loading