@@ -424,6 +424,64 @@ def __exit__(self, *args, **kwargs):
424424 self ._lock .release ()
425425
426426
427+ def _get_module_chain (name ):
428+ """Return the chain of dotted-name prefixes from root to leaf.
429+
430+ For example: 'a.b.c' -> ['a', 'a.b', 'a.b.c']
431+ """
432+ parts = name .split ('.' )
433+ return ['.' .join (parts [:i + 1 ]) for i in range (len (parts ))]
434+
435+
436+ class _HierarchicalLockManager :
437+ """Manages acquisition of multiple module locks in hierarchical order.
438+
439+ This prevents deadlocks by ensuring all threads acquire locks in the
440+ same order (parent modules before child modules).
441+ """
442+
443+ def __init__ (self , name ):
444+ self ._name = name
445+ self ._module_chain = _get_module_chain (name )
446+ self ._locks = []
447+
448+ def __enter__ (self ):
449+ try :
450+ for module_name in self ._module_chain :
451+ # Only acquire lock if module is not already fully loaded
452+ module = sys .modules .get (module_name )
453+ if (module is None or
454+ getattr (getattr (module , "__spec__" , None ),
455+ "_initializing" , False )):
456+ lock = _get_module_lock (module_name )
457+ try :
458+ lock .acquire ()
459+ except _DeadlockError :
460+ if module_name == self ._name :
461+ raise
462+ # The parent is being initialised by a thread that
463+ # is (transitively) waiting on a lock we hold.
464+ # Apply the same policy as _lock_unlock_module():
465+ # accept a partially-initialised parent for circular
466+ # imports rather than failing the whole chain.
467+ continue
468+ self ._locks .append ((module_name , lock ))
469+ except :
470+ # __exit__ is not called when __enter__ raises (e.g. _DeadlockError
471+ # on the leaf lock, or KeyboardInterrupt), so release whatever we
472+ # already hold to avoid permanently leaking held module locks.
473+ for module_name , lock in reversed (self ._locks ):
474+ lock .release ()
475+ self ._locks .clear ()
476+ raise
477+ return self
478+
479+ def __exit__ (self , * args , ** kwargs ):
480+ for module_name , lock in reversed (self ._locks ):
481+ lock .release ()
482+ self ._locks .clear ()
483+
484+
427485# The following two functions are for consumption by Python/import.c.
428486
429487def _get_module_lock (name ):
@@ -521,24 +579,6 @@ def _requires_frozen_wrapper(self, fullname):
521579 return _requires_frozen_wrapper
522580
523581
524- # Typically used by loader classes as a method replacement.
525- def _load_module_shim (self , fullname ):
526- """Load the specified module into sys.modules and return it.
527-
528- This method is deprecated. Use loader.exec_module() instead.
529-
530- """
531- msg = ("the load_module() method is deprecated and slated for removal in "
532- "Python 3.15; use exec_module() instead" )
533- _warnings .warn (msg , DeprecationWarning )
534- spec = spec_from_loader (fullname , self )
535- if fullname in sys .modules :
536- module = sys .modules [fullname ]
537- _exec (spec , module )
538- return sys .modules [fullname ]
539- else :
540- return _load (spec )
541-
542582# Module specifications #######################################################
543583
544584def _module_repr (module ):
@@ -583,8 +623,7 @@ class ModuleSpec:
583623 `has_location` indicates that a spec's "origin" reflects a location.
584624 When this is True, `__file__` attribute of the module is set.
585625
586- `cached` is the location of the cached bytecode file, if any. It
587- corresponds to the `__cached__` attribute.
626+ `cached` is the location of the cached bytecode file, if any.
588627
589628 `submodule_search_locations` is the sequence of path entries to
590629 search when importing submodules. If set, is_package should be
@@ -717,18 +756,14 @@ def _spec_from_module(module, loader=None, origin=None):
717756 origin = getattr (loader , '_ORIGIN' , None )
718757 if not origin and location is not None :
719758 origin = location
720- try :
721- cached = module .__cached__
722- except AttributeError :
723- cached = None
724759 try :
725760 submodule_search_locations = list (module .__path__ )
726761 except AttributeError :
727762 submodule_search_locations = None
728763
729764 spec = ModuleSpec (name , loader , origin = origin )
730765 spec ._set_fileattr = False if location is None else (origin == location )
731- spec .cached = cached
766+ spec .cached = None
732767 spec .submodule_search_locations = submodule_search_locations
733768 return spec
734769
@@ -763,8 +798,7 @@ def _init_module_attrs(spec, module, *, override=False):
763798 # should also be None for consistency. While a bit of a hack,
764799 # this is the best place to ensure this consistency.
765800 #
766- # See # https://docs.python.org/3/library/importlib.html#importlib.abc.Loader.load_module
767- # and bpo-32305
801+ # See bpo-32305
768802 module .__file__ = None
769803 try :
770804 module .__loader__ = loader
@@ -789,20 +823,14 @@ def _init_module_attrs(spec, module, *, override=False):
789823 module .__path__ = spec .submodule_search_locations
790824 except AttributeError :
791825 pass
792- # __file__/__cached__
826+ # __file__
793827 if spec .has_location :
794828 if override or getattr (module , '__file__' , None ) is None :
795829 try :
796830 module .__file__ = spec .origin
797831 except AttributeError :
798832 pass
799833
800- if override or getattr (module , '__cached__' , None ) is None :
801- if spec .cached is not None :
802- try :
803- module .__cached__ = spec .cached
804- except AttributeError :
805- pass
806834 return module
807835
808836
@@ -844,7 +872,7 @@ def _module_repr_from_spec(spec):
844872 return f'<module { spec .name !r} ({ spec .origin } )>'
845873
846874
847- # Used by importlib.reload() and _load_module_shim() .
875+ # Used by importlib.reload().
848876def _exec (spec , module ):
849877 """Execute the spec's specified module in an existing module's namespace."""
850878 name = spec .name
@@ -860,67 +888,16 @@ def _exec(spec, module):
860888 _init_module_attrs (spec , module , override = True )
861889 else :
862890 _init_module_attrs (spec , module , override = True )
863- if not hasattr (spec .loader , 'exec_module' ):
864- msg = (f"{ _object_name (spec .loader )} .exec_module() not found; "
865- "falling back to load_module()" )
866- _warnings .warn (msg , ImportWarning )
867- spec .loader .load_module (name )
868- else :
869- spec .loader .exec_module (module )
891+ spec .loader .exec_module (module )
870892 finally :
871893 # Update the order of insertion into sys.modules for module
872894 # clean-up at shutdown.
873895 module = sys .modules .pop (spec .name )
874896 sys .modules [spec .name ] = module
875897 return module
876898
877-
878- def _load_backward_compatible (spec ):
879- # It is assumed that all callers have been warned about using load_module()
880- # appropriately before calling this function.
881- try :
882- spec .loader .load_module (spec .name )
883- except :
884- if spec .name in sys .modules :
885- module = sys .modules .pop (spec .name )
886- sys .modules [spec .name ] = module
887- raise
888- # The module must be in sys.modules at this point!
889- # Move it to the end of sys.modules.
890- module = sys .modules .pop (spec .name )
891- sys .modules [spec .name ] = module
892- if getattr (module , '__loader__' , None ) is None :
893- try :
894- module .__loader__ = spec .loader
895- except AttributeError :
896- pass
897- if getattr (module , '__package__' , None ) is None :
898- try :
899- # Since module.__path__ may not line up with
900- # spec.submodule_search_paths, we can't necessarily rely
901- # on spec.parent here.
902- module .__package__ = module .__name__
903- if not hasattr (module , '__path__' ):
904- module .__package__ = spec .name .rpartition ('.' )[0 ]
905- except AttributeError :
906- pass
907- if getattr (module , '__spec__' , None ) is None :
908- try :
909- module .__spec__ = spec
910- except AttributeError :
911- pass
912- return module
913-
914899def _load_unlocked (spec ):
915900 # A helper for direct use by the import system.
916- if spec .loader is not None :
917- # Not a namespace package.
918- if not hasattr (spec .loader , 'exec_module' ):
919- msg = (f"{ _object_name (spec .loader )} .exec_module() not found; "
920- "falling back to load_module()" )
921- _warnings .warn (msg , ImportWarning )
922- return _load_backward_compatible (spec )
923-
924901 module = module_from_spec (spec )
925902
926903 # This must be done before putting the module in sys.modules
@@ -954,8 +931,7 @@ def _load_unlocked(spec):
954931
955932 return module
956933
957- # A method used during testing of _load_unlocked() and by
958- # _load_module_shim().
934+ # A method used during testing of _load_unlocked().
959935def _load (spec ):
960936 """Return a new module object, loaded by the spec's loader.
961937
@@ -1020,8 +996,6 @@ def is_package(cls, fullname):
1020996 """Return False as built-in modules are never packages."""
1021997 return False
1022998
1023- load_module = classmethod (_load_module_shim )
1024-
1025999
10261000class FrozenImporter :
10271001
@@ -1178,25 +1152,6 @@ def exec_module(module):
11781152 code = _call_with_frames_removed (_imp .get_frozen_object , name )
11791153 exec (code , module .__dict__ )
11801154
1181- @classmethod
1182- def load_module (cls , fullname ):
1183- """Load a frozen module.
1184-
1185- This method is deprecated. Use exec_module() instead.
1186-
1187- """
1188- # Warning about deprecation implemented in _load_module_shim().
1189- module = _load_module_shim (cls , fullname )
1190- info = _imp .find_frozen (fullname )
1191- assert info is not None
1192- _ , ispkg , origname = info
1193- module .__origname__ = origname
1194- vars (module ).pop ('__file__' , None )
1195- if ispkg :
1196- module .__path__ = []
1197- cls ._fix_up_module (module )
1198- return module
1199-
12001155 @classmethod
12011156 @_requires_frozen
12021157 def get_code (cls , fullname ):
@@ -1305,8 +1260,16 @@ def _sanity_check(name, package, level):
13051260
13061261_ERR_MSG_PREFIX = 'No module named '
13071262
1308- def _find_and_load_unlocked (name , import_ ):
1263+ def _find_and_load_unlocked (name , import_ , * , lazy_submodule = False ):
13091264 path = None
1265+ sys .audit (
1266+ "import" ,
1267+ name ,
1268+ path ,
1269+ getattr (sys , "path" , None ),
1270+ getattr (sys , "meta_path" , None ),
1271+ getattr (sys , "path_hooks" , None )
1272+ )
13101273 parent = name .rpartition ('.' )[0 ]
13111274 parent_spec = None
13121275 if parent :
@@ -1320,6 +1283,8 @@ def _find_and_load_unlocked(name, import_):
13201283 try :
13211284 path = parent_module .__path__
13221285 except AttributeError :
1286+ if lazy_submodule :
1287+ return None
13231288 msg = f'{ _ERR_MSG_PREFIX } { name !r} ; { parent !r} is not a package'
13241289 raise ModuleNotFoundError (msg , name = name ) from None
13251290 parent_spec = parent_module .__spec__
@@ -1332,6 +1297,8 @@ def _find_and_load_unlocked(name, import_):
13321297 child = name .rpartition ('.' )[2 ]
13331298 spec = _find_spec (name , path )
13341299 if spec is None :
1300+ if lazy_submodule :
1301+ return None
13351302 raise ModuleNotFoundError (f'{ _ERR_MSG_PREFIX } { name !r} ' , name = name )
13361303 else :
13371304 if parent_spec :
@@ -1351,24 +1318,37 @@ def _find_and_load_unlocked(name, import_):
13511318 except AttributeError :
13521319 msg = f"Cannot set an attribute on { parent !r} for child module { child !r} "
13531320 _warnings .warn (msg , ImportWarning )
1321+ # Set attributes to lazy submodules on the module.
1322+ try :
1323+ _imp ._set_lazy_attributes (module , name )
1324+ except Exception as e :
1325+ msg = f"Cannot set lazy attributes on { name !r} : { e !r} "
1326+ _warnings .warn (msg , ImportWarning )
13541327 return module
13551328
13561329
13571330_NEEDS_LOADING = object ()
13581331
13591332
1360- def _find_and_load (name , import_ ):
1333+ def _find_and_load (name , import_ , * , lazy_submodule = False ):
13611334 """Find and load the module."""
13621335
13631336 # Optimization: we avoid unneeded module locking if the module
13641337 # already exists in sys.modules and is fully initialized.
13651338 module = sys .modules .get (name , _NEEDS_LOADING )
13661339 if (module is _NEEDS_LOADING or
13671340 getattr (getattr (module , "__spec__" , None ), "_initializing" , False )):
1368- with _ModuleLockManager (name ):
1341+
1342+ if '.' in name :
1343+ lock_manager = _HierarchicalLockManager (name )
1344+ else :
1345+ lock_manager = _ModuleLockManager (name )
1346+
1347+ with lock_manager :
13691348 module = sys .modules .get (name , _NEEDS_LOADING )
13701349 if module is _NEEDS_LOADING :
1371- return _find_and_load_unlocked (name , import_ )
1350+ return _find_and_load_unlocked (
1351+ name , import_ , lazy_submodule = lazy_submodule )
13721352
13731353 # Optimization: only call _bootstrap._lock_unlock_module() if
13741354 # module.__spec__._initializing is True.
@@ -1382,7 +1362,7 @@ def _find_and_load(name, import_):
13821362 # to preserve normal semantics: the caller gets the exception from
13831363 # the actual import failure rather than a synthetic error.
13841364 if sys .modules .get (name ) is not module :
1385- return _find_and_load (name , import_ )
1365+ return _find_and_load (name , import_ , lazy_submodule = lazy_submodule )
13861366
13871367 if module is None :
13881368 message = f'import of { name } halted; None in sys.modules'
@@ -1391,6 +1371,10 @@ def _find_and_load(name, import_):
13911371 return module
13921372
13931373
1374+ def _find_and_load_lazy_submodule (name , import_ ):
1375+ return _find_and_load (name , import_ , lazy_submodule = True )
1376+
1377+
13941378def _gcd_import (name , package = None , level = 0 ):
13951379 """Import and return the module based on its name, the package the call is
13961380 being made from, and the level adjustment.
0 commit comments