Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Lib/importlib/_bootstrap_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -1377,7 +1377,14 @@ 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 as e:
raise ModuleNotFoundError(
f"{parent_module_name} must be imported before finding {self._name}.",
name=parent_module_name,
) from e
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/foo/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
unrelated subpackage.
10 changes: 10 additions & 0 deletions Lib/test/test_importlib/test_namespace_pkgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,16 @@ def test_module_before_namespace_package(self):
self.assertEqual(a_test.attr, 'in module')


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

def test_namespace_subpackage_shares_name_with_directory(self):
submodule_path = 'project4.foo'
msg = 'project4 must be imported before finding project4.foo.'
with self.assertRaisesRegex(ModuleNotFoundError, msg):
importlib.machinery.PathFinder.find_spec(submodule_path)


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

Expand Down
1 change: 1 addition & 0 deletions Makefile.pre.in
Original file line number Diff line number Diff line change
Expand Up @@ -2427,6 +2427,7 @@ TESTSUBDIRS= idlelib/idle_test \
test/test_importlib/namespace_pkgs \
test/test_importlib/namespace_pkgs/both_portions \
test/test_importlib/namespace_pkgs/both_portions/foo \
test/test_importlib/namespace_pkgs/foo \
test/test_importlib/namespace_pkgs/module_and_namespace_package \
test/test_importlib/namespace_pkgs/module_and_namespace_package/a_test \
test/test_importlib/namespace_pkgs/not_a_namespace_pkg \
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Reraise :exc:`KeyError` as :exc:`ModuleNotFoundError` when
:meth:`importlib.machinery.PathFinder.find_spec` is called on a submodule
without importing the parent (and without a ``path`` argument).
Loading