@@ -636,31 +636,30 @@ def _import_module_using_spec(
636636
637637 if spec_matches_module_path (spec , module_path ):
638638 assert spec is not None
639+ # Attempt to import the parent module, seems is our responsibility:
640+ # https://github.com/python/cpython/blob/73906d5c908c1e0b73c5436faeff7d93698fc074/Lib/importlib/_bootstrap.py#L1308-L1311
641+ parent_module_name , _ , name = module_name .rpartition ("." )
642+ parent_module : Optional [ModuleType ] = sys .modules .get (parent_module_name )
643+ if parent_module is None and parent_module_name :
644+ with contextlib .suppress (ModuleNotFoundError , ImportWarning ):
645+ parent_module = importlib .import_module (parent_module_name )
646+
647+ # Find spec and import this module.
639648 mod = importlib .util .module_from_spec (spec )
640649 sys .modules [module_name ] = mod
641650 spec .loader .exec_module (mod ) # type: ignore[union-attr]
651+
652+ # Set this module as an attribute of the parent module (#12194).
653+ if parent_module is not None :
654+ setattr (parent_module , name , mod )
655+
642656 if insert_modules :
643657 insert_missing_modules (sys .modules , module_name )
644- _set_name_in_parent (mod )
645658 return mod
646659
647660 return None
648661
649662
650- def _set_name_in_parent (module : ModuleType ) -> None :
651- """
652- Sets an attribute in the module's parent pointing to the module itself (#12194).
653-
654- Based on https://github.com/python/cpython/blob/73906d5c908c1e0b73c5436faeff7d93698fc074/Lib/importlib/_bootstrap.py#L1335-L1342.
655- """
656- parent , _ , name = module .__name__ .rpartition ("." )
657- if not parent :
658- return
659- parent_module = sys .modules .get (parent )
660- if parent_module is not None :
661- setattr (sys .modules [parent ], name , module )
662-
663-
664663def spec_matches_module_path (
665664 module_spec : Optional [ModuleSpec ], module_path : Path
666665) -> bool :
0 commit comments