_bootstrap.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. """Core implementation of import.
  2. This module is NOT meant to be directly imported! It has been designed such
  3. that it can be bootstrapped into Python as the implementation of import. As
  4. such it requires the injection of specific modules and attributes in order to
  5. work. One should use importlib as the public-facing version of this module.
  6. """
  7. #
  8. # IMPORTANT: Whenever making changes to this module, be sure to run a top-level
  9. # `make regen-importlib` followed by `make` in order to get the frozen version
  10. # of the module updated. Not doing so will result in the Makefile to fail for
  11. # all others who don't have a ./python around to freeze the module
  12. # in the early stages of compilation.
  13. #
  14. # See importlib._setup() for what is injected into the global namespace.
  15. # When editing this code be aware that code executed at import time CANNOT
  16. # reference any injected objects! This includes not only global code but also
  17. # anything specified at the class level.
  18. # Bootstrap-related code ######################################################
  19. _bootstrap_external = None
  20. def _wrap(new, old):
  21. """Simple substitute for functools.update_wrapper."""
  22. for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
  23. if hasattr(old, replace):
  24. setattr(new, replace, getattr(old, replace))
  25. new.__dict__.update(old.__dict__)
  26. def _new_module(name):
  27. return type(sys)(name)
  28. # Module-level locking ########################################################
  29. # A dict mapping module names to weakrefs of _ModuleLock instances
  30. # Dictionary protected by the global import lock
  31. _module_locks = {}
  32. # A dict mapping thread ids to _ModuleLock instances
  33. _blocking_on = {}
  34. class _DeadlockError(RuntimeError):
  35. pass
  36. class _ModuleLock:
  37. """A recursive lock implementation which is able to detect deadlocks
  38. (e.g. thread 1 trying to take locks A then B, and thread 2 trying to
  39. take locks B then A).
  40. """
  41. def __init__(self, name):
  42. self.lock = _thread.allocate_lock()
  43. self.wakeup = _thread.allocate_lock()
  44. self.name = name
  45. self.owner = None
  46. self.count = 0
  47. self.waiters = 0
  48. def has_deadlock(self):
  49. # Deadlock avoidance for concurrent circular imports.
  50. me = _thread.get_ident()
  51. tid = self.owner
  52. seen = set()
  53. while True:
  54. lock = _blocking_on.get(tid)
  55. if lock is None:
  56. return False
  57. tid = lock.owner
  58. if tid == me:
  59. return True
  60. if tid in seen:
  61. # bpo 38091: the chain of tid's we encounter here
  62. # eventually leads to a fixpoint or a cycle, but
  63. # does not reach 'me'. This means we would not
  64. # actually deadlock. This can happen if other
  65. # threads are at the beginning of acquire() below.
  66. return False
  67. seen.add(tid)
  68. def acquire(self):
  69. """
  70. Acquire the module lock. If a potential deadlock is detected,
  71. a _DeadlockError is raised.
  72. Otherwise, the lock is always acquired and True is returned.
  73. """
  74. tid = _thread.get_ident()
  75. _blocking_on[tid] = self
  76. try:
  77. while True:
  78. with self.lock:
  79. if self.count == 0 or self.owner == tid:
  80. self.owner = tid
  81. self.count += 1
  82. return True
  83. if self.has_deadlock():
  84. raise _DeadlockError('deadlock detected by %r' % self)
  85. if self.wakeup.acquire(False):
  86. self.waiters += 1
  87. # Wait for a release() call
  88. self.wakeup.acquire()
  89. self.wakeup.release()
  90. finally:
  91. del _blocking_on[tid]
  92. def release(self):
  93. tid = _thread.get_ident()
  94. with self.lock:
  95. if self.owner != tid:
  96. raise RuntimeError('cannot release un-acquired lock')
  97. assert self.count > 0
  98. self.count -= 1
  99. if self.count == 0:
  100. self.owner = None
  101. if self.waiters:
  102. self.waiters -= 1
  103. self.wakeup.release()
  104. def __repr__(self):
  105. return '_ModuleLock({!r}) at {}'.format(self.name, id(self))
  106. class _DummyModuleLock:
  107. """A simple _ModuleLock equivalent for Python builds without
  108. multi-threading support."""
  109. def __init__(self, name):
  110. self.name = name
  111. self.count = 0
  112. def acquire(self):
  113. self.count += 1
  114. return True
  115. def release(self):
  116. if self.count == 0:
  117. raise RuntimeError('cannot release un-acquired lock')
  118. self.count -= 1
  119. def __repr__(self):
  120. return '_DummyModuleLock({!r}) at {}'.format(self.name, id(self))
  121. class _ModuleLockManager:
  122. def __init__(self, name):
  123. self._name = name
  124. self._lock = None
  125. def __enter__(self):
  126. self._lock = _get_module_lock(self._name)
  127. self._lock.acquire()
  128. def __exit__(self, *args, **kwargs):
  129. self._lock.release()
  130. # The following two functions are for consumption by Python/import.c.
  131. def _get_module_lock(name):
  132. """Get or create the module lock for a given module name.
  133. Acquire/release internally the global import lock to protect
  134. _module_locks."""
  135. _imp.acquire_lock()
  136. try:
  137. try:
  138. lock = _module_locks[name]()
  139. except KeyError:
  140. lock = None
  141. if lock is None:
  142. if _thread is None:
  143. lock = _DummyModuleLock(name)
  144. else:
  145. lock = _ModuleLock(name)
  146. def cb(ref, name=name):
  147. _imp.acquire_lock()
  148. try:
  149. # bpo-31070: Check if another thread created a new lock
  150. # after the previous lock was destroyed
  151. # but before the weakref callback was called.
  152. if _module_locks.get(name) is ref:
  153. del _module_locks[name]
  154. finally:
  155. _imp.release_lock()
  156. _module_locks[name] = _weakref.ref(lock, cb)
  157. finally:
  158. _imp.release_lock()
  159. return lock
  160. def _lock_unlock_module(name):
  161. """Acquires then releases the module lock for a given module name.
  162. This is used to ensure a module is completely initialized, in the
  163. event it is being imported by another thread.
  164. """
  165. lock = _get_module_lock(name)
  166. try:
  167. lock.acquire()
  168. except _DeadlockError:
  169. # Concurrent circular import, we'll accept a partially initialized
  170. # module object.
  171. pass
  172. else:
  173. lock.release()
  174. # Frame stripping magic ###############################################
  175. def _call_with_frames_removed(f, *args, **kwds):
  176. """remove_importlib_frames in import.c will always remove sequences
  177. of importlib frames that end with a call to this function
  178. Use it instead of a normal call in places where including the importlib
  179. frames introduces unwanted noise into the traceback (e.g. when executing
  180. module code)
  181. """
  182. return f(*args, **kwds)
  183. def _verbose_message(message, *args, verbosity=1):
  184. """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
  185. if sys.flags.verbose >= verbosity:
  186. if not message.startswith(('#', 'import ')):
  187. message = '# ' + message
  188. print(message.format(*args), file=sys.stderr)
  189. def _requires_builtin(fxn):
  190. """Decorator to verify the named module is built-in."""
  191. def _requires_builtin_wrapper(self, fullname):
  192. if fullname not in sys.builtin_module_names:
  193. raise ImportError('{!r} is not a built-in module'.format(fullname),
  194. name=fullname)
  195. return fxn(self, fullname)
  196. _wrap(_requires_builtin_wrapper, fxn)
  197. return _requires_builtin_wrapper
  198. def _requires_frozen(fxn):
  199. """Decorator to verify the named module is frozen."""
  200. def _requires_frozen_wrapper(self, fullname):
  201. if not _imp.is_frozen(fullname):
  202. raise ImportError('{!r} is not a frozen module'.format(fullname),
  203. name=fullname)
  204. return fxn(self, fullname)
  205. _wrap(_requires_frozen_wrapper, fxn)
  206. return _requires_frozen_wrapper
  207. # Typically used by loader classes as a method replacement.
  208. def _load_module_shim(self, fullname):
  209. """Load the specified module into sys.modules and return it.
  210. This method is deprecated. Use loader.exec_module instead.
  211. """
  212. spec = spec_from_loader(fullname, self)
  213. if fullname in sys.modules:
  214. module = sys.modules[fullname]
  215. _exec(spec, module)
  216. return sys.modules[fullname]
  217. else:
  218. return _load(spec)
  219. # Module specifications #######################################################
  220. def _module_repr(module):
  221. # The implementation of ModuleType.__repr__().
  222. loader = getattr(module, '__loader__', None)
  223. if hasattr(loader, 'module_repr'):
  224. # As soon as BuiltinImporter, FrozenImporter, and NamespaceLoader
  225. # drop their implementations for module_repr. we can add a
  226. # deprecation warning here.
  227. try:
  228. return loader.module_repr(module)
  229. except Exception:
  230. pass
  231. try:
  232. spec = module.__spec__
  233. except AttributeError:
  234. pass
  235. else:
  236. if spec is not None:
  237. return _module_repr_from_spec(spec)
  238. # We could use module.__class__.__name__ instead of 'module' in the
  239. # various repr permutations.
  240. try:
  241. name = module.__name__
  242. except AttributeError:
  243. name = '?'
  244. try:
  245. filename = module.__file__
  246. except AttributeError:
  247. if loader is None:
  248. return '<module {!r}>'.format(name)
  249. else:
  250. return '<module {!r} ({!r})>'.format(name, loader)
  251. else:
  252. return '<module {!r} from {!r}>'.format(name, filename)
  253. class ModuleSpec:
  254. """The specification for a module, used for loading.
  255. A module's spec is the source for information about the module. For
  256. data associated with the module, including source, use the spec's
  257. loader.
  258. `name` is the absolute name of the module. `loader` is the loader
  259. to use when loading the module. `parent` is the name of the
  260. package the module is in. The parent is derived from the name.
  261. `is_package` determines if the module is considered a package or
  262. not. On modules this is reflected by the `__path__` attribute.
  263. `origin` is the specific location used by the loader from which to
  264. load the module, if that information is available. When filename is
  265. set, origin will match.
  266. `has_location` indicates that a spec's "origin" reflects a location.
  267. When this is True, `__file__` attribute of the module is set.
  268. `cached` is the location of the cached bytecode file, if any. It
  269. corresponds to the `__cached__` attribute.
  270. `submodule_search_locations` is the sequence of path entries to
  271. search when importing submodules. If set, is_package should be
  272. True--and False otherwise.
  273. Packages are simply modules that (may) have submodules. If a spec
  274. has a non-None value in `submodule_search_locations`, the import
  275. system will consider modules loaded from the spec as packages.
  276. Only finders (see importlib.abc.MetaPathFinder and
  277. importlib.abc.PathEntryFinder) should modify ModuleSpec instances.
  278. """
  279. def __init__(self, name, loader, *, origin=None, loader_state=None,
  280. is_package=None):
  281. self.name = name
  282. self.loader = loader
  283. self.origin = origin
  284. self.loader_state = loader_state
  285. self.submodule_search_locations = [] if is_package else None
  286. # file-location attributes
  287. self._set_fileattr = False
  288. self._cached = None
  289. def __repr__(self):
  290. args = ['name={!r}'.format(self.name),
  291. 'loader={!r}'.format(self.loader)]
  292. if self.origin is not None:
  293. args.append('origin={!r}'.format(self.origin))
  294. if self.submodule_search_locations is not None:
  295. args.append('submodule_search_locations={}'
  296. .format(self.submodule_search_locations))
  297. return '{}({})'.format(self.__class__.__name__, ', '.join(args))
  298. def __eq__(self, other):
  299. smsl = self.submodule_search_locations
  300. try:
  301. return (self.name == other.name and
  302. self.loader == other.loader and
  303. self.origin == other.origin and
  304. smsl == other.submodule_search_locations and
  305. self.cached == other.cached and
  306. self.has_location == other.has_location)
  307. except AttributeError:
  308. return NotImplemented
  309. @property
  310. def cached(self):
  311. if self._cached is None:
  312. if self.origin is not None and self._set_fileattr:
  313. if _bootstrap_external is None:
  314. raise NotImplementedError
  315. self._cached = _bootstrap_external._get_cached(self.origin)
  316. return self._cached
  317. @cached.setter
  318. def cached(self, cached):
  319. self._cached = cached
  320. @property
  321. def parent(self):
  322. """The name of the module's parent."""
  323. if self.submodule_search_locations is None:
  324. return self.name.rpartition('.')[0]
  325. else:
  326. return self.name
  327. @property
  328. def has_location(self):
  329. return self._set_fileattr
  330. @has_location.setter
  331. def has_location(self, value):
  332. self._set_fileattr = bool(value)
  333. def spec_from_loader(name, loader, *, origin=None, is_package=None):
  334. """Return a module spec based on various loader methods."""
  335. if hasattr(loader, 'get_filename'):
  336. if _bootstrap_external is None:
  337. raise NotImplementedError
  338. spec_from_file_location = _bootstrap_external.spec_from_file_location
  339. if is_package is None:
  340. return spec_from_file_location(name, loader=loader)
  341. search = [] if is_package else None
  342. return spec_from_file_location(name, loader=loader,
  343. submodule_search_locations=search)
  344. if is_package is None:
  345. if hasattr(loader, 'is_package'):
  346. try:
  347. is_package = loader.is_package(name)
  348. except ImportError:
  349. is_package = None # aka, undefined
  350. else:
  351. # the default
  352. is_package = False
  353. return ModuleSpec(name, loader, origin=origin, is_package=is_package)
  354. def _spec_from_module(module, loader=None, origin=None):
  355. # This function is meant for use in _setup().
  356. try:
  357. spec = module.__spec__
  358. except AttributeError:
  359. pass
  360. else:
  361. if spec is not None:
  362. return spec
  363. name = module.__name__
  364. if loader is None:
  365. try:
  366. loader = module.__loader__
  367. except AttributeError:
  368. # loader will stay None.
  369. pass
  370. try:
  371. location = module.__file__
  372. except AttributeError:
  373. location = None
  374. if origin is None:
  375. if location is None:
  376. try:
  377. origin = loader._ORIGIN
  378. except AttributeError:
  379. origin = None
  380. else:
  381. origin = location
  382. try:
  383. cached = module.__cached__
  384. except AttributeError:
  385. cached = None
  386. try:
  387. submodule_search_locations = list(module.__path__)
  388. except AttributeError:
  389. submodule_search_locations = None
  390. spec = ModuleSpec(name, loader, origin=origin)
  391. spec._set_fileattr = False if location is None else True
  392. spec.cached = cached
  393. spec.submodule_search_locations = submodule_search_locations
  394. return spec
  395. def _init_module_attrs(spec, module, *, override=False):
  396. # The passed-in module may be not support attribute assignment,
  397. # in which case we simply don't set the attributes.
  398. # __name__
  399. if (override or getattr(module, '__name__', None) is None):
  400. try:
  401. module.__name__ = spec.name
  402. except AttributeError:
  403. pass
  404. # __loader__
  405. if override or getattr(module, '__loader__', None) is None:
  406. loader = spec.loader
  407. if loader is None:
  408. # A backward compatibility hack.
  409. if spec.submodule_search_locations is not None:
  410. if _bootstrap_external is None:
  411. raise NotImplementedError
  412. _NamespaceLoader = _bootstrap_external._NamespaceLoader
  413. loader = _NamespaceLoader.__new__(_NamespaceLoader)
  414. loader._path = spec.submodule_search_locations
  415. spec.loader = loader
  416. # While the docs say that module.__file__ is not set for
  417. # built-in modules, and the code below will avoid setting it if
  418. # spec.has_location is false, this is incorrect for namespace
  419. # packages. Namespace packages have no location, but their
  420. # __spec__.origin is None, and thus their module.__file__
  421. # should also be None for consistency. While a bit of a hack,
  422. # this is the best place to ensure this consistency.
  423. #
  424. # See # https://docs.python.org/3/library/importlib.html#importlib.abc.Loader.load_module
  425. # and bpo-32305
  426. module.__file__ = None
  427. try:
  428. module.__loader__ = loader
  429. except AttributeError:
  430. pass
  431. # __package__
  432. if override or getattr(module, '__package__', None) is None:
  433. try:
  434. module.__package__ = spec.parent
  435. except AttributeError:
  436. pass
  437. # __spec__
  438. try:
  439. module.__spec__ = spec
  440. except AttributeError:
  441. pass
  442. # __path__
  443. if override or getattr(module, '__path__', None) is None:
  444. if spec.submodule_search_locations is not None:
  445. try:
  446. module.__path__ = spec.submodule_search_locations
  447. except AttributeError:
  448. pass
  449. # __file__/__cached__
  450. if spec.has_location:
  451. if override or getattr(module, '__file__', None) is None:
  452. try:
  453. module.__file__ = spec.origin
  454. except AttributeError:
  455. pass
  456. if override or getattr(module, '__cached__', None) is None:
  457. if spec.cached is not None:
  458. try:
  459. module.__cached__ = spec.cached
  460. except AttributeError:
  461. pass
  462. return module
  463. def module_from_spec(spec):
  464. """Create a module based on the provided spec."""
  465. # Typically loaders will not implement create_module().
  466. module = None
  467. if hasattr(spec.loader, 'create_module'):
  468. # If create_module() returns `None` then it means default
  469. # module creation should be used.
  470. module = spec.loader.create_module(spec)
  471. elif hasattr(spec.loader, 'exec_module'):
  472. raise ImportError('loaders that define exec_module() '
  473. 'must also define create_module()')
  474. if module is None:
  475. module = _new_module(spec.name)
  476. _init_module_attrs(spec, module)
  477. return module
  478. def _module_repr_from_spec(spec):
  479. """Return the repr to use for the module."""
  480. # We mostly replicate _module_repr() using the spec attributes.
  481. name = '?' if spec.name is None else spec.name
  482. if spec.origin is None:
  483. if spec.loader is None:
  484. return '<module {!r}>'.format(name)
  485. else:
  486. return '<module {!r} ({!r})>'.format(name, spec.loader)
  487. else:
  488. if spec.has_location:
  489. return '<module {!r} from {!r}>'.format(name, spec.origin)
  490. else:
  491. return '<module {!r} ({})>'.format(spec.name, spec.origin)
  492. # Used by importlib.reload() and _load_module_shim().
  493. def _exec(spec, module):
  494. """Execute the spec's specified module in an existing module's namespace."""
  495. name = spec.name
  496. with _ModuleLockManager(name):
  497. if sys.modules.get(name) is not module:
  498. msg = 'module {!r} not in sys.modules'.format(name)
  499. raise ImportError(msg, name=name)
  500. try:
  501. if spec.loader is None:
  502. if spec.submodule_search_locations is None:
  503. raise ImportError('missing loader', name=spec.name)
  504. # Namespace package.
  505. _init_module_attrs(spec, module, override=True)
  506. else:
  507. _init_module_attrs(spec, module, override=True)
  508. if not hasattr(spec.loader, 'exec_module'):
  509. # (issue19713) Once BuiltinImporter and ExtensionFileLoader
  510. # have exec_module() implemented, we can add a deprecation
  511. # warning here.
  512. spec.loader.load_module(name)
  513. else:
  514. spec.loader.exec_module(module)
  515. finally:
  516. # Update the order of insertion into sys.modules for module
  517. # clean-up at shutdown.
  518. module = sys.modules.pop(spec.name)
  519. sys.modules[spec.name] = module
  520. return module
  521. def _load_backward_compatible(spec):
  522. # (issue19713) Once BuiltinImporter and ExtensionFileLoader
  523. # have exec_module() implemented, we can add a deprecation
  524. # warning here.
  525. try:
  526. spec.loader.load_module(spec.name)
  527. except:
  528. if spec.name in sys.modules:
  529. module = sys.modules.pop(spec.name)
  530. sys.modules[spec.name] = module
  531. raise
  532. # The module must be in sys.modules at this point!
  533. # Move it to the end of sys.modules.
  534. module = sys.modules.pop(spec.name)
  535. sys.modules[spec.name] = module
  536. if getattr(module, '__loader__', None) is None:
  537. try:
  538. module.__loader__ = spec.loader
  539. except AttributeError:
  540. pass
  541. if getattr(module, '__package__', None) is None:
  542. try:
  543. # Since module.__path__ may not line up with
  544. # spec.submodule_search_paths, we can't necessarily rely
  545. # on spec.parent here.
  546. module.__package__ = module.__name__
  547. if not hasattr(module, '__path__'):
  548. module.__package__ = spec.name.rpartition('.')[0]
  549. except AttributeError:
  550. pass
  551. if getattr(module, '__spec__', None) is None:
  552. try:
  553. module.__spec__ = spec
  554. except AttributeError:
  555. pass
  556. return module
  557. def _load_unlocked(spec):
  558. # A helper for direct use by the import system.
  559. if spec.loader is not None:
  560. # Not a namespace package.
  561. if not hasattr(spec.loader, 'exec_module'):
  562. return _load_backward_compatible(spec)
  563. module = module_from_spec(spec)
  564. # This must be done before putting the module in sys.modules
  565. # (otherwise an optimization shortcut in import.c becomes
  566. # wrong).
  567. spec._initializing = True
  568. try:
  569. sys.modules[spec.name] = module
  570. try:
  571. if spec.loader is None:
  572. if spec.submodule_search_locations is None:
  573. raise ImportError('missing loader', name=spec.name)
  574. # A namespace package so do nothing.
  575. else:
  576. spec.loader.exec_module(module)
  577. except:
  578. try:
  579. del sys.modules[spec.name]
  580. except KeyError:
  581. pass
  582. raise
  583. # Move the module to the end of sys.modules.
  584. # We don't ensure that the import-related module attributes get
  585. # set in the sys.modules replacement case. Such modules are on
  586. # their own.
  587. module = sys.modules.pop(spec.name)
  588. sys.modules[spec.name] = module
  589. _verbose_message('import {!r} # {!r}', spec.name, spec.loader)
  590. finally:
  591. spec._initializing = False
  592. return module
  593. # A method used during testing of _load_unlocked() and by
  594. # _load_module_shim().
  595. def _load(spec):
  596. """Return a new module object, loaded by the spec's loader.
  597. The module is not added to its parent.
  598. If a module is already in sys.modules, that existing module gets
  599. clobbered.
  600. """
  601. with _ModuleLockManager(spec.name):
  602. return _load_unlocked(spec)
  603. # Loaders #####################################################################
  604. class BuiltinImporter:
  605. """Meta path import for built-in modules.
  606. All methods are either class or static methods to avoid the need to
  607. instantiate the class.
  608. """
  609. _ORIGIN = "built-in"
  610. @staticmethod
  611. def module_repr(module):
  612. """Return repr for the module.
  613. The method is deprecated. The import machinery does the job itself.
  614. """
  615. return f'<module {module.__name__!r} ({BuiltinImporter._ORIGIN})>'
  616. @classmethod
  617. def find_spec(cls, fullname, path=None, target=None):
  618. if path is not None:
  619. return None
  620. if _imp.is_builtin(fullname):
  621. return spec_from_loader(fullname, cls, origin=cls._ORIGIN)
  622. else:
  623. return None
  624. @classmethod
  625. def find_module(cls, fullname, path=None):
  626. """Find the built-in module.
  627. If 'path' is ever specified then the search is considered a failure.
  628. This method is deprecated. Use find_spec() instead.
  629. """
  630. spec = cls.find_spec(fullname, path)
  631. return spec.loader if spec is not None else None
  632. @classmethod
  633. def create_module(self, spec):
  634. """Create a built-in module"""
  635. if spec.name not in sys.builtin_module_names:
  636. raise ImportError('{!r} is not a built-in module'.format(spec.name),
  637. name=spec.name)
  638. return _call_with_frames_removed(_imp.create_builtin, spec)
  639. @classmethod
  640. def exec_module(self, module):
  641. """Exec a built-in module"""
  642. _call_with_frames_removed(_imp.exec_builtin, module)
  643. @classmethod
  644. @_requires_builtin
  645. def get_code(cls, fullname):
  646. """Return None as built-in modules do not have code objects."""
  647. return None
  648. @classmethod
  649. @_requires_builtin
  650. def get_source(cls, fullname):
  651. """Return None as built-in modules do not have source code."""
  652. return None
  653. @classmethod
  654. @_requires_builtin
  655. def is_package(cls, fullname):
  656. """Return False as built-in modules are never packages."""
  657. return False
  658. load_module = classmethod(_load_module_shim)
  659. class FrozenImporter:
  660. """Meta path import for frozen modules.
  661. All methods are either class or static methods to avoid the need to
  662. instantiate the class.
  663. """
  664. _ORIGIN = "frozen"
  665. @staticmethod
  666. def module_repr(m):
  667. """Return repr for the module.
  668. The method is deprecated. The import machinery does the job itself.
  669. """
  670. return '<module {!r} ({})>'.format(m.__name__, FrozenImporter._ORIGIN)
  671. @classmethod
  672. def find_spec(cls, fullname, path=None, target=None):
  673. if _imp.is_frozen(fullname):
  674. return spec_from_loader(fullname, cls, origin=cls._ORIGIN)
  675. else:
  676. return None
  677. @classmethod
  678. def find_module(cls, fullname, path=None):
  679. """Find a frozen module.
  680. This method is deprecated. Use find_spec() instead.
  681. """
  682. return cls if _imp.is_frozen(fullname) else None
  683. @classmethod
  684. def create_module(cls, spec):
  685. """Use default semantics for module creation."""
  686. @staticmethod
  687. def exec_module(module):
  688. name = module.__spec__.name
  689. if not _imp.is_frozen(name):
  690. raise ImportError('{!r} is not a frozen module'.format(name),
  691. name=name)
  692. code = _call_with_frames_removed(_imp.get_frozen_object, name)
  693. exec(code, module.__dict__)
  694. @classmethod
  695. def load_module(cls, fullname):
  696. """Load a frozen module.
  697. This method is deprecated. Use exec_module() instead.
  698. """
  699. return _load_module_shim(cls, fullname)
  700. @classmethod
  701. @_requires_frozen
  702. def get_code(cls, fullname):
  703. """Return the code object for the frozen module."""
  704. return _imp.get_frozen_object(fullname)
  705. @classmethod
  706. @_requires_frozen
  707. def get_source(cls, fullname):
  708. """Return None as frozen modules do not have source code."""
  709. return None
  710. @classmethod
  711. @_requires_frozen
  712. def is_package(cls, fullname):
  713. """Return True if the frozen module is a package."""
  714. return _imp.is_frozen_package(fullname)
  715. # Import itself ###############################################################
  716. class _ImportLockContext:
  717. """Context manager for the import lock."""
  718. def __enter__(self):
  719. """Acquire the import lock."""
  720. _imp.acquire_lock()
  721. def __exit__(self, exc_type, exc_value, exc_traceback):
  722. """Release the import lock regardless of any raised exceptions."""
  723. _imp.release_lock()
  724. def _resolve_name(name, package, level):
  725. """Resolve a relative module name to an absolute one."""
  726. bits = package.rsplit('.', level - 1)
  727. if len(bits) < level:
  728. raise ImportError('attempted relative import beyond top-level package')
  729. base = bits[0]
  730. return '{}.{}'.format(base, name) if name else base
  731. def _find_spec_legacy(finder, name, path):
  732. # This would be a good place for a DeprecationWarning if
  733. # we ended up going that route.
  734. loader = finder.find_module(name, path)
  735. if loader is None:
  736. return None
  737. return spec_from_loader(name, loader)
  738. def _find_spec(name, path, target=None):
  739. """Find a module's spec."""
  740. meta_path = sys.meta_path
  741. if meta_path is None:
  742. # PyImport_Cleanup() is running or has been called.
  743. raise ImportError("sys.meta_path is None, Python is likely "
  744. "shutting down")
  745. if not meta_path:
  746. _warnings.warn('sys.meta_path is empty', ImportWarning)
  747. # We check sys.modules here for the reload case. While a passed-in
  748. # target will usually indicate a reload there is no guarantee, whereas
  749. # sys.modules provides one.
  750. is_reload = name in sys.modules
  751. for finder in meta_path:
  752. with _ImportLockContext():
  753. try:
  754. find_spec = finder.find_spec
  755. except AttributeError:
  756. spec = _find_spec_legacy(finder, name, path)
  757. if spec is None:
  758. continue
  759. else:
  760. spec = find_spec(name, path, target)
  761. if spec is not None:
  762. # The parent import may have already imported this module.
  763. if not is_reload and name in sys.modules:
  764. module = sys.modules[name]
  765. try:
  766. __spec__ = module.__spec__
  767. except AttributeError:
  768. # We use the found spec since that is the one that
  769. # we would have used if the parent module hadn't
  770. # beaten us to the punch.
  771. return spec
  772. else:
  773. if __spec__ is None:
  774. return spec
  775. else:
  776. return __spec__
  777. else:
  778. return spec
  779. else:
  780. return None
  781. def _sanity_check(name, package, level):
  782. """Verify arguments are "sane"."""
  783. if not isinstance(name, str):
  784. raise TypeError('module name must be str, not {}'.format(type(name)))
  785. if level < 0:
  786. raise ValueError('level must be >= 0')
  787. if level > 0:
  788. if not isinstance(package, str):
  789. raise TypeError('__package__ not set to a string')
  790. elif not package:
  791. raise ImportError('attempted relative import with no known parent '
  792. 'package')
  793. if not name and level == 0:
  794. raise ValueError('Empty module name')
  795. _ERR_MSG_PREFIX = 'No module named '
  796. _ERR_MSG = _ERR_MSG_PREFIX + '{!r}'
  797. def _find_and_load_unlocked(name, import_):
  798. path = None
  799. parent = name.rpartition('.')[0]
  800. if parent:
  801. if parent not in sys.modules:
  802. _call_with_frames_removed(import_, parent)
  803. # Crazy side-effects!
  804. if name in sys.modules:
  805. return sys.modules[name]
  806. parent_module = sys.modules[parent]
  807. try:
  808. path = parent_module.__path__
  809. except AttributeError:
  810. msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
  811. raise ModuleNotFoundError(msg, name=name) from None
  812. spec = _find_spec(name, path)
  813. if spec is None:
  814. raise ModuleNotFoundError(_ERR_MSG.format(name), name=name)
  815. else:
  816. module = _load_unlocked(spec)
  817. if parent:
  818. # Set the module as an attribute on its parent.
  819. parent_module = sys.modules[parent]
  820. child = name.rpartition('.')[2]
  821. try:
  822. setattr(parent_module, child, module)
  823. except AttributeError:
  824. msg = f"Cannot set an attribute on {parent!r} for child module {child!r}"
  825. _warnings.warn(msg, ImportWarning)
  826. return module
  827. _NEEDS_LOADING = object()
  828. def _find_and_load(name, import_):
  829. """Find and load the module."""
  830. with _ModuleLockManager(name):
  831. module = sys.modules.get(name, _NEEDS_LOADING)
  832. if module is _NEEDS_LOADING:
  833. return _find_and_load_unlocked(name, import_)
  834. if module is None:
  835. message = ('import of {} halted; '
  836. 'None in sys.modules'.format(name))
  837. raise ModuleNotFoundError(message, name=name)
  838. _lock_unlock_module(name)
  839. return module
  840. def _gcd_import(name, package=None, level=0):
  841. """Import and return the module based on its name, the package the call is
  842. being made from, and the level adjustment.
  843. This function represents the greatest common denominator of functionality
  844. between import_module and __import__. This includes setting __package__ if
  845. the loader did not.
  846. """
  847. _sanity_check(name, package, level)
  848. if level > 0:
  849. name = _resolve_name(name, package, level)
  850. return _find_and_load(name, _gcd_import)
  851. def _handle_fromlist(module, fromlist, import_, *, recursive=False):
  852. """Figure out what __import__ should return.
  853. The import_ parameter is a callable which takes the name of module to
  854. import. It is required to decouple the function from assuming importlib's
  855. import implementation is desired.
  856. """
  857. # The hell that is fromlist ...
  858. # If a package was imported, try to import stuff from fromlist.
  859. for x in fromlist:
  860. if not isinstance(x, str):
  861. if recursive:
  862. where = module.__name__ + '.__all__'
  863. else:
  864. where = "``from list''"
  865. raise TypeError(f"Item in {where} must be str, "
  866. f"not {type(x).__name__}")
  867. elif x == '*':
  868. if not recursive and hasattr(module, '__all__'):
  869. _handle_fromlist(module, module.__all__, import_,
  870. recursive=True)
  871. elif not hasattr(module, x):
  872. from_name = '{}.{}'.format(module.__name__, x)
  873. try:
  874. _call_with_frames_removed(import_, from_name)
  875. except ModuleNotFoundError as exc:
  876. # Backwards-compatibility dictates we ignore failed
  877. # imports triggered by fromlist for modules that don't
  878. # exist.
  879. if (exc.name == from_name and
  880. sys.modules.get(from_name, _NEEDS_LOADING) is not None):
  881. continue
  882. raise
  883. return module
  884. def _calc___package__(globals):
  885. """Calculate what __package__ should be.
  886. __package__ is not guaranteed to be defined or could be set to None
  887. to represent that its proper value is unknown.
  888. """
  889. package = globals.get('__package__')
  890. spec = globals.get('__spec__')
  891. if package is not None:
  892. if spec is not None and package != spec.parent:
  893. _warnings.warn("__package__ != __spec__.parent "
  894. f"({package!r} != {spec.parent!r})",
  895. ImportWarning, stacklevel=3)
  896. return package
  897. elif spec is not None:
  898. return spec.parent
  899. else:
  900. _warnings.warn("can't resolve package from __spec__ or __package__, "
  901. "falling back on __name__ and __path__",
  902. ImportWarning, stacklevel=3)
  903. package = globals['__name__']
  904. if '__path__' not in globals:
  905. package = package.rpartition('.')[0]
  906. return package
  907. def __import__(name, globals=None, locals=None, fromlist=(), level=0):
  908. """Import a module.
  909. The 'globals' argument is used to infer where the import is occurring from
  910. to handle relative imports. The 'locals' argument is ignored. The
  911. 'fromlist' argument specifies what should exist as attributes on the module
  912. being imported (e.g. ``from module import <fromlist>``). The 'level'
  913. argument represents the package location to import from in a relative
  914. import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
  915. """
  916. if level == 0:
  917. module = _gcd_import(name)
  918. else:
  919. globals_ = globals if globals is not None else {}
  920. package = _calc___package__(globals_)
  921. module = _gcd_import(name, package, level)
  922. if not fromlist:
  923. # Return up to the first dot in 'name'. This is complicated by the fact
  924. # that 'name' may be relative.
  925. if level == 0:
  926. return _gcd_import(name.partition('.')[0])
  927. elif not name:
  928. return module
  929. else:
  930. # Figure out where to slice the module's name up to the first dot
  931. # in 'name'.
  932. cut_off = len(name) - len(name.partition('.')[0])
  933. # Slice end needs to be positive to alleviate need to special-case
  934. # when ``'.' not in name``.
  935. return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  936. elif hasattr(module, '__path__'):
  937. return _handle_fromlist(module, fromlist, _gcd_import)
  938. else:
  939. return module
  940. def _builtin_from_name(name):
  941. spec = BuiltinImporter.find_spec(name)
  942. if spec is None:
  943. raise ImportError('no built-in module named ' + name)
  944. return _load_unlocked(spec)
  945. def _setup(sys_module, _imp_module):
  946. """Setup importlib by importing needed built-in modules and injecting them
  947. into the global namespace.
  948. As sys is needed for sys.modules access and _imp is needed to load built-in
  949. modules, those two modules must be explicitly passed in.
  950. """
  951. global _imp, sys
  952. _imp = _imp_module
  953. sys = sys_module
  954. # Set up the spec for existing builtin/frozen modules.
  955. module_type = type(sys)
  956. for name, module in sys.modules.items():
  957. if isinstance(module, module_type):
  958. if name in sys.builtin_module_names:
  959. loader = BuiltinImporter
  960. elif _imp.is_frozen(name):
  961. loader = FrozenImporter
  962. else:
  963. continue
  964. spec = _spec_from_module(module, loader)
  965. _init_module_attrs(spec, module)
  966. # Directly load built-in modules needed during bootstrap.
  967. self_module = sys.modules[__name__]
  968. for builtin_name in ('_thread', '_warnings', '_weakref'):
  969. if builtin_name not in sys.modules:
  970. builtin_module = _builtin_from_name(builtin_name)
  971. else:
  972. builtin_module = sys.modules[builtin_name]
  973. setattr(self_module, builtin_name, builtin_module)
  974. def _install(sys_module, _imp_module):
  975. """Install importers for builtin and frozen modules"""
  976. _setup(sys_module, _imp_module)
  977. sys.meta_path.append(BuiltinImporter)
  978. sys.meta_path.append(FrozenImporter)
  979. def _install_external_importers():
  980. """Install importers that require external filesystem access"""
  981. global _bootstrap_external
  982. import _frozen_importlib_external
  983. _bootstrap_external = _frozen_importlib_external
  984. _frozen_importlib_external._install(sys.modules[__name__])