11"""Utility code for constructing importers, etc."""
22
3+ from . import _bootstrap
34from ._bootstrap import _resolve_name
45from ._bootstrap import _find_spec
56
@@ -168,6 +169,33 @@ def override(self):
168169 return - 1 if self .disable_check else 1
169170
170171
172+ class _LazyModuleLock :
173+
174+ """Hold the import system's lock for a module while it loads lazily.
175+
176+ Unlike a plain lock, the module lock detects a deadlock between threads
177+ that are loading each other's modules. On a deadlock, proceed without the
178+ lock as _bootstrap._lock_unlock_module() does for eager imports, so that
179+ the partially initialized module is returned.
180+ """
181+
182+ def __init__ (self , name ):
183+ self ._lock = _bootstrap ._get_module_lock (name )
184+ self ._acquired = False
185+
186+ def __enter__ (self ):
187+ try :
188+ self ._lock .acquire ()
189+ except _bootstrap ._DeadlockError :
190+ pass
191+ else :
192+ self ._acquired = True
193+
194+ def __exit__ (self , * args ):
195+ if self ._acquired :
196+ self ._lock .release ()
197+
198+
171199class _LazyModule (types .ModuleType ):
172200
173201 """A subclass of the module type which triggers loading upon attribute access."""
@@ -176,7 +204,7 @@ def __getattribute__(self, attr):
176204 """Trigger the load of the module and return the attribute."""
177205 __spec__ = object .__getattribute__ (self , '__spec__' )
178206 loader_state = __spec__ .loader_state
179- with loader_state [ 'lock' ] :
207+ with _LazyModuleLock ( __spec__ . name ) :
180208 # Only the first thread to get the lock should trigger the load
181209 # and reset the module's class. The rest can now getattr().
182210 if object .__getattribute__ (self , '__class__' ) is _LazyModule :
@@ -259,9 +287,6 @@ def create_module(self, spec):
259287
260288 def exec_module (self , module ):
261289 """Make the module load lazily."""
262- # Threading is only needed for lazy loading, and importlib.util can
263- # be pulled in at interpreter startup, so defer until needed.
264- import threading
265290 module .__spec__ .loader = self .loader
266291 module .__loader__ = self .loader
267292 # Don't need to worry about deep-copying as trying to set an attribute
@@ -271,7 +296,6 @@ def exec_module(self, module):
271296 loader_state = {}
272297 loader_state ['__dict__' ] = module .__dict__ .copy ()
273298 loader_state ['__class__' ] = module .__class__
274- loader_state ['lock' ] = threading .RLock ()
275299 loader_state ['is_loading' ] = False
276300 module .__spec__ .loader_state = loader_state
277301 module .__class__ = _LazyModule
0 commit comments