File tree Expand file tree Collapse file tree 5 files changed +26
-1
lines changed Expand file tree Collapse file tree 5 files changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -1116,7 +1116,15 @@ def _find_parent_path_names(self):
1116
1116
1117
1117
def _get_parent_path (self ):
1118
1118
parent_module_name , path_attr_name = self ._find_parent_path_names ()
1119
- return getattr (sys .modules [parent_module_name ], path_attr_name )
1119
+ try :
1120
+ module = sys .modules [parent_module_name ]
1121
+ except KeyError as e :
1122
+ raise ModuleNotFoundError (
1123
+ f"{ parent_module_name !r} must be imported before finding { self ._name !r} ." ,
1124
+ name = parent_module_name ,
1125
+ ) from e
1126
+ else :
1127
+ return getattr (module , path_attr_name )
1120
1128
1121
1129
def _recalculate (self ):
1122
1130
# If the parent's path has changed, recalculate _path
Original file line number Diff line number Diff line change
1
+ This directory should not be a package, but should share a name with an
2
+ unrelated subpackage.
Original file line number Diff line number Diff line change @@ -318,6 +318,17 @@ def test_module_before_namespace_package(self):
318
318
self .assertEqual (a_test .attr , 'in module' )
319
319
320
320
321
+ class NamespaceSubpackageSameName (NamespacePackageTest ):
322
+ paths = ['' ]
323
+
324
+ def test_namespace_subpackage_shares_name_with_directory (self ):
325
+ submodule_path = 'project4.foo'
326
+ with self .assertRaises (ModuleNotFoundError ) as cm :
327
+ importlib .machinery .PathFinder .find_spec (submodule_path )
328
+
329
+ self .assertEqual (cm .exception .name , 'project4' )
330
+
331
+
321
332
class ReloadTests (NamespacePackageTest ):
322
333
paths = ['portion1' ]
323
334
Original file line number Diff line number Diff line change @@ -2648,6 +2648,7 @@ TESTSUBDIRS= idlelib/idle_test \
2648
2648
test/test_importlib/namespace_pkgs \
2649
2649
test/test_importlib/namespace_pkgs/both_portions \
2650
2650
test/test_importlib/namespace_pkgs/both_portions/foo \
2651
+ test/test_importlib/namespace_pkgs/foo \
2651
2652
test/test_importlib/namespace_pkgs/module_and_namespace_package \
2652
2653
test/test_importlib/namespace_pkgs/module_and_namespace_package/a_test \
2653
2654
test/test_importlib/namespace_pkgs/not_a_namespace_pkg \
Original file line number Diff line number Diff line change
1
+ Reraise :exc: `KeyError ` as :exc: `ModuleNotFoundError ` when
2
+ :meth: `importlib.machinery.PathFinder.find_spec ` is called on a submodule
3
+ without importing the parent (and without a ``path `` argument).
You can’t perform that action at this time.
0 commit comments