_bootstrap.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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
  9. # a top-level make in order to get the frozen version of the module
  10. # 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 _installed_safely:
  245. def __init__(self, module):
  246. self._module = module
  247. self._spec = module.__spec__
  248. def __enter__(self):
  249. # This must be done before putting the module in sys.modules
  250. # (otherwise an optimization shortcut in import.c becomes
  251. # wrong)
  252. self._spec._initializing = True
  253. sys.modules[self._spec.name] = self._module
  254. def __exit__(self, *args):
  255. try:
  256. spec = self._spec
  257. if any(arg is not None for arg in args):
  258. try:
  259. del sys.modules[spec.name]
  260. except KeyError:
  261. pass
  262. else:
  263. _verbose_message('import {!r} # {!r}', spec.name, spec.loader)
  264. finally:
  265. self._spec._initializing = False
  266. class ModuleSpec:
  267. """The specification for a module, used for loading.
  268. A module's spec is the source for information about the module. For
  269. data associated with the module, including source, use the spec's
  270. loader.
  271. `name` is the absolute name of the module. `loader` is the loader
  272. to use when loading the module. `parent` is the name of the
  273. package the module is in. The parent is derived from the name.
  274. `is_package` determines if the module is considered a package or
  275. not. On modules this is reflected by the `__path__` attribute.
  276. `origin` is the specific location used by the loader from which to
  277. load the module, if that information is available. When filename is
  278. set, origin will match.
  279. `has_location` indicates that a spec's "origin" reflects a location.
  280. When this is True, `__file__` attribute of the module is set.
  281. `cached` is the location of the cached bytecode file, if any. It
  282. corresponds to the `__cached__` attribute.
  283. `submodule_search_locations` is the sequence of path entries to
  284. search when importing submodules. If set, is_package should be
  285. True--and False otherwise.
  286. Packages are simply modules that (may) have submodules. If a spec
  287. has a non-None value in `submodule_search_locations`, the import
  288. system will consider modules loaded from the spec as packages.
  289. Only finders (see importlib.abc.MetaPathFinder and
  290. importlib.abc.PathEntryFinder) should modify ModuleSpec instances.
  291. """
  292. def __init__(self, name, loader, *, origin=None, loader_state=None,
  293. is_package=None):
  294. self.name = name
  295. self.loader = loader
  296. self.origin = origin
  297. self.loader_state = loader_state
  298. self.submodule_search_locations = [] if is_package else None
  299. # file-location attributes
  300. self._set_fileattr = False
  301. self._cached = None
  302. def __repr__(self):
  303. args = ['name={!r}'.format(self.name),
  304. 'loader={!r}'.format(self.loader)]
  305. if self.origin is not None:
  306. args.append('origin={!r}'.format(self.origin))
  307. if self.submodule_search_locations is not None:
  308. args.append('submodule_search_locations={}'
  309. .format(self.submodule_search_locations))
  310. return '{}({})'.format(self.__class__.__name__, ', '.join(args))
  311. def __eq__(self, other):
  312. smsl = self.submodule_search_locations
  313. try:
  314. return (self.name == other.name and
  315. self.loader == other.loader and
  316. self.origin == other.origin and
  317. smsl == other.submodule_search_locations and
  318. self.cached == other.cached and
  319. self.has_location == other.has_location)
  320. except AttributeError:
  321. return False
  322. @property
  323. def cached(self):
  324. if self._cached is None:
  325. if self.origin is not None and self._set_fileattr:
  326. if _bootstrap_external is None:
  327. raise NotImplementedError
  328. self._cached = _bootstrap_external._get_cached(self.origin)
  329. return self._cached
  330. @cached.setter
  331. def cached(self, cached):
  332. self._cached = cached
  333. @property
  334. def parent(self):
  335. """The name of the module's parent."""
  336. if self.submodule_search_locations is None:
  337. return self.name.rpartition('.')[0]
  338. else:
  339. return self.name
  340. @property
  341. def has_location(self):
  342. return self._set_fileattr
  343. @has_location.setter
  344. def has_location(self, value):
  345. self._set_fileattr = bool(value)
  346. def spec_from_loader(name, loader, *, origin=None, is_package=None):
  347. """Return a module spec based on various loader methods."""
  348. if hasattr(loader, 'get_filename'):
  349. if _bootstrap_external is None:
  350. raise NotImplementedError
  351. spec_from_file_location = _bootstrap_external.spec_from_file_location
  352. if is_package is None:
  353. return spec_from_file_location(name, loader=loader)
  354. search = [] if is_package else None
  355. return spec_from_file_location(name, loader=loader,
  356. submodule_search_locations=search)
  357. if is_package is None:
  358. if hasattr(loader, 'is_package'):
  359. try:
  360. is_package = loader.is_package(name)
  361. except ImportError:
  362. is_package = None # aka, undefined
  363. else:
  364. # the default
  365. is_package = False
  366. return ModuleSpec(name, loader, origin=origin, is_package=is_package)
  367. def _spec_from_module(module, loader=None, origin=None):
  368. # This function is meant for use in _setup().
  369. try:
  370. spec = module.__spec__
  371. except AttributeError:
  372. pass
  373. else:
  374. if spec is not None:
  375. return spec
  376. name = module.__name__
  377. if loader is None:
  378. try:
  379. loader = module.__loader__
  380. except AttributeError:
  381. # loader will stay None.
  382. pass
  383. try:
  384. location = module.__file__
  385. except AttributeError:
  386. location = None
  387. if origin is None:
  388. if location is None:
  389. try:
  390. origin = loader._ORIGIN
  391. except AttributeError:
  392. origin = None
  393. else:
  394. origin = location
  395. try:
  396. cached = module.__cached__
  397. except AttributeError:
  398. cached = None
  399. try:
  400. submodule_search_locations = list(module.__path__)
  401. except AttributeError:
  402. submodule_search_locations = None
  403. spec = ModuleSpec(name, loader, origin=origin)
  404. spec._set_fileattr = False if location is None else True
  405. spec.cached = cached
  406. spec.submodule_search_locations = submodule_search_locations
  407. return spec
  408. def _init_module_attrs(spec, module, *, override=False):
  409. # The passed-in module may be not support attribute assignment,
  410. # in which case we simply don't set the attributes.
  411. # __name__
  412. if (override or getattr(module, '__name__', None) is None):
  413. try:
  414. module.__name__ = spec.name
  415. except AttributeError:
  416. pass
  417. # __loader__
  418. if override or getattr(module, '__loader__', None) is None:
  419. loader = spec.loader
  420. if loader is None:
  421. # A backward compatibility hack.
  422. if spec.submodule_search_locations is not None:
  423. if _bootstrap_external is None:
  424. raise NotImplementedError
  425. _NamespaceLoader = _bootstrap_external._NamespaceLoader
  426. loader = _NamespaceLoader.__new__(_NamespaceLoader)
  427. loader._path = spec.submodule_search_locations
  428. spec.loader = loader
  429. # While the docs say that module.__file__ is not set for
  430. # built-in modules, and the code below will avoid setting it if
  431. # spec.has_location is false, this is incorrect for namespace
  432. # packages. Namespace packages have no location, but their
  433. # __spec__.origin is None, and thus their module.__file__
  434. # should also be None for consistency. While a bit of a hack,
  435. # this is the best place to ensure this consistency.
  436. #
  437. # See # https://docs.python.org/3/library/importlib.html#importlib.abc.Loader.load_module
  438. # and bpo-32305
  439. module.__file__ = None
  440. try:
  441. module.__loader__ = loader
  442. except AttributeError:
  443. pass
  444. # __package__
  445. if override or getattr(module, '__package__', None) is None:
  446. try:
  447. module.__package__ = spec.parent
  448. except AttributeError:
  449. pass
  450. # __spec__
  451. try:
  452. module.__spec__ = spec
  453. except AttributeError:
  454. pass
  455. # __path__
  456. if override or getattr(module, '__path__', None) is None:
  457. if spec.submodule_search_locations is not None:
  458. try:
  459. module.__path__ = spec.submodule_search_locations
  460. except AttributeError:
  461. pass
  462. # __file__/__cached__
  463. if spec.has_location:
  464. if override or getattr(module, '__file__', None) is None:
  465. try:
  466. module.__file__ = spec.origin
  467. except AttributeError:
  468. pass
  469. if override or getattr(module, '__cached__', None) is None:
  470. if spec.cached is not None:
  471. try:
  472. module.__cached__ = spec.cached
  473. except AttributeError:
  474. pass
  475. return module
  476. def module_from_spec(spec):
  477. """Create a module based on the provided spec."""
  478. # Typically loaders will not implement create_module().
  479. module = None
  480. if hasattr(spec.loader, 'create_module'):
  481. # If create_module() returns `None` then it means default
  482. # module creation should be used.
  483. module = spec.loader.create_module(spec)
  484. elif hasattr(spec.loader, 'exec_module'):
  485. raise ImportError('loaders that define exec_module() '
  486. 'must also define create_module()')
  487. if module is None:
  488. module = _new_module(spec.name)
  489. _init_module_attrs(spec, module)
  490. return module
  491. def _module_repr_from_spec(spec):
  492. """Return the repr to use for the module."""
  493. # We mostly replicate _module_repr() using the spec attributes.
  494. name = '?' if spec.name is None else spec.name
  495. if spec.origin is None:
  496. if spec.loader is None:
  497. return '<module {!r}>'.format(name)
  498. else:
  499. return '<module {!r} ({!r})>'.format(name, spec.loader)
  500. else:
  501. if spec.has_location:
  502. return '<module {!r} from {!r}>'.format(name, spec.origin)
  503. else:
  504. return '<module {!r} ({})>'.format(spec.name, spec.origin)
  505. # Used by importlib.reload() and _load_module_shim().
  506. def _exec(spec, module):
  507. """Execute the spec's specified module in an existing module's namespace."""
  508. name = spec.name
  509. with _ModuleLockManager(name):
  510. if sys.modules.get(name) is not module:
  511. msg = 'module {!r} not in sys.modules'.format(name)
  512. raise ImportError(msg, name=name)
  513. if spec.loader is None:
  514. if spec.submodule_search_locations is None:
  515. raise ImportError('missing loader', name=spec.name)
  516. # namespace package
  517. _init_module_attrs(spec, module, override=True)
  518. return module
  519. _init_module_attrs(spec, module, override=True)
  520. if not hasattr(spec.loader, 'exec_module'):
  521. # (issue19713) Once BuiltinImporter and ExtensionFileLoader
  522. # have exec_module() implemented, we can add a deprecation
  523. # warning here.
  524. spec.loader.load_module(name)
  525. else:
  526. spec.loader.exec_module(module)
  527. return sys.modules[name]
  528. def _load_backward_compatible(spec):
  529. # (issue19713) Once BuiltinImporter and ExtensionFileLoader
  530. # have exec_module() implemented, we can add a deprecation
  531. # warning here.
  532. spec.loader.load_module(spec.name)
  533. # The module must be in sys.modules at this point!
  534. module = sys.modules[spec.name]
  535. if getattr(module, '__loader__', None) is None:
  536. try:
  537. module.__loader__ = spec.loader
  538. except AttributeError:
  539. pass
  540. if getattr(module, '__package__', None) is None:
  541. try:
  542. # Since module.__path__ may not line up with
  543. # spec.submodule_search_paths, we can't necessarily rely
  544. # on spec.parent here.
  545. module.__package__ = module.__name__
  546. if not hasattr(module, '__path__'):
  547. module.__package__ = spec.name.rpartition('.')[0]
  548. except AttributeError:
  549. pass
  550. if getattr(module, '__spec__', None) is None:
  551. try:
  552. module.__spec__ = spec
  553. except AttributeError:
  554. pass
  555. return module
  556. def _load_unlocked(spec):
  557. # A helper for direct use by the import system.
  558. if spec.loader is not None:
  559. # not a namespace package
  560. if not hasattr(spec.loader, 'exec_module'):
  561. return _load_backward_compatible(spec)
  562. module = module_from_spec(spec)
  563. with _installed_safely(module):
  564. if spec.loader is None:
  565. if spec.submodule_search_locations is None:
  566. raise ImportError('missing loader', name=spec.name)
  567. # A namespace package so do nothing.
  568. else:
  569. spec.loader.exec_module(module)
  570. # We don't ensure that the import-related module attributes get
  571. # set in the sys.modules replacement case. Such modules are on
  572. # their own.
  573. return sys.modules[spec.name]
  574. # A method used during testing of _load_unlocked() and by
  575. # _load_module_shim().
  576. def _load(spec):
  577. """Return a new module object, loaded by the spec's loader.
  578. The module is not added to its parent.
  579. If a module is already in sys.modules, that existing module gets
  580. clobbered.
  581. """
  582. with _ModuleLockManager(spec.name):
  583. return _load_unlocked(spec)
  584. # Loaders #####################################################################
  585. class BuiltinImporter:
  586. """Meta path import for built-in modules.
  587. All methods are either class or static methods to avoid the need to
  588. instantiate the class.
  589. """
  590. @staticmethod
  591. def module_repr(module):
  592. """Return repr for the module.
  593. The method is deprecated. The import machinery does the job itself.
  594. """
  595. return '<module {!r} (built-in)>'.format(module.__name__)
  596. @classmethod
  597. def find_spec(cls, fullname, path=None, target=None):
  598. if path is not None:
  599. return None
  600. if _imp.is_builtin(fullname):
  601. return spec_from_loader(fullname, cls, origin='built-in')
  602. else:
  603. return None
  604. @classmethod
  605. def find_module(cls, fullname, path=None):
  606. """Find the built-in module.
  607. If 'path' is ever specified then the search is considered a failure.
  608. This method is deprecated. Use find_spec() instead.
  609. """
  610. spec = cls.find_spec(fullname, path)
  611. return spec.loader if spec is not None else None
  612. @classmethod
  613. def create_module(self, spec):
  614. """Create a built-in module"""
  615. if spec.name not in sys.builtin_module_names:
  616. raise ImportError('{!r} is not a built-in module'.format(spec.name),
  617. name=spec.name)
  618. return _call_with_frames_removed(_imp.create_builtin, spec)
  619. @classmethod
  620. def exec_module(self, module):
  621. """Exec a built-in module"""
  622. _call_with_frames_removed(_imp.exec_builtin, module)
  623. @classmethod
  624. @_requires_builtin
  625. def get_code(cls, fullname):
  626. """Return None as built-in modules do not have code objects."""
  627. return None
  628. @classmethod
  629. @_requires_builtin
  630. def get_source(cls, fullname):
  631. """Return None as built-in modules do not have source code."""
  632. return None
  633. @classmethod
  634. @_requires_builtin
  635. def is_package(cls, fullname):
  636. """Return False as built-in modules are never packages."""
  637. return False
  638. load_module = classmethod(_load_module_shim)
  639. class FrozenImporter:
  640. """Meta path import for frozen modules.
  641. All methods are either class or static methods to avoid the need to
  642. instantiate the class.
  643. """
  644. @staticmethod
  645. def module_repr(m):
  646. """Return repr for the module.
  647. The method is deprecated. The import machinery does the job itself.
  648. """
  649. return '<module {!r} (frozen)>'.format(m.__name__)
  650. @classmethod
  651. def find_spec(cls, fullname, path=None, target=None):
  652. if _imp.is_frozen(fullname):
  653. return spec_from_loader(fullname, cls, origin='frozen')
  654. else:
  655. return None
  656. @classmethod
  657. def find_module(cls, fullname, path=None):
  658. """Find a frozen module.
  659. This method is deprecated. Use find_spec() instead.
  660. """
  661. return cls if _imp.is_frozen(fullname) else None
  662. @classmethod
  663. def create_module(cls, spec):
  664. """Use default semantics for module creation."""
  665. @staticmethod
  666. def exec_module(module):
  667. name = module.__spec__.name
  668. if not _imp.is_frozen(name):
  669. raise ImportError('{!r} is not a frozen module'.format(name),
  670. name=name)
  671. code = _call_with_frames_removed(_imp.get_frozen_object, name)
  672. exec(code, module.__dict__)
  673. @classmethod
  674. def load_module(cls, fullname):
  675. """Load a frozen module.
  676. This method is deprecated. Use exec_module() instead.
  677. """
  678. return _load_module_shim(cls, fullname)
  679. @classmethod
  680. @_requires_frozen
  681. def get_code(cls, fullname):
  682. """Return the code object for the frozen module."""
  683. return _imp.get_frozen_object(fullname)
  684. @classmethod
  685. @_requires_frozen
  686. def get_source(cls, fullname):
  687. """Return None as frozen modules do not have source code."""
  688. return None
  689. @classmethod
  690. @_requires_frozen
  691. def is_package(cls, fullname):
  692. """Return True if the frozen module is a package."""
  693. return _imp.is_frozen_package(fullname)
  694. # Import itself ###############################################################
  695. class _ImportLockContext:
  696. """Context manager for the import lock."""
  697. def __enter__(self):
  698. """Acquire the import lock."""
  699. _imp.acquire_lock()
  700. def __exit__(self, exc_type, exc_value, exc_traceback):
  701. """Release the import lock regardless of any raised exceptions."""
  702. _imp.release_lock()
  703. def _resolve_name(name, package, level):
  704. """Resolve a relative module name to an absolute one."""
  705. bits = package.rsplit('.', level - 1)
  706. if len(bits) < level:
  707. raise ValueError('attempted relative import beyond top-level package')
  708. base = bits[0]
  709. return '{}.{}'.format(base, name) if name else base
  710. def _find_spec_legacy(finder, name, path):
  711. # This would be a good place for a DeprecationWarning if
  712. # we ended up going that route.
  713. loader = finder.find_module(name, path)
  714. if loader is None:
  715. return None
  716. return spec_from_loader(name, loader)
  717. def _find_spec(name, path, target=None):
  718. """Find a module's spec."""
  719. meta_path = sys.meta_path
  720. if meta_path is None:
  721. # PyImport_Cleanup() is running or has been called.
  722. raise ImportError("sys.meta_path is None, Python is likely "
  723. "shutting down")
  724. if not meta_path:
  725. _warnings.warn('sys.meta_path is empty', ImportWarning)
  726. # We check sys.modules here for the reload case. While a passed-in
  727. # target will usually indicate a reload there is no guarantee, whereas
  728. # sys.modules provides one.
  729. is_reload = name in sys.modules
  730. for finder in meta_path:
  731. with _ImportLockContext():
  732. try:
  733. find_spec = finder.find_spec
  734. except AttributeError:
  735. spec = _find_spec_legacy(finder, name, path)
  736. if spec is None:
  737. continue
  738. else:
  739. spec = find_spec(name, path, target)
  740. if spec is not None:
  741. # The parent import may have already imported this module.
  742. if not is_reload and name in sys.modules:
  743. module = sys.modules[name]
  744. try:
  745. __spec__ = module.__spec__
  746. except AttributeError:
  747. # We use the found spec since that is the one that
  748. # we would have used if the parent module hadn't
  749. # beaten us to the punch.
  750. return spec
  751. else:
  752. if __spec__ is None:
  753. return spec
  754. else:
  755. return __spec__
  756. else:
  757. return spec
  758. else:
  759. return None
  760. def _sanity_check(name, package, level):
  761. """Verify arguments are "sane"."""
  762. if not isinstance(name, str):
  763. raise TypeError('module name must be str, not {}'.format(type(name)))
  764. if level < 0:
  765. raise ValueError('level must be >= 0')
  766. if level > 0:
  767. if not isinstance(package, str):
  768. raise TypeError('__package__ not set to a string')
  769. elif not package:
  770. raise ImportError('attempted relative import with no known parent '
  771. 'package')
  772. if not name and level == 0:
  773. raise ValueError('Empty module name')
  774. _ERR_MSG_PREFIX = 'No module named '
  775. _ERR_MSG = _ERR_MSG_PREFIX + '{!r}'
  776. def _find_and_load_unlocked(name, import_):
  777. path = None
  778. parent = name.rpartition('.')[0]
  779. if parent:
  780. if parent not in sys.modules:
  781. _call_with_frames_removed(import_, parent)
  782. # Crazy side-effects!
  783. if name in sys.modules:
  784. return sys.modules[name]
  785. parent_module = sys.modules[parent]
  786. try:
  787. path = parent_module.__path__
  788. except AttributeError:
  789. msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
  790. raise ModuleNotFoundError(msg, name=name) from None
  791. spec = _find_spec(name, path)
  792. if spec is None:
  793. raise ModuleNotFoundError(_ERR_MSG.format(name), name=name)
  794. else:
  795. module = _load_unlocked(spec)
  796. if parent:
  797. # Set the module as an attribute on its parent.
  798. parent_module = sys.modules[parent]
  799. setattr(parent_module, name.rpartition('.')[2], module)
  800. return module
  801. _NEEDS_LOADING = object()
  802. def _find_and_load(name, import_):
  803. """Find and load the module."""
  804. with _ModuleLockManager(name):
  805. module = sys.modules.get(name, _NEEDS_LOADING)
  806. if module is _NEEDS_LOADING:
  807. return _find_and_load_unlocked(name, import_)
  808. if module is None:
  809. message = ('import of {} halted; '
  810. 'None in sys.modules'.format(name))
  811. raise ModuleNotFoundError(message, name=name)
  812. _lock_unlock_module(name)
  813. return module
  814. def _gcd_import(name, package=None, level=0):
  815. """Import and return the module based on its name, the package the call is
  816. being made from, and the level adjustment.
  817. This function represents the greatest common denominator of functionality
  818. between import_module and __import__. This includes setting __package__ if
  819. the loader did not.
  820. """
  821. _sanity_check(name, package, level)
  822. if level > 0:
  823. name = _resolve_name(name, package, level)
  824. return _find_and_load(name, _gcd_import)
  825. def _handle_fromlist(module, fromlist, import_, *, recursive=False):
  826. """Figure out what __import__ should return.
  827. The import_ parameter is a callable which takes the name of module to
  828. import. It is required to decouple the function from assuming importlib's
  829. import implementation is desired.
  830. """
  831. # The hell that is fromlist ...
  832. # If a package was imported, try to import stuff from fromlist.
  833. if hasattr(module, '__path__'):
  834. for x in fromlist:
  835. if not isinstance(x, str):
  836. if recursive:
  837. where = module.__name__ + '.__all__'
  838. else:
  839. where = "``from list''"
  840. raise TypeError(f"Item in {where} must be str, "
  841. f"not {type(x).__name__}")
  842. elif x == '*':
  843. if not recursive and hasattr(module, '__all__'):
  844. _handle_fromlist(module, module.__all__, import_,
  845. recursive=True)
  846. elif not hasattr(module, x):
  847. from_name = '{}.{}'.format(module.__name__, x)
  848. try:
  849. _call_with_frames_removed(import_, from_name)
  850. except ModuleNotFoundError as exc:
  851. # Backwards-compatibility dictates we ignore failed
  852. # imports triggered by fromlist for modules that don't
  853. # exist.
  854. if (exc.name == from_name and
  855. sys.modules.get(from_name, _NEEDS_LOADING) is not None):
  856. continue
  857. raise
  858. return module
  859. def _calc___package__(globals):
  860. """Calculate what __package__ should be.
  861. __package__ is not guaranteed to be defined or could be set to None
  862. to represent that its proper value is unknown.
  863. """
  864. package = globals.get('__package__')
  865. spec = globals.get('__spec__')
  866. if package is not None:
  867. if spec is not None and package != spec.parent:
  868. _warnings.warn("__package__ != __spec__.parent "
  869. f"({package!r} != {spec.parent!r})",
  870. ImportWarning, stacklevel=3)
  871. return package
  872. elif spec is not None:
  873. return spec.parent
  874. else:
  875. _warnings.warn("can't resolve package from __spec__ or __package__, "
  876. "falling back on __name__ and __path__",
  877. ImportWarning, stacklevel=3)
  878. package = globals['__name__']
  879. if '__path__' not in globals:
  880. package = package.rpartition('.')[0]
  881. return package
  882. def __import__(name, globals=None, locals=None, fromlist=(), level=0):
  883. """Import a module.
  884. The 'globals' argument is used to infer where the import is occurring from
  885. to handle relative imports. The 'locals' argument is ignored. The
  886. 'fromlist' argument specifies what should exist as attributes on the module
  887. being imported (e.g. ``from module import <fromlist>``). The 'level'
  888. argument represents the package location to import from in a relative
  889. import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
  890. """
  891. if level == 0:
  892. module = _gcd_import(name)
  893. else:
  894. globals_ = globals if globals is not None else {}
  895. package = _calc___package__(globals_)
  896. module = _gcd_import(name, package, level)
  897. if not fromlist:
  898. # Return up to the first dot in 'name'. This is complicated by the fact
  899. # that 'name' may be relative.
  900. if level == 0:
  901. return _gcd_import(name.partition('.')[0])
  902. elif not name:
  903. return module
  904. else:
  905. # Figure out where to slice the module's name up to the first dot
  906. # in 'name'.
  907. cut_off = len(name) - len(name.partition('.')[0])
  908. # Slice end needs to be positive to alleviate need to special-case
  909. # when ``'.' not in name``.
  910. return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  911. else:
  912. return _handle_fromlist(module, fromlist, _gcd_import)
  913. def _builtin_from_name(name):
  914. spec = BuiltinImporter.find_spec(name)
  915. if spec is None:
  916. raise ImportError('no built-in module named ' + name)
  917. return _load_unlocked(spec)
  918. def _setup(sys_module, _imp_module):
  919. """Setup importlib by importing needed built-in modules and injecting them
  920. into the global namespace.
  921. As sys is needed for sys.modules access and _imp is needed to load built-in
  922. modules, those two modules must be explicitly passed in.
  923. """
  924. global _imp, sys
  925. _imp = _imp_module
  926. sys = sys_module
  927. # Set up the spec for existing builtin/frozen modules.
  928. module_type = type(sys)
  929. for name, module in sys.modules.items():
  930. if isinstance(module, module_type):
  931. if name in sys.builtin_module_names:
  932. loader = BuiltinImporter
  933. elif _imp.is_frozen(name):
  934. loader = FrozenImporter
  935. else:
  936. continue
  937. spec = _spec_from_module(module, loader)
  938. _init_module_attrs(spec, module)
  939. # Directly load built-in modules needed during bootstrap.
  940. self_module = sys.modules[__name__]
  941. for builtin_name in ('_thread', '_warnings', '_weakref'):
  942. if builtin_name not in sys.modules:
  943. builtin_module = _builtin_from_name(builtin_name)
  944. else:
  945. builtin_module = sys.modules[builtin_name]
  946. setattr(self_module, builtin_name, builtin_module)
  947. def _install(sys_module, _imp_module):
  948. """Install importers for builtin and frozen modules"""
  949. _setup(sys_module, _imp_module)
  950. sys.meta_path.append(BuiltinImporter)
  951. sys.meta_path.append(FrozenImporter)
  952. def _install_external_importers():
  953. """Install importers that require external filesystem access"""
  954. global _bootstrap_external
  955. import _frozen_importlib_external
  956. _bootstrap_external = _frozen_importlib_external
  957. _frozen_importlib_external._install(sys.modules[__name__])