_bootstrap.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  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. def _object_name(obj):
  19. try:
  20. return obj.__qualname__
  21. except AttributeError:
  22. return type(obj).__qualname__
  23. # Bootstrap-related code ######################################################
  24. # Modules injected manually by _setup()
  25. _thread = None
  26. _warnings = None
  27. _weakref = None
  28. # Import done by _install_external_importers()
  29. _bootstrap_external = None
  30. def _wrap(new, old):
  31. """Simple substitute for functools.update_wrapper."""
  32. for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
  33. if hasattr(old, replace):
  34. setattr(new, replace, getattr(old, replace))
  35. new.__dict__.update(old.__dict__)
  36. def _new_module(name):
  37. return type(sys)(name)
  38. # Module-level locking ########################################################
  39. # For a list that can have a weakref to it.
  40. class _List(list):
  41. pass
  42. # Copied from weakref.py with some simplifications and modifications unique to
  43. # bootstrapping importlib. Many methods were simply deleting for simplicity, so if they
  44. # are needed in the future they may work if simply copied back in.
  45. class _WeakValueDictionary:
  46. def __init__(self):
  47. self_weakref = _weakref.ref(self)
  48. # Inlined to avoid issues with inheriting from _weakref.ref before _weakref is
  49. # set by _setup(). Since there's only one instance of this class, this is
  50. # not expensive.
  51. class KeyedRef(_weakref.ref):
  52. __slots__ = "key",
  53. def __new__(type, ob, key):
  54. self = super().__new__(type, ob, type.remove)
  55. self.key = key
  56. return self
  57. def __init__(self, ob, key):
  58. super().__init__(ob, self.remove)
  59. @staticmethod
  60. def remove(wr):
  61. nonlocal self_weakref
  62. self = self_weakref()
  63. if self is not None:
  64. if self._iterating:
  65. self._pending_removals.append(wr.key)
  66. else:
  67. _weakref._remove_dead_weakref(self.data, wr.key)
  68. self._KeyedRef = KeyedRef
  69. self.clear()
  70. def clear(self):
  71. self._pending_removals = []
  72. self._iterating = set()
  73. self.data = {}
  74. def _commit_removals(self):
  75. pop = self._pending_removals.pop
  76. d = self.data
  77. while True:
  78. try:
  79. key = pop()
  80. except IndexError:
  81. return
  82. _weakref._remove_dead_weakref(d, key)
  83. def get(self, key, default=None):
  84. if self._pending_removals:
  85. self._commit_removals()
  86. try:
  87. wr = self.data[key]
  88. except KeyError:
  89. return default
  90. else:
  91. if (o := wr()) is None:
  92. return default
  93. else:
  94. return o
  95. def setdefault(self, key, default=None):
  96. try:
  97. o = self.data[key]()
  98. except KeyError:
  99. o = None
  100. if o is None:
  101. if self._pending_removals:
  102. self._commit_removals()
  103. self.data[key] = self._KeyedRef(default, key)
  104. return default
  105. else:
  106. return o
  107. # A dict mapping module names to weakrefs of _ModuleLock instances.
  108. # Dictionary protected by the global import lock.
  109. _module_locks = {}
  110. # A dict mapping thread IDs to weakref'ed lists of _ModuleLock instances.
  111. # This maps a thread to the module locks it is blocking on acquiring. The
  112. # values are lists because a single thread could perform a re-entrant import
  113. # and be "in the process" of blocking on locks for more than one module. A
  114. # thread can be "in the process" because a thread cannot actually block on
  115. # acquiring more than one lock but it can have set up bookkeeping that reflects
  116. # that it intends to block on acquiring more than one lock.
  117. #
  118. # The dictionary uses a WeakValueDictionary to avoid keeping unnecessary
  119. # lists around, regardless of GC runs. This way there's no memory leak if
  120. # the list is no longer needed (GH-106176).
  121. _blocking_on = None
  122. class _BlockingOnManager:
  123. """A context manager responsible to updating ``_blocking_on``."""
  124. def __init__(self, thread_id, lock):
  125. self.thread_id = thread_id
  126. self.lock = lock
  127. def __enter__(self):
  128. """Mark the running thread as waiting for self.lock. via _blocking_on."""
  129. # Interactions with _blocking_on are *not* protected by the global
  130. # import lock here because each thread only touches the state that it
  131. # owns (state keyed on its thread id). The global import lock is
  132. # re-entrant (i.e., a single thread may take it more than once) so it
  133. # wouldn't help us be correct in the face of re-entrancy either.
  134. self.blocked_on = _blocking_on.setdefault(self.thread_id, _List())
  135. self.blocked_on.append(self.lock)
  136. def __exit__(self, *args, **kwargs):
  137. """Remove self.lock from this thread's _blocking_on list."""
  138. self.blocked_on.remove(self.lock)
  139. class _DeadlockError(RuntimeError):
  140. pass
  141. def _has_deadlocked(target_id, *, seen_ids, candidate_ids, blocking_on):
  142. """Check if 'target_id' is holding the same lock as another thread(s).
  143. The search within 'blocking_on' starts with the threads listed in
  144. 'candidate_ids'. 'seen_ids' contains any threads that are considered
  145. already traversed in the search.
  146. Keyword arguments:
  147. target_id -- The thread id to try to reach.
  148. seen_ids -- A set of threads that have already been visited.
  149. candidate_ids -- The thread ids from which to begin.
  150. blocking_on -- A dict representing the thread/blocking-on graph. This may
  151. be the same object as the global '_blocking_on' but it is
  152. a parameter to reduce the impact that global mutable
  153. state has on the result of this function.
  154. """
  155. if target_id in candidate_ids:
  156. # If we have already reached the target_id, we're done - signal that it
  157. # is reachable.
  158. return True
  159. # Otherwise, try to reach the target_id from each of the given candidate_ids.
  160. for tid in candidate_ids:
  161. if not (candidate_blocking_on := blocking_on.get(tid)):
  162. # There are no edges out from this node, skip it.
  163. continue
  164. elif tid in seen_ids:
  165. # bpo 38091: the chain of tid's we encounter here eventually leads
  166. # to a fixed point or a cycle, but does not reach target_id.
  167. # This means we would not actually deadlock. This can happen if
  168. # other threads are at the beginning of acquire() below.
  169. return False
  170. seen_ids.add(tid)
  171. # Follow the edges out from this thread.
  172. edges = [lock.owner for lock in candidate_blocking_on]
  173. if _has_deadlocked(target_id, seen_ids=seen_ids, candidate_ids=edges,
  174. blocking_on=blocking_on):
  175. return True
  176. return False
  177. class _ModuleLock:
  178. """A recursive lock implementation which is able to detect deadlocks
  179. (e.g. thread 1 trying to take locks A then B, and thread 2 trying to
  180. take locks B then A).
  181. """
  182. def __init__(self, name):
  183. # Create an RLock for protecting the import process for the
  184. # corresponding module. Since it is an RLock, a single thread will be
  185. # able to take it more than once. This is necessary to support
  186. # re-entrancy in the import system that arises from (at least) signal
  187. # handlers and the garbage collector. Consider the case of:
  188. #
  189. # import foo
  190. # -> ...
  191. # -> importlib._bootstrap._ModuleLock.acquire
  192. # -> ...
  193. # -> <garbage collector>
  194. # -> __del__
  195. # -> import foo
  196. # -> ...
  197. # -> importlib._bootstrap._ModuleLock.acquire
  198. # -> _BlockingOnManager.__enter__
  199. #
  200. # If a different thread than the running one holds the lock then the
  201. # thread will have to block on taking the lock, which is what we want
  202. # for thread safety.
  203. self.lock = _thread.RLock()
  204. self.wakeup = _thread.allocate_lock()
  205. # The name of the module for which this is a lock.
  206. self.name = name
  207. # Can end up being set to None if this lock is not owned by any thread
  208. # or the thread identifier for the owning thread.
  209. self.owner = None
  210. # Represent the number of times the owning thread has acquired this lock
  211. # via a list of True. This supports RLock-like ("re-entrant lock")
  212. # behavior, necessary in case a single thread is following a circular
  213. # import dependency and needs to take the lock for a single module
  214. # more than once.
  215. #
  216. # Counts are represented as a list of True because list.append(True)
  217. # and list.pop() are both atomic and thread-safe in CPython and it's hard
  218. # to find another primitive with the same properties.
  219. self.count = []
  220. # This is a count of the number of threads that are blocking on
  221. # self.wakeup.acquire() awaiting to get their turn holding this module
  222. # lock. When the module lock is released, if this is greater than
  223. # zero, it is decremented and `self.wakeup` is released one time. The
  224. # intent is that this will let one other thread make more progress on
  225. # acquiring this module lock. This repeats until all the threads have
  226. # gotten a turn.
  227. #
  228. # This is incremented in self.acquire() when a thread notices it is
  229. # going to have to wait for another thread to finish.
  230. #
  231. # See the comment above count for explanation of the representation.
  232. self.waiters = []
  233. def has_deadlock(self):
  234. # To avoid deadlocks for concurrent or re-entrant circular imports,
  235. # look at _blocking_on to see if any threads are blocking
  236. # on getting the import lock for any module for which the import lock
  237. # is held by this thread.
  238. return _has_deadlocked(
  239. # Try to find this thread.
  240. target_id=_thread.get_ident(),
  241. seen_ids=set(),
  242. # Start from the thread that holds the import lock for this
  243. # module.
  244. candidate_ids=[self.owner],
  245. # Use the global "blocking on" state.
  246. blocking_on=_blocking_on,
  247. )
  248. def acquire(self):
  249. """
  250. Acquire the module lock. If a potential deadlock is detected,
  251. a _DeadlockError is raised.
  252. Otherwise, the lock is always acquired and True is returned.
  253. """
  254. tid = _thread.get_ident()
  255. with _BlockingOnManager(tid, self):
  256. while True:
  257. # Protect interaction with state on self with a per-module
  258. # lock. This makes it safe for more than one thread to try to
  259. # acquire the lock for a single module at the same time.
  260. with self.lock:
  261. if self.count == [] or self.owner == tid:
  262. # If the lock for this module is unowned then we can
  263. # take the lock immediately and succeed. If the lock
  264. # for this module is owned by the running thread then
  265. # we can also allow the acquire to succeed. This
  266. # supports circular imports (thread T imports module A
  267. # which imports module B which imports module A).
  268. self.owner = tid
  269. self.count.append(True)
  270. return True
  271. # At this point we know the lock is held (because count !=
  272. # 0) by another thread (because owner != tid). We'll have
  273. # to get in line to take the module lock.
  274. # But first, check to see if this thread would create a
  275. # deadlock by acquiring this module lock. If it would
  276. # then just stop with an error.
  277. #
  278. # It's not clear who is expected to handle this error.
  279. # There is one handler in _lock_unlock_module but many
  280. # times this method is called when entering the context
  281. # manager _ModuleLockManager instead - so _DeadlockError
  282. # will just propagate up to application code.
  283. #
  284. # This seems to be more than just a hypothetical -
  285. # https://stackoverflow.com/questions/59509154
  286. # https://github.com/encode/django-rest-framework/issues/7078
  287. if self.has_deadlock():
  288. raise _DeadlockError(f'deadlock detected by {self!r}')
  289. # Check to see if we're going to be able to acquire the
  290. # lock. If we are going to have to wait then increment
  291. # the waiters so `self.release` will know to unblock us
  292. # later on. We do this part non-blockingly so we don't
  293. # get stuck here before we increment waiters. We have
  294. # this extra acquire call (in addition to the one below,
  295. # outside the self.lock context manager) to make sure
  296. # self.wakeup is held when the next acquire is called (so
  297. # we block). This is probably needlessly complex and we
  298. # should just take self.wakeup in the return codepath
  299. # above.
  300. if self.wakeup.acquire(False):
  301. self.waiters.append(None)
  302. # Now take the lock in a blocking fashion. This won't
  303. # complete until the thread holding this lock
  304. # (self.owner) calls self.release.
  305. self.wakeup.acquire()
  306. # Taking the lock has served its purpose (making us wait), so we can
  307. # give it up now. We'll take it w/o blocking again on the
  308. # next iteration around this 'while' loop.
  309. self.wakeup.release()
  310. def release(self):
  311. tid = _thread.get_ident()
  312. with self.lock:
  313. if self.owner != tid:
  314. raise RuntimeError('cannot release un-acquired lock')
  315. assert len(self.count) > 0
  316. self.count.pop()
  317. if not len(self.count):
  318. self.owner = None
  319. if len(self.waiters) > 0:
  320. self.waiters.pop()
  321. self.wakeup.release()
  322. def __repr__(self):
  323. return f'_ModuleLock({self.name!r}) at {id(self)}'
  324. class _DummyModuleLock:
  325. """A simple _ModuleLock equivalent for Python builds without
  326. multi-threading support."""
  327. def __init__(self, name):
  328. self.name = name
  329. self.count = 0
  330. def acquire(self):
  331. self.count += 1
  332. return True
  333. def release(self):
  334. if self.count == 0:
  335. raise RuntimeError('cannot release un-acquired lock')
  336. self.count -= 1
  337. def __repr__(self):
  338. return f'_DummyModuleLock({self.name!r}) at {id(self)}'
  339. class _ModuleLockManager:
  340. def __init__(self, name):
  341. self._name = name
  342. self._lock = None
  343. def __enter__(self):
  344. self._lock = _get_module_lock(self._name)
  345. self._lock.acquire()
  346. def __exit__(self, *args, **kwargs):
  347. self._lock.release()
  348. # The following two functions are for consumption by Python/import.c.
  349. def _get_module_lock(name):
  350. """Get or create the module lock for a given module name.
  351. Acquire/release internally the global import lock to protect
  352. _module_locks."""
  353. _imp.acquire_lock()
  354. try:
  355. try:
  356. lock = _module_locks[name]()
  357. except KeyError:
  358. lock = None
  359. if lock is None:
  360. if _thread is None:
  361. lock = _DummyModuleLock(name)
  362. else:
  363. lock = _ModuleLock(name)
  364. def cb(ref, name=name):
  365. _imp.acquire_lock()
  366. try:
  367. # bpo-31070: Check if another thread created a new lock
  368. # after the previous lock was destroyed
  369. # but before the weakref callback was called.
  370. if _module_locks.get(name) is ref:
  371. del _module_locks[name]
  372. finally:
  373. _imp.release_lock()
  374. _module_locks[name] = _weakref.ref(lock, cb)
  375. finally:
  376. _imp.release_lock()
  377. return lock
  378. def _lock_unlock_module(name):
  379. """Acquires then releases the module lock for a given module name.
  380. This is used to ensure a module is completely initialized, in the
  381. event it is being imported by another thread.
  382. """
  383. lock = _get_module_lock(name)
  384. try:
  385. lock.acquire()
  386. except _DeadlockError:
  387. # Concurrent circular import, we'll accept a partially initialized
  388. # module object.
  389. pass
  390. else:
  391. lock.release()
  392. # Frame stripping magic ###############################################
  393. def _call_with_frames_removed(f, *args, **kwds):
  394. """remove_importlib_frames in import.c will always remove sequences
  395. of importlib frames that end with a call to this function
  396. Use it instead of a normal call in places where including the importlib
  397. frames introduces unwanted noise into the traceback (e.g. when executing
  398. module code)
  399. """
  400. return f(*args, **kwds)
  401. def _verbose_message(message, *args, verbosity=1):
  402. """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
  403. if sys.flags.verbose >= verbosity:
  404. if not message.startswith(('#', 'import ')):
  405. message = '# ' + message
  406. print(message.format(*args), file=sys.stderr)
  407. def _requires_builtin(fxn):
  408. """Decorator to verify the named module is built-in."""
  409. def _requires_builtin_wrapper(self, fullname):
  410. if fullname not in sys.builtin_module_names:
  411. raise ImportError(f'{fullname!r} is not a built-in module',
  412. name=fullname)
  413. return fxn(self, fullname)
  414. _wrap(_requires_builtin_wrapper, fxn)
  415. return _requires_builtin_wrapper
  416. def _requires_frozen(fxn):
  417. """Decorator to verify the named module is frozen."""
  418. def _requires_frozen_wrapper(self, fullname):
  419. if not _imp.is_frozen(fullname):
  420. raise ImportError(f'{fullname!r} is not a frozen module',
  421. name=fullname)
  422. return fxn(self, fullname)
  423. _wrap(_requires_frozen_wrapper, fxn)
  424. return _requires_frozen_wrapper
  425. # Typically used by loader classes as a method replacement.
  426. def _load_module_shim(self, fullname):
  427. """Load the specified module into sys.modules and return it.
  428. This method is deprecated. Use loader.exec_module() instead.
  429. """
  430. msg = ("the load_module() method is deprecated and slated for removal in "
  431. "Python 3.12; use exec_module() instead")
  432. _warnings.warn(msg, DeprecationWarning)
  433. spec = spec_from_loader(fullname, self)
  434. if fullname in sys.modules:
  435. module = sys.modules[fullname]
  436. _exec(spec, module)
  437. return sys.modules[fullname]
  438. else:
  439. return _load(spec)
  440. # Module specifications #######################################################
  441. def _module_repr(module):
  442. """The implementation of ModuleType.__repr__()."""
  443. loader = getattr(module, '__loader__', None)
  444. if spec := getattr(module, "__spec__", None):
  445. return _module_repr_from_spec(spec)
  446. # Fall through to a catch-all which always succeeds.
  447. try:
  448. name = module.__name__
  449. except AttributeError:
  450. name = '?'
  451. try:
  452. filename = module.__file__
  453. except AttributeError:
  454. if loader is None:
  455. return f'<module {name!r}>'
  456. else:
  457. return f'<module {name!r} ({loader!r})>'
  458. else:
  459. return f'<module {name!r} from {filename!r}>'
  460. class ModuleSpec:
  461. """The specification for a module, used for loading.
  462. A module's spec is the source for information about the module. For
  463. data associated with the module, including source, use the spec's
  464. loader.
  465. `name` is the absolute name of the module. `loader` is the loader
  466. to use when loading the module. `parent` is the name of the
  467. package the module is in. The parent is derived from the name.
  468. `is_package` determines if the module is considered a package or
  469. not. On modules this is reflected by the `__path__` attribute.
  470. `origin` is the specific location used by the loader from which to
  471. load the module, if that information is available. When filename is
  472. set, origin will match.
  473. `has_location` indicates that a spec's "origin" reflects a location.
  474. When this is True, `__file__` attribute of the module is set.
  475. `cached` is the location of the cached bytecode file, if any. It
  476. corresponds to the `__cached__` attribute.
  477. `submodule_search_locations` is the sequence of path entries to
  478. search when importing submodules. If set, is_package should be
  479. True--and False otherwise.
  480. Packages are simply modules that (may) have submodules. If a spec
  481. has a non-None value in `submodule_search_locations`, the import
  482. system will consider modules loaded from the spec as packages.
  483. Only finders (see importlib.abc.MetaPathFinder and
  484. importlib.abc.PathEntryFinder) should modify ModuleSpec instances.
  485. """
  486. def __init__(self, name, loader, *, origin=None, loader_state=None,
  487. is_package=None):
  488. self.name = name
  489. self.loader = loader
  490. self.origin = origin
  491. self.loader_state = loader_state
  492. self.submodule_search_locations = [] if is_package else None
  493. self._uninitialized_submodules = []
  494. # file-location attributes
  495. self._set_fileattr = False
  496. self._cached = None
  497. def __repr__(self):
  498. args = [f'name={self.name!r}', f'loader={self.loader!r}']
  499. if self.origin is not None:
  500. args.append(f'origin={self.origin!r}')
  501. if self.submodule_search_locations is not None:
  502. args.append(f'submodule_search_locations={self.submodule_search_locations}')
  503. return f'{self.__class__.__name__}({", ".join(args)})'
  504. def __eq__(self, other):
  505. smsl = self.submodule_search_locations
  506. try:
  507. return (self.name == other.name and
  508. self.loader == other.loader and
  509. self.origin == other.origin and
  510. smsl == other.submodule_search_locations and
  511. self.cached == other.cached and
  512. self.has_location == other.has_location)
  513. except AttributeError:
  514. return NotImplemented
  515. @property
  516. def cached(self):
  517. if self._cached is None:
  518. if self.origin is not None and self._set_fileattr:
  519. if _bootstrap_external is None:
  520. raise NotImplementedError
  521. self._cached = _bootstrap_external._get_cached(self.origin)
  522. return self._cached
  523. @cached.setter
  524. def cached(self, cached):
  525. self._cached = cached
  526. @property
  527. def parent(self):
  528. """The name of the module's parent."""
  529. if self.submodule_search_locations is None:
  530. return self.name.rpartition('.')[0]
  531. else:
  532. return self.name
  533. @property
  534. def has_location(self):
  535. return self._set_fileattr
  536. @has_location.setter
  537. def has_location(self, value):
  538. self._set_fileattr = bool(value)
  539. def spec_from_loader(name, loader, *, origin=None, is_package=None):
  540. """Return a module spec based on various loader methods."""
  541. if origin is None:
  542. origin = getattr(loader, '_ORIGIN', None)
  543. if not origin and hasattr(loader, 'get_filename'):
  544. if _bootstrap_external is None:
  545. raise NotImplementedError
  546. spec_from_file_location = _bootstrap_external.spec_from_file_location
  547. if is_package is None:
  548. return spec_from_file_location(name, loader=loader)
  549. search = [] if is_package else None
  550. return spec_from_file_location(name, loader=loader,
  551. submodule_search_locations=search)
  552. if is_package is None:
  553. if hasattr(loader, 'is_package'):
  554. try:
  555. is_package = loader.is_package(name)
  556. except ImportError:
  557. is_package = None # aka, undefined
  558. else:
  559. # the default
  560. is_package = False
  561. return ModuleSpec(name, loader, origin=origin, is_package=is_package)
  562. def _spec_from_module(module, loader=None, origin=None):
  563. # This function is meant for use in _setup().
  564. try:
  565. spec = module.__spec__
  566. except AttributeError:
  567. pass
  568. else:
  569. if spec is not None:
  570. return spec
  571. name = module.__name__
  572. if loader is None:
  573. try:
  574. loader = module.__loader__
  575. except AttributeError:
  576. # loader will stay None.
  577. pass
  578. try:
  579. location = module.__file__
  580. except AttributeError:
  581. location = None
  582. if origin is None:
  583. if loader is not None:
  584. origin = getattr(loader, '_ORIGIN', None)
  585. if not origin and location is not None:
  586. origin = location
  587. try:
  588. cached = module.__cached__
  589. except AttributeError:
  590. cached = None
  591. try:
  592. submodule_search_locations = list(module.__path__)
  593. except AttributeError:
  594. submodule_search_locations = None
  595. spec = ModuleSpec(name, loader, origin=origin)
  596. spec._set_fileattr = False if location is None else (origin == location)
  597. spec.cached = cached
  598. spec.submodule_search_locations = submodule_search_locations
  599. return spec
  600. def _init_module_attrs(spec, module, *, override=False):
  601. # The passed-in module may be not support attribute assignment,
  602. # in which case we simply don't set the attributes.
  603. # __name__
  604. if (override or getattr(module, '__name__', None) is None):
  605. try:
  606. module.__name__ = spec.name
  607. except AttributeError:
  608. pass
  609. # __loader__
  610. if override or getattr(module, '__loader__', None) is None:
  611. loader = spec.loader
  612. if loader is None:
  613. # A backward compatibility hack.
  614. if spec.submodule_search_locations is not None:
  615. if _bootstrap_external is None:
  616. raise NotImplementedError
  617. NamespaceLoader = _bootstrap_external.NamespaceLoader
  618. loader = NamespaceLoader.__new__(NamespaceLoader)
  619. loader._path = spec.submodule_search_locations
  620. spec.loader = loader
  621. # While the docs say that module.__file__ is not set for
  622. # built-in modules, and the code below will avoid setting it if
  623. # spec.has_location is false, this is incorrect for namespace
  624. # packages. Namespace packages have no location, but their
  625. # __spec__.origin is None, and thus their module.__file__
  626. # should also be None for consistency. While a bit of a hack,
  627. # this is the best place to ensure this consistency.
  628. #
  629. # See # https://docs.python.org/3/library/importlib.html#importlib.abc.Loader.load_module
  630. # and bpo-32305
  631. module.__file__ = None
  632. try:
  633. module.__loader__ = loader
  634. except AttributeError:
  635. pass
  636. # __package__
  637. if override or getattr(module, '__package__', None) is None:
  638. try:
  639. module.__package__ = spec.parent
  640. except AttributeError:
  641. pass
  642. # __spec__
  643. try:
  644. module.__spec__ = spec
  645. except AttributeError:
  646. pass
  647. # __path__
  648. if override or getattr(module, '__path__', None) is None:
  649. if spec.submodule_search_locations is not None:
  650. # XXX We should extend __path__ if it's already a list.
  651. try:
  652. module.__path__ = spec.submodule_search_locations
  653. except AttributeError:
  654. pass
  655. # __file__/__cached__
  656. if spec.has_location:
  657. if override or getattr(module, '__file__', None) is None:
  658. try:
  659. module.__file__ = spec.origin
  660. except AttributeError:
  661. pass
  662. if override or getattr(module, '__cached__', None) is None:
  663. if spec.cached is not None:
  664. try:
  665. module.__cached__ = spec.cached
  666. except AttributeError:
  667. pass
  668. return module
  669. def module_from_spec(spec):
  670. """Create a module based on the provided spec."""
  671. # Typically loaders will not implement create_module().
  672. module = None
  673. if hasattr(spec.loader, 'create_module'):
  674. # If create_module() returns `None` then it means default
  675. # module creation should be used.
  676. module = spec.loader.create_module(spec)
  677. elif hasattr(spec.loader, 'exec_module'):
  678. raise ImportError('loaders that define exec_module() '
  679. 'must also define create_module()')
  680. if module is None:
  681. module = _new_module(spec.name)
  682. _init_module_attrs(spec, module)
  683. return module
  684. def _module_repr_from_spec(spec):
  685. """Return the repr to use for the module."""
  686. name = '?' if spec.name is None else spec.name
  687. if spec.origin is None:
  688. loader = spec.loader
  689. if loader is None:
  690. return f'<module {name!r}>'
  691. elif (
  692. _bootstrap_external is not None
  693. and isinstance(loader, _bootstrap_external.NamespaceLoader)
  694. ):
  695. return f'<module {name!r} (namespace) from {list(loader._path)}>'
  696. else:
  697. return f'<module {name!r} ({loader!r})>'
  698. else:
  699. if spec.has_location:
  700. return f'<module {name!r} from {spec.origin!r}>'
  701. else:
  702. return f'<module {spec.name!r} ({spec.origin})>'
  703. # Used by importlib.reload() and _load_module_shim().
  704. def _exec(spec, module):
  705. """Execute the spec's specified module in an existing module's namespace."""
  706. name = spec.name
  707. with _ModuleLockManager(name):
  708. if sys.modules.get(name) is not module:
  709. msg = f'module {name!r} not in sys.modules'
  710. raise ImportError(msg, name=name)
  711. try:
  712. if spec.loader is None:
  713. if spec.submodule_search_locations is None:
  714. raise ImportError('missing loader', name=spec.name)
  715. # Namespace package.
  716. _init_module_attrs(spec, module, override=True)
  717. else:
  718. _init_module_attrs(spec, module, override=True)
  719. if not hasattr(spec.loader, 'exec_module'):
  720. msg = (f"{_object_name(spec.loader)}.exec_module() not found; "
  721. "falling back to load_module()")
  722. _warnings.warn(msg, ImportWarning)
  723. spec.loader.load_module(name)
  724. else:
  725. spec.loader.exec_module(module)
  726. finally:
  727. # Update the order of insertion into sys.modules for module
  728. # clean-up at shutdown.
  729. module = sys.modules.pop(spec.name)
  730. sys.modules[spec.name] = module
  731. return module
  732. def _load_backward_compatible(spec):
  733. # It is assumed that all callers have been warned about using load_module()
  734. # appropriately before calling this function.
  735. try:
  736. spec.loader.load_module(spec.name)
  737. except:
  738. if spec.name in sys.modules:
  739. module = sys.modules.pop(spec.name)
  740. sys.modules[spec.name] = module
  741. raise
  742. # The module must be in sys.modules at this point!
  743. # Move it to the end of sys.modules.
  744. module = sys.modules.pop(spec.name)
  745. sys.modules[spec.name] = module
  746. if getattr(module, '__loader__', None) is None:
  747. try:
  748. module.__loader__ = spec.loader
  749. except AttributeError:
  750. pass
  751. if getattr(module, '__package__', None) is None:
  752. try:
  753. # Since module.__path__ may not line up with
  754. # spec.submodule_search_paths, we can't necessarily rely
  755. # on spec.parent here.
  756. module.__package__ = module.__name__
  757. if not hasattr(module, '__path__'):
  758. module.__package__ = spec.name.rpartition('.')[0]
  759. except AttributeError:
  760. pass
  761. if getattr(module, '__spec__', None) is None:
  762. try:
  763. module.__spec__ = spec
  764. except AttributeError:
  765. pass
  766. return module
  767. def _load_unlocked(spec):
  768. # A helper for direct use by the import system.
  769. if spec.loader is not None:
  770. # Not a namespace package.
  771. if not hasattr(spec.loader, 'exec_module'):
  772. msg = (f"{_object_name(spec.loader)}.exec_module() not found; "
  773. "falling back to load_module()")
  774. _warnings.warn(msg, ImportWarning)
  775. return _load_backward_compatible(spec)
  776. module = module_from_spec(spec)
  777. # This must be done before putting the module in sys.modules
  778. # (otherwise an optimization shortcut in import.c becomes
  779. # wrong).
  780. spec._initializing = True
  781. try:
  782. sys.modules[spec.name] = module
  783. try:
  784. if spec.loader is None:
  785. if spec.submodule_search_locations is None:
  786. raise ImportError('missing loader', name=spec.name)
  787. # A namespace package so do nothing.
  788. else:
  789. spec.loader.exec_module(module)
  790. except:
  791. try:
  792. del sys.modules[spec.name]
  793. except KeyError:
  794. pass
  795. raise
  796. # Move the module to the end of sys.modules.
  797. # We don't ensure that the import-related module attributes get
  798. # set in the sys.modules replacement case. Such modules are on
  799. # their own.
  800. module = sys.modules.pop(spec.name)
  801. sys.modules[spec.name] = module
  802. _verbose_message('import {!r} # {!r}', spec.name, spec.loader)
  803. finally:
  804. spec._initializing = False
  805. return module
  806. # A method used during testing of _load_unlocked() and by
  807. # _load_module_shim().
  808. def _load(spec):
  809. """Return a new module object, loaded by the spec's loader.
  810. The module is not added to its parent.
  811. If a module is already in sys.modules, that existing module gets
  812. clobbered.
  813. """
  814. with _ModuleLockManager(spec.name):
  815. return _load_unlocked(spec)
  816. # Loaders #####################################################################
  817. class BuiltinImporter:
  818. """Meta path import for built-in modules.
  819. All methods are either class or static methods to avoid the need to
  820. instantiate the class.
  821. """
  822. _ORIGIN = "built-in"
  823. @classmethod
  824. def find_spec(cls, fullname, path=None, target=None):
  825. if _imp.is_builtin(fullname):
  826. return spec_from_loader(fullname, cls, origin=cls._ORIGIN)
  827. else:
  828. return None
  829. @staticmethod
  830. def create_module(spec):
  831. """Create a built-in module"""
  832. if spec.name not in sys.builtin_module_names:
  833. raise ImportError(f'{spec.name!r} is not a built-in module',
  834. name=spec.name)
  835. return _call_with_frames_removed(_imp.create_builtin, spec)
  836. @staticmethod
  837. def exec_module(module):
  838. """Exec a built-in module"""
  839. _call_with_frames_removed(_imp.exec_builtin, module)
  840. @classmethod
  841. @_requires_builtin
  842. def get_code(cls, fullname):
  843. """Return None as built-in modules do not have code objects."""
  844. return None
  845. @classmethod
  846. @_requires_builtin
  847. def get_source(cls, fullname):
  848. """Return None as built-in modules do not have source code."""
  849. return None
  850. @classmethod
  851. @_requires_builtin
  852. def is_package(cls, fullname):
  853. """Return False as built-in modules are never packages."""
  854. return False
  855. load_module = classmethod(_load_module_shim)
  856. class FrozenImporter:
  857. """Meta path import for frozen modules.
  858. All methods are either class or static methods to avoid the need to
  859. instantiate the class.
  860. """
  861. _ORIGIN = "frozen"
  862. @classmethod
  863. def _fix_up_module(cls, module):
  864. spec = module.__spec__
  865. state = spec.loader_state
  866. if state is None:
  867. # The module is missing FrozenImporter-specific values.
  868. # Fix up the spec attrs.
  869. origname = vars(module).pop('__origname__', None)
  870. assert origname, 'see PyImport_ImportFrozenModuleObject()'
  871. ispkg = hasattr(module, '__path__')
  872. assert _imp.is_frozen_package(module.__name__) == ispkg, ispkg
  873. filename, pkgdir = cls._resolve_filename(origname, spec.name, ispkg)
  874. spec.loader_state = type(sys.implementation)(
  875. filename=filename,
  876. origname=origname,
  877. )
  878. __path__ = spec.submodule_search_locations
  879. if ispkg:
  880. assert __path__ == [], __path__
  881. if pkgdir:
  882. spec.submodule_search_locations.insert(0, pkgdir)
  883. else:
  884. assert __path__ is None, __path__
  885. # Fix up the module attrs (the bare minimum).
  886. assert not hasattr(module, '__file__'), module.__file__
  887. if filename:
  888. try:
  889. module.__file__ = filename
  890. except AttributeError:
  891. pass
  892. if ispkg:
  893. if module.__path__ != __path__:
  894. assert module.__path__ == [], module.__path__
  895. module.__path__.extend(__path__)
  896. else:
  897. # These checks ensure that _fix_up_module() is only called
  898. # in the right places.
  899. __path__ = spec.submodule_search_locations
  900. ispkg = __path__ is not None
  901. # Check the loader state.
  902. assert sorted(vars(state)) == ['filename', 'origname'], state
  903. if state.origname:
  904. # The only frozen modules with "origname" set are stdlib modules.
  905. (__file__, pkgdir,
  906. ) = cls._resolve_filename(state.origname, spec.name, ispkg)
  907. assert state.filename == __file__, (state.filename, __file__)
  908. if pkgdir:
  909. assert __path__ == [pkgdir], (__path__, pkgdir)
  910. else:
  911. assert __path__ == ([] if ispkg else None), __path__
  912. else:
  913. __file__ = None
  914. assert state.filename is None, state.filename
  915. assert __path__ == ([] if ispkg else None), __path__
  916. # Check the file attrs.
  917. if __file__:
  918. assert hasattr(module, '__file__')
  919. assert module.__file__ == __file__, (module.__file__, __file__)
  920. else:
  921. assert not hasattr(module, '__file__'), module.__file__
  922. if ispkg:
  923. assert hasattr(module, '__path__')
  924. assert module.__path__ == __path__, (module.__path__, __path__)
  925. else:
  926. assert not hasattr(module, '__path__'), module.__path__
  927. assert not spec.has_location
  928. @classmethod
  929. def _resolve_filename(cls, fullname, alias=None, ispkg=False):
  930. if not fullname or not getattr(sys, '_stdlib_dir', None):
  931. return None, None
  932. try:
  933. sep = cls._SEP
  934. except AttributeError:
  935. sep = cls._SEP = '\\' if sys.platform == 'win32' else '/'
  936. if fullname != alias:
  937. if fullname.startswith('<'):
  938. fullname = fullname[1:]
  939. if not ispkg:
  940. fullname = f'{fullname}.__init__'
  941. else:
  942. ispkg = False
  943. relfile = fullname.replace('.', sep)
  944. if ispkg:
  945. pkgdir = f'{sys._stdlib_dir}{sep}{relfile}'
  946. filename = f'{pkgdir}{sep}__init__.py'
  947. else:
  948. pkgdir = None
  949. filename = f'{sys._stdlib_dir}{sep}{relfile}.py'
  950. return filename, pkgdir
  951. @classmethod
  952. def find_spec(cls, fullname, path=None, target=None):
  953. info = _call_with_frames_removed(_imp.find_frozen, fullname)
  954. if info is None:
  955. return None
  956. # We get the marshaled data in exec_module() (the loader
  957. # part of the importer), instead of here (the finder part).
  958. # The loader is the usual place to get the data that will
  959. # be loaded into the module. (For example, see _LoaderBasics
  960. # in _bootstra_external.py.) Most importantly, this importer
  961. # is simpler if we wait to get the data.
  962. # However, getting as much data in the finder as possible
  963. # to later load the module is okay, and sometimes important.
  964. # (That's why ModuleSpec.loader_state exists.) This is
  965. # especially true if it avoids throwing away expensive data
  966. # the loader would otherwise duplicate later and can be done
  967. # efficiently. In this case it isn't worth it.
  968. _, ispkg, origname = info
  969. spec = spec_from_loader(fullname, cls,
  970. origin=cls._ORIGIN,
  971. is_package=ispkg)
  972. filename, pkgdir = cls._resolve_filename(origname, fullname, ispkg)
  973. spec.loader_state = type(sys.implementation)(
  974. filename=filename,
  975. origname=origname,
  976. )
  977. if pkgdir:
  978. spec.submodule_search_locations.insert(0, pkgdir)
  979. return spec
  980. @staticmethod
  981. def create_module(spec):
  982. """Set __file__, if able."""
  983. module = _new_module(spec.name)
  984. try:
  985. filename = spec.loader_state.filename
  986. except AttributeError:
  987. pass
  988. else:
  989. if filename:
  990. module.__file__ = filename
  991. return module
  992. @staticmethod
  993. def exec_module(module):
  994. spec = module.__spec__
  995. name = spec.name
  996. code = _call_with_frames_removed(_imp.get_frozen_object, name)
  997. exec(code, module.__dict__)
  998. @classmethod
  999. def load_module(cls, fullname):
  1000. """Load a frozen module.
  1001. This method is deprecated. Use exec_module() instead.
  1002. """
  1003. # Warning about deprecation implemented in _load_module_shim().
  1004. module = _load_module_shim(cls, fullname)
  1005. info = _imp.find_frozen(fullname)
  1006. assert info is not None
  1007. _, ispkg, origname = info
  1008. module.__origname__ = origname
  1009. vars(module).pop('__file__', None)
  1010. if ispkg:
  1011. module.__path__ = []
  1012. cls._fix_up_module(module)
  1013. return module
  1014. @classmethod
  1015. @_requires_frozen
  1016. def get_code(cls, fullname):
  1017. """Return the code object for the frozen module."""
  1018. return _imp.get_frozen_object(fullname)
  1019. @classmethod
  1020. @_requires_frozen
  1021. def get_source(cls, fullname):
  1022. """Return None as frozen modules do not have source code."""
  1023. return None
  1024. @classmethod
  1025. @_requires_frozen
  1026. def is_package(cls, fullname):
  1027. """Return True if the frozen module is a package."""
  1028. return _imp.is_frozen_package(fullname)
  1029. # Import itself ###############################################################
  1030. class _ImportLockContext:
  1031. """Context manager for the import lock."""
  1032. def __enter__(self):
  1033. """Acquire the import lock."""
  1034. _imp.acquire_lock()
  1035. def __exit__(self, exc_type, exc_value, exc_traceback):
  1036. """Release the import lock regardless of any raised exceptions."""
  1037. _imp.release_lock()
  1038. def _resolve_name(name, package, level):
  1039. """Resolve a relative module name to an absolute one."""
  1040. bits = package.rsplit('.', level - 1)
  1041. if len(bits) < level:
  1042. raise ImportError('attempted relative import beyond top-level package')
  1043. base = bits[0]
  1044. return f'{base}.{name}' if name else base
  1045. def _find_spec(name, path, target=None):
  1046. """Find a module's spec."""
  1047. meta_path = sys.meta_path
  1048. if meta_path is None:
  1049. # PyImport_Cleanup() is running or has been called.
  1050. raise ImportError("sys.meta_path is None, Python is likely "
  1051. "shutting down")
  1052. if not meta_path:
  1053. _warnings.warn('sys.meta_path is empty', ImportWarning)
  1054. # We check sys.modules here for the reload case. While a passed-in
  1055. # target will usually indicate a reload there is no guarantee, whereas
  1056. # sys.modules provides one.
  1057. is_reload = name in sys.modules
  1058. for finder in meta_path:
  1059. with _ImportLockContext():
  1060. try:
  1061. find_spec = finder.find_spec
  1062. except AttributeError:
  1063. continue
  1064. else:
  1065. spec = find_spec(name, path, target)
  1066. if spec is not None:
  1067. # The parent import may have already imported this module.
  1068. if not is_reload and name in sys.modules:
  1069. module = sys.modules[name]
  1070. try:
  1071. __spec__ = module.__spec__
  1072. except AttributeError:
  1073. # We use the found spec since that is the one that
  1074. # we would have used if the parent module hadn't
  1075. # beaten us to the punch.
  1076. return spec
  1077. else:
  1078. if __spec__ is None:
  1079. return spec
  1080. else:
  1081. return __spec__
  1082. else:
  1083. return spec
  1084. else:
  1085. return None
  1086. def _sanity_check(name, package, level):
  1087. """Verify arguments are "sane"."""
  1088. if not isinstance(name, str):
  1089. raise TypeError(f'module name must be str, not {type(name)}')
  1090. if level < 0:
  1091. raise ValueError('level must be >= 0')
  1092. if level > 0:
  1093. if not isinstance(package, str):
  1094. raise TypeError('__package__ not set to a string')
  1095. elif not package:
  1096. raise ImportError('attempted relative import with no known parent '
  1097. 'package')
  1098. if not name and level == 0:
  1099. raise ValueError('Empty module name')
  1100. _ERR_MSG_PREFIX = 'No module named '
  1101. _ERR_MSG = _ERR_MSG_PREFIX + '{!r}'
  1102. def _find_and_load_unlocked(name, import_):
  1103. path = None
  1104. parent = name.rpartition('.')[0]
  1105. parent_spec = None
  1106. if parent:
  1107. if parent not in sys.modules:
  1108. _call_with_frames_removed(import_, parent)
  1109. # Crazy side-effects!
  1110. if name in sys.modules:
  1111. return sys.modules[name]
  1112. parent_module = sys.modules[parent]
  1113. try:
  1114. path = parent_module.__path__
  1115. except AttributeError:
  1116. msg = f'{_ERR_MSG_PREFIX}{name!r}; {parent!r} is not a package'
  1117. raise ModuleNotFoundError(msg, name=name) from None
  1118. parent_spec = parent_module.__spec__
  1119. child = name.rpartition('.')[2]
  1120. spec = _find_spec(name, path)
  1121. if spec is None:
  1122. raise ModuleNotFoundError(f'{_ERR_MSG_PREFIX}{name!r}', name=name)
  1123. else:
  1124. if parent_spec:
  1125. # Temporarily add child we are currently importing to parent's
  1126. # _uninitialized_submodules for circular import tracking.
  1127. parent_spec._uninitialized_submodules.append(child)
  1128. try:
  1129. module = _load_unlocked(spec)
  1130. finally:
  1131. if parent_spec:
  1132. parent_spec._uninitialized_submodules.pop()
  1133. if parent:
  1134. # Set the module as an attribute on its parent.
  1135. parent_module = sys.modules[parent]
  1136. try:
  1137. setattr(parent_module, child, module)
  1138. except AttributeError:
  1139. msg = f"Cannot set an attribute on {parent!r} for child module {child!r}"
  1140. _warnings.warn(msg, ImportWarning)
  1141. return module
  1142. _NEEDS_LOADING = object()
  1143. def _find_and_load(name, import_):
  1144. """Find and load the module."""
  1145. # Optimization: we avoid unneeded module locking if the module
  1146. # already exists in sys.modules and is fully initialized.
  1147. module = sys.modules.get(name, _NEEDS_LOADING)
  1148. if (module is _NEEDS_LOADING or
  1149. getattr(getattr(module, "__spec__", None), "_initializing", False)):
  1150. with _ModuleLockManager(name):
  1151. module = sys.modules.get(name, _NEEDS_LOADING)
  1152. if module is _NEEDS_LOADING:
  1153. return _find_and_load_unlocked(name, import_)
  1154. # Optimization: only call _bootstrap._lock_unlock_module() if
  1155. # module.__spec__._initializing is True.
  1156. # NOTE: because of this, initializing must be set *before*
  1157. # putting the new module in sys.modules.
  1158. _lock_unlock_module(name)
  1159. if module is None:
  1160. message = f'import of {name} halted; None in sys.modules'
  1161. raise ModuleNotFoundError(message, name=name)
  1162. return module
  1163. def _gcd_import(name, package=None, level=0):
  1164. """Import and return the module based on its name, the package the call is
  1165. being made from, and the level adjustment.
  1166. This function represents the greatest common denominator of functionality
  1167. between import_module and __import__. This includes setting __package__ if
  1168. the loader did not.
  1169. """
  1170. _sanity_check(name, package, level)
  1171. if level > 0:
  1172. name = _resolve_name(name, package, level)
  1173. return _find_and_load(name, _gcd_import)
  1174. def _handle_fromlist(module, fromlist, import_, *, recursive=False):
  1175. """Figure out what __import__ should return.
  1176. The import_ parameter is a callable which takes the name of module to
  1177. import. It is required to decouple the function from assuming importlib's
  1178. import implementation is desired.
  1179. """
  1180. # The hell that is fromlist ...
  1181. # If a package was imported, try to import stuff from fromlist.
  1182. for x in fromlist:
  1183. if not isinstance(x, str):
  1184. if recursive:
  1185. where = module.__name__ + '.__all__'
  1186. else:
  1187. where = "``from list''"
  1188. raise TypeError(f"Item in {where} must be str, "
  1189. f"not {type(x).__name__}")
  1190. elif x == '*':
  1191. if not recursive and hasattr(module, '__all__'):
  1192. _handle_fromlist(module, module.__all__, import_,
  1193. recursive=True)
  1194. elif not hasattr(module, x):
  1195. from_name = f'{module.__name__}.{x}'
  1196. try:
  1197. _call_with_frames_removed(import_, from_name)
  1198. except ModuleNotFoundError as exc:
  1199. # Backwards-compatibility dictates we ignore failed
  1200. # imports triggered by fromlist for modules that don't
  1201. # exist.
  1202. if (exc.name == from_name and
  1203. sys.modules.get(from_name, _NEEDS_LOADING) is not None):
  1204. continue
  1205. raise
  1206. return module
  1207. def _calc___package__(globals):
  1208. """Calculate what __package__ should be.
  1209. __package__ is not guaranteed to be defined or could be set to None
  1210. to represent that its proper value is unknown.
  1211. """
  1212. package = globals.get('__package__')
  1213. spec = globals.get('__spec__')
  1214. if package is not None:
  1215. if spec is not None and package != spec.parent:
  1216. _warnings.warn("__package__ != __spec__.parent "
  1217. f"({package!r} != {spec.parent!r})",
  1218. DeprecationWarning, stacklevel=3)
  1219. return package
  1220. elif spec is not None:
  1221. return spec.parent
  1222. else:
  1223. _warnings.warn("can't resolve package from __spec__ or __package__, "
  1224. "falling back on __name__ and __path__",
  1225. ImportWarning, stacklevel=3)
  1226. package = globals['__name__']
  1227. if '__path__' not in globals:
  1228. package = package.rpartition('.')[0]
  1229. return package
  1230. def __import__(name, globals=None, locals=None, fromlist=(), level=0):
  1231. """Import a module.
  1232. The 'globals' argument is used to infer where the import is occurring from
  1233. to handle relative imports. The 'locals' argument is ignored. The
  1234. 'fromlist' argument specifies what should exist as attributes on the module
  1235. being imported (e.g. ``from module import <fromlist>``). The 'level'
  1236. argument represents the package location to import from in a relative
  1237. import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
  1238. """
  1239. if level == 0:
  1240. module = _gcd_import(name)
  1241. else:
  1242. globals_ = globals if globals is not None else {}
  1243. package = _calc___package__(globals_)
  1244. module = _gcd_import(name, package, level)
  1245. if not fromlist:
  1246. # Return up to the first dot in 'name'. This is complicated by the fact
  1247. # that 'name' may be relative.
  1248. if level == 0:
  1249. return _gcd_import(name.partition('.')[0])
  1250. elif not name:
  1251. return module
  1252. else:
  1253. # Figure out where to slice the module's name up to the first dot
  1254. # in 'name'.
  1255. cut_off = len(name) - len(name.partition('.')[0])
  1256. # Slice end needs to be positive to alleviate need to special-case
  1257. # when ``'.' not in name``.
  1258. return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  1259. elif hasattr(module, '__path__'):
  1260. return _handle_fromlist(module, fromlist, _gcd_import)
  1261. else:
  1262. return module
  1263. def _builtin_from_name(name):
  1264. spec = BuiltinImporter.find_spec(name)
  1265. if spec is None:
  1266. raise ImportError('no built-in module named ' + name)
  1267. return _load_unlocked(spec)
  1268. def _setup(sys_module, _imp_module):
  1269. """Setup importlib by importing needed built-in modules and injecting them
  1270. into the global namespace.
  1271. As sys is needed for sys.modules access and _imp is needed to load built-in
  1272. modules, those two modules must be explicitly passed in.
  1273. """
  1274. global _imp, sys, _blocking_on
  1275. _imp = _imp_module
  1276. sys = sys_module
  1277. # Set up the spec for existing builtin/frozen modules.
  1278. module_type = type(sys)
  1279. for name, module in sys.modules.items():
  1280. if isinstance(module, module_type):
  1281. if name in sys.builtin_module_names:
  1282. loader = BuiltinImporter
  1283. elif _imp.is_frozen(name):
  1284. loader = FrozenImporter
  1285. else:
  1286. continue
  1287. spec = _spec_from_module(module, loader)
  1288. _init_module_attrs(spec, module)
  1289. if loader is FrozenImporter:
  1290. loader._fix_up_module(module)
  1291. # Directly load built-in modules needed during bootstrap.
  1292. self_module = sys.modules[__name__]
  1293. for builtin_name in ('_thread', '_warnings', '_weakref'):
  1294. if builtin_name not in sys.modules:
  1295. builtin_module = _builtin_from_name(builtin_name)
  1296. else:
  1297. builtin_module = sys.modules[builtin_name]
  1298. setattr(self_module, builtin_name, builtin_module)
  1299. # Instantiation requires _weakref to have been set.
  1300. _blocking_on = _WeakValueDictionary()
  1301. def _install(sys_module, _imp_module):
  1302. """Install importers for builtin and frozen modules"""
  1303. _setup(sys_module, _imp_module)
  1304. sys.meta_path.append(BuiltinImporter)
  1305. sys.meta_path.append(FrozenImporter)
  1306. def _install_external_importers():
  1307. """Install importers that require external filesystem access"""
  1308. global _bootstrap_external
  1309. import _frozen_importlib_external
  1310. _bootstrap_external = _frozen_importlib_external
  1311. _frozen_importlib_external._install(sys.modules[__name__])