_bootstrap.py 39 KB

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