Debian Codegraph @

lib-python/3/importlib/util.py

raw symbols SCIP
1 """Utility code for constructing importers, etc."""
2 from ._abc import Loader
3 from ._bootstrap import module_from_spec
4 from ._bootstrap import _resolve_name
5 from ._bootstrap import spec_from_loader
6 from ._bootstrap import _find_spec
7 from ._bootstrap_external import MAGIC_NUMBER
8 from ._bootstrap_external import _RAW_MAGIC_NUMBER
9 from ._bootstrap_external import cache_from_source
10 from ._bootstrap_external import decode_source
11 from ._bootstrap_external import source_from_cache
12 from ._bootstrap_external import spec_from_file_location
13
14 from contextlib import contextmanager
15 import _imp
16 import functools
17 import sys
18 import threading
19 import types
20 import warnings
21
22
23 def source_hash(source_bytes):
24 "Return the hash of *source_bytes* as used in hash-based pyc files."
25 return _imp.source_hash(_RAW_MAGIC_NUMBER, source_bytes)
26
27
28 def resolve_name(name, package):
29 """Resolve a relative module name to an absolute one."""
30 if not name.startswith('.'):
31 return name
32 elif not package:
33 raise ImportError(f'no package specified for {repr(name)} '
34 '(required for relative module names)')
35 level = 0
36 for character in name:
37 if character != '.':
38 break
39 level += 1
40 return _resolve_name(name[level:], package, level)
41
42
43 def _find_spec_from_path(name, path=None):
44 """Return the spec for the specified module.
45
46 First, sys.modules is checked to see if the module was already imported. If
47 so, then sys.modules[name].__spec__ is returned. If that happens to be
48 set to None, then ValueError is raised. If the module is not in
49 sys.modules, then sys.meta_path is searched for a suitable spec with the
50 value of 'path' given to the finders. None is returned if no spec could
51 be found.
52
53 Dotted names do not have their parent packages implicitly imported. You will
54 most likely need to explicitly import all parent packages in the proper
55 order for a submodule to get the correct spec.
56
57 """
58 if name not in sys.modules:
59 return _find_spec(name, path)
60 else:
61 module = sys.modules[name]
62 if module is None:
63 return None
64 try:
65 spec = module.__spec__
66 except AttributeError:
67 raise ValueError('{}.__spec__ is not set'.format(name)) from None
68 else:
69 if spec is None:
70 raise ValueError('{}.__spec__ is None'.format(name))
71 return spec
72
73
74 def find_spec(name, package=None):
75 """Return the spec for the specified module.
76
77 First, sys.modules is checked to see if the module was already imported. If
78 so, then sys.modules[name].__spec__ is returned. If that happens to be
79 set to None, then ValueError is raised. If the module is not in
80 sys.modules, then sys.meta_path is searched for a suitable spec with the
81 value of 'path' given to the finders. None is returned if no spec could
82 be found.
83
84 If the name is for submodule (contains a dot), the parent module is
85 automatically imported.
86
87 The name and package arguments work the same as importlib.import_module().
88 In other words, relative module names (with leading dots) work.
89
90 """
91 fullname = resolve_name(name, package) if name.startswith('.') else name
92 if fullname not in sys.modules:
93 parent_name = fullname.rpartition('.')[0]
94 if parent_name:
95 parent = __import__(parent_name, fromlist=['__path__'])
96 try:
97 parent_path = parent.__path__
98 except AttributeError as e:
99 raise ModuleNotFoundError(
100 f"__path__ attribute not found on {parent_name!r} "
101 f"while trying to find {fullname!r}", name=fullname) from e
102 else:
103 parent_path = None
104 return _find_spec(fullname, parent_path)
105 else:
106 module = sys.modules[fullname]
107 if module is None:
108 return None
109 try:
110 spec = module.__spec__
111 except AttributeError:
112 raise ValueError('{}.__spec__ is not set'.format(name)) from None
113 else:
114 if spec is None:
115 raise ValueError('{}.__spec__ is None'.format(name))
116 return spec
117
118
119 @contextmanager
120 def _module_to_load(name):
121 is_reload = name in sys.modules
122
123 module = sys.modules.get(name)
124 if not is_reload:
125 # This must be done before open() is called as the 'io' module
126 # implicitly imports 'locale' and would otherwise trigger an
127 # infinite loop.
128 module = type(sys)(name)
129 # This must be done before putting the module in sys.modules
130 # (otherwise an optimization shortcut in import.c becomes wrong)
131 module.__initializing__ = True
132 sys.modules[name] = module
133 try:
134 yield module
135 except Exception:
136 if not is_reload:
137 try:
138 del sys.modules[name]
139 except KeyError:
140 pass
141 finally:
142 module.__initializing__ = False
143
144
145 def set_package(fxn):
146 """Set __package__ on the returned module.
147
148 This function is deprecated.
149
150 """
151 @functools.wraps(fxn)
152 def set_package_wrapper(*args, **kwargs):
153 warnings.warn('The import system now takes care of this automatically; '
154 'this decorator is slated for removal in Python 3.12',
155 DeprecationWarning, stacklevel=2)
156 module = fxn(*args, **kwargs)
157 if getattr(module, '__package__', None) is None:
158 module.__package__ = module.__name__
159 if not hasattr(module, '__path__'):
160 module.__package__ = module.__package__.rpartition('.')[0]
161 return module
162 return set_package_wrapper
163
164
165 def set_loader(fxn):
166 """Set __loader__ on the returned module.
167
168 This function is deprecated.
169
170 """
171 @functools.wraps(fxn)
172 def set_loader_wrapper(self, *args, **kwargs):
173 warnings.warn('The import system now takes care of this automatically; '
174 'this decorator is slated for removal in Python 3.12',
175 DeprecationWarning, stacklevel=2)
176 module = fxn(self, *args, **kwargs)
177 if getattr(module, '__loader__', None) is None:
178 module.__loader__ = self
179 return module
180 return set_loader_wrapper
181
182
183 def module_for_loader(fxn):
184 """Decorator to handle selecting the proper module for loaders.
185
186 The decorated function is passed the module to use instead of the module
187 name. The module passed in to the function is either from sys.modules if
188 it already exists or is a new module. If the module is new, then __name__
189 is set the first argument to the method, __loader__ is set to self, and
190 __package__ is set accordingly (if self.is_package() is defined) will be set
191 before it is passed to the decorated function (if self.is_package() does
192 not work for the module it will be set post-load).
193
194 If an exception is raised and the decorator created the module it is
195 subsequently removed from sys.modules.
196
197 The decorator assumes that the decorated function takes the module name as
198 the second argument.
199
200 """
201 warnings.warn('The import system now takes care of this automatically; '
202 'this decorator is slated for removal in Python 3.12',
203 DeprecationWarning, stacklevel=2)
204 @functools.wraps(fxn)
205 def module_for_loader_wrapper(self, fullname, *args, **kwargs):
206 with _module_to_load(fullname) as module:
207 module.__loader__ = self
208 try:
209 is_package = self.is_package(fullname)
210 except (ImportError, AttributeError):
211 pass
212 else:
213 if is_package:
214 module.__package__ = fullname
215 else:
216 module.__package__ = fullname.rpartition('.')[0]
217 # If __package__ was not set above, __import__() will do it later.
218 return fxn(self, module, *args, **kwargs)
219
220 return module_for_loader_wrapper
221
222
223 class _LazyModule(types.ModuleType):
224
225 """A subclass of the module type which triggers loading upon attribute access."""
226
227 def __getattribute__(self, attr):
228 """Trigger the load of the module and return the attribute."""
229 __spec__ = object.__getattribute__(self, '__spec__')
230 loader_state = __spec__.loader_state
231 with loader_state['lock']:
232 # Only the first thread to get the lock should trigger the load
233 # and reset the module's class. The rest can now getattr().
234 if object.__getattribute__(self, '__class__') is _LazyModule:
235 # Reentrant calls from the same thread must be allowed to proceed without
236 # triggering the load again.
237 # exec_module() and self-referential imports are the primary ways this can
238 # happen, but in any case we must return something to avoid deadlock.
239 if loader_state['is_loading']:
240 return object.__getattribute__(self, attr)
241 loader_state['is_loading'] = True
242
243 __dict__ = object.__getattribute__(self, '__dict__')
244
245 # All module metadata must be gathered from __spec__ in order to avoid
246 # using mutated values.
247 # Get the original name to make sure no object substitution occurred
248 # in sys.modules.
249 original_name = __spec__.name
250 # Figure out exactly what attributes were mutated between the creation
251 # of the module and now.
252 attrs_then = loader_state['__dict__']
253 attrs_now = __dict__
254 attrs_updated = {}
255 for key, value in attrs_now.items():
256 # Code that set an attribute may have kept a reference to the
257 # assigned object, making identity more important than equality.
258 if key not in attrs_then:
259 attrs_updated[key] = value
260 elif id(attrs_now[key]) != id(attrs_then[key]):
261 attrs_updated[key] = value
262 __spec__.loader.exec_module(self)
263 # If exec_module() was used directly there is no guarantee the module
264 # object was put into sys.modules.
265 if original_name in sys.modules:
266 if id(self) != id(sys.modules[original_name]):
267 raise ValueError(f"module object for {original_name!r} "
268 "substituted in sys.modules during a lazy "
269 "load")
270 # Update after loading since that's what would happen in an eager
271 # loading situation.
272 __dict__.update(attrs_updated)
273 # Finally, stop triggering this method.
274 self.__class__ = types.ModuleType
275
276 return getattr(self, attr)
277
278 def __delattr__(self, attr):
279 """Trigger the load and then perform the deletion."""
280 # To trigger the load and raise an exception if the attribute
281 # doesn't exist.
282 self.__getattribute__(attr)
283 delattr(self, attr)
284
285
286 class LazyLoader(Loader):
287
288 """A loader that creates a module which defers loading until attribute access."""
289
290 @staticmethod
291 def __check_eager_loader(loader):
292 if not hasattr(loader, 'exec_module'):
293 raise TypeError('loader must define exec_module()')
294
295 @classmethod
296 def factory(cls, loader):
297 """Construct a callable which returns the eager loader made lazy."""
298 cls.__check_eager_loader(loader)
299 return lambda *args, **kwargs: cls(loader(*args, **kwargs))
300
301 def __init__(self, loader):
302 self.__check_eager_loader(loader)
303 self.loader = loader
304
305 def create_module(self, spec):
306 return self.loader.create_module(spec)
307
308 def exec_module(self, module):
309 """Make the module load lazily."""
310 module.__spec__.loader = self.loader
311 module.__loader__ = self.loader
312 # Don't need to worry about deep-copying as trying to set an attribute
313 # on an object would have triggered the load,
314 # e.g. ``module.__spec__.loader = None`` would trigger a load from
315 # trying to access module.__spec__.
316 loader_state = {}
317 loader_state['__dict__'] = module.__dict__.copy()
318 loader_state['__class__'] = module.__class__
319 loader_state['lock'] = threading.RLock()
320 loader_state['is_loading'] = False
321 module.__spec__.loader_state = loader_state
322 module.__class__ = _LazyModule