_bootstrap.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  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. if spec.loader is None:
  689. return f'<module {name!r}>'
  690. else:
  691. return f'<module {name!r} (namespace) from {list(spec.loader._path)}>'
  692. else:
  693. if spec.has_location:
  694. return f'<module {name!r} from {spec.origin!r}>'
  695. else:
  696. return f'<module {spec.name!r} ({spec.origin})>'
  697. # Used by importlib.reload() and _load_module_shim().
  698. def _exec(spec, module):
  699. """Execute the spec's specified module in an existing module's namespace."""
  700. name = spec.name
  701. with _ModuleLockManager(name):
  702. if sys.modules.get(name) is not module:
  703. msg = f'module {name!r} not in sys.modules'
  704. raise ImportError(msg, name=name)
  705. try:
  706. if spec.loader is None:
  707. if spec.submodule_search_locations is None:
  708. raise ImportError('missing loader', name=spec.name)
  709. # Namespace package.
  710. _init_module_attrs(spec, module, override=True)
  711. else:
  712. _init_module_attrs(spec, module, override=True)
  713. if not hasattr(spec.loader, 'exec_module'):
  714. msg = (f"{_object_name(spec.loader)}.exec_module() not found; "
  715. "falling back to load_module()")
  716. _warnings.warn(msg, ImportWarning)
  717. spec.loader.load_module(name)
  718. else:
  719. spec.loader.exec_module(module)
  720. finally:
  721. # Update the order of insertion into sys.modules for module
  722. # clean-up at shutdown.
  723. module = sys.modules.pop(spec.name)
  724. sys.modules[spec.name] = module
  725. return module
  726. def _load_backward_compatible(spec):
  727. # It is assumed that all callers have been warned about using load_module()
  728. # appropriately before calling this function.
  729. try:
  730. spec.loader.load_module(spec.name)
  731. except:
  732. if spec.name in sys.modules:
  733. module = sys.modules.pop(spec.name)
  734. sys.modules[spec.name] = module
  735. raise
  736. # The module must be in sys.modules at this point!
  737. # Move it to the end of sys.modules.
  738. module = sys.modules.pop(spec.name)
  739. sys.modules[spec.name] = module
  740. if getattr(module, '__loader__', None) is None:
  741. try:
  742. module.__loader__ = spec.loader
  743. except AttributeError:
  744. pass
  745. if getattr(module, '__package__', None) is None:
  746. try:
  747. # Since module.__path__ may not line up with
  748. # spec.submodule_search_paths, we can't necessarily rely
  749. # on spec.parent here.
  750. module.__package__ = module.__name__
  751. if not hasattr(module, '__path__'):
  752. module.__package__ = spec.name.rpartition('.')[0]
  753. except AttributeError:
  754. pass
  755. if getattr(module, '__spec__', None) is None:
  756. try:
  757. module.__spec__ = spec
  758. except AttributeError:
  759. pass
  760. return module
  761. def _load_unlocked(spec):
  762. # A helper for direct use by the import system.
  763. if spec.loader is not None:
  764. # Not a namespace package.
  765. if not hasattr(spec.loader, 'exec_module'):
  766. msg = (f"{_object_name(spec.loader)}.exec_module() not found; "
  767. "falling back to load_module()")
  768. _warnings.warn(msg, ImportWarning)
  769. return _load_backward_compatible(spec)
  770. module = module_from_spec(spec)
  771. # This must be done before putting the module in sys.modules
  772. # (otherwise an optimization shortcut in import.c becomes
  773. # wrong).
  774. spec._initializing = True
  775. try:
  776. sys.modules[spec.name] = module
  777. try:
  778. if spec.loader is None:
  779. if spec.submodule_search_locations is None:
  780. raise ImportError('missing loader', name=spec.name)
  781. # A namespace package so do nothing.
  782. else:
  783. spec.loader.exec_module(module)
  784. except:
  785. try:
  786. del sys.modules[spec.name]
  787. except KeyError:
  788. pass
  789. raise
  790. # Move the module to the end of sys.modules.
  791. # We don't ensure that the import-related module attributes get
  792. # set in the sys.modules replacement case. Such modules are on
  793. # their own.
  794. module = sys.modules.pop(spec.name)
  795. sys.modules[spec.name] = module
  796. _verbose_message('import {!r} # {!r}', spec.name, spec.loader)
  797. finally:
  798. spec._initializing = False
  799. return module
  800. # A method used during testing of _load_unlocked() and by
  801. # _load_module_shim().
  802. def _load(spec):
  803. """Return a new module object, loaded by the spec's loader.
  804. The module is not added to its parent.
  805. If a module is already in sys.modules, that existing module gets
  806. clobbered.
  807. """
  808. with _ModuleLockManager(spec.name):
  809. return _load_unlocked(spec)
  810. # Loaders #####################################################################
  811. class BuiltinImporter:
  812. """Meta path import for built-in modules.
  813. All methods are either class or static methods to avoid the need to
  814. instantiate the class.
  815. """
  816. _ORIGIN = "built-in"
  817. @classmethod
  818. def find_spec(cls, fullname, path=None, target=None):
  819. if _imp.is_builtin(fullname):
  820. return spec_from_loader(fullname, cls, origin=cls._ORIGIN)
  821. else:
  822. return None
  823. @staticmethod
  824. def create_module(spec):
  825. """Create a built-in module"""
  826. if spec.name not in sys.builtin_module_names:
  827. raise ImportError(f'{spec.name!r} is not a built-in module',
  828. name=spec.name)
  829. return _call_with_frames_removed(_imp.create_builtin, spec)
  830. @staticmethod
  831. def exec_module(module):
  832. """Exec a built-in module"""
  833. _call_with_frames_removed(_imp.exec_builtin, module)
  834. @classmethod
  835. @_requires_builtin
  836. def get_code(cls, fullname):
  837. """Return None as built-in modules do not have code objects."""
  838. return None
  839. @classmethod
  840. @_requires_builtin
  841. def get_source(cls, fullname):
  842. """Return None as built-in modules do not have source code."""
  843. return None
  844. @classmethod
  845. @_requires_builtin
  846. def is_package(cls, fullname):
  847. """Return False as built-in modules are never packages."""
  848. return False
  849. load_module = classmethod(_load_module_shim)
  850. class FrozenImporter:
  851. """Meta path import for frozen modules.
  852. All methods are either class or static methods to avoid the need to
  853. instantiate the class.
  854. """
  855. _ORIGIN = "frozen"
  856. @classmethod
  857. def _fix_up_module(cls, module):
  858. spec = module.__spec__
  859. state = spec.loader_state
  860. if state is None:
  861. # The module is missing FrozenImporter-specific values.
  862. # Fix up the spec attrs.
  863. origname = vars(module).pop('__origname__', None)
  864. assert origname, 'see PyImport_ImportFrozenModuleObject()'
  865. ispkg = hasattr(module, '__path__')
  866. assert _imp.is_frozen_package(module.__name__) == ispkg, ispkg
  867. filename, pkgdir = cls._resolve_filename(origname, spec.name, ispkg)
  868. spec.loader_state = type(sys.implementation)(
  869. filename=filename,
  870. origname=origname,
  871. )
  872. __path__ = spec.submodule_search_locations
  873. if ispkg:
  874. assert __path__ == [], __path__
  875. if pkgdir:
  876. spec.submodule_search_locations.insert(0, pkgdir)
  877. else:
  878. assert __path__ is None, __path__
  879. # Fix up the module attrs (the bare minimum).
  880. assert not hasattr(module, '__file__'), module.__file__
  881. if filename:
  882. try:
  883. module.__file__ = filename
  884. except AttributeError:
  885. pass
  886. if ispkg:
  887. if module.__path__ != __path__:
  888. assert module.__path__ == [], module.__path__
  889. module.__path__.extend(__path__)
  890. else:
  891. # These checks ensure that _fix_up_module() is only called
  892. # in the right places.
  893. __path__ = spec.submodule_search_locations
  894. ispkg = __path__ is not None
  895. # Check the loader state.
  896. assert sorted(vars(state)) == ['filename', 'origname'], state
  897. if state.origname:
  898. # The only frozen modules with "origname" set are stdlib modules.
  899. (__file__, pkgdir,
  900. ) = cls._resolve_filename(state.origname, spec.name, ispkg)
  901. assert state.filename == __file__, (state.filename, __file__)
  902. if pkgdir:
  903. assert __path__ == [pkgdir], (__path__, pkgdir)
  904. else:
  905. assert __path__ == ([] if ispkg else None), __path__
  906. else:
  907. __file__ = None
  908. assert state.filename is None, state.filename
  909. assert __path__ == ([] if ispkg else None), __path__
  910. # Check the file attrs.
  911. if __file__:
  912. assert hasattr(module, '__file__')
  913. assert module.__file__ == __file__, (module.__file__, __file__)
  914. else:
  915. assert not hasattr(module, '__file__'), module.__file__
  916. if ispkg:
  917. assert hasattr(module, '__path__')
  918. assert module.__path__ == __path__, (module.__path__, __path__)
  919. else:
  920. assert not hasattr(module, '__path__'), module.__path__
  921. assert not spec.has_location
  922. @classmethod
  923. def _resolve_filename(cls, fullname, alias=None, ispkg=False):
  924. if not fullname or not getattr(sys, '_stdlib_dir', None):
  925. return None, None
  926. try:
  927. sep = cls._SEP
  928. except AttributeError:
  929. sep = cls._SEP = '\\' if sys.platform == 'win32' else '/'
  930. if fullname != alias:
  931. if fullname.startswith('<'):
  932. fullname = fullname[1:]
  933. if not ispkg:
  934. fullname = f'{fullname}.__init__'
  935. else:
  936. ispkg = False
  937. relfile = fullname.replace('.', sep)
  938. if ispkg:
  939. pkgdir = f'{sys._stdlib_dir}{sep}{relfile}'
  940. filename = f'{pkgdir}{sep}__init__.py'
  941. else:
  942. pkgdir = None
  943. filename = f'{sys._stdlib_dir}{sep}{relfile}.py'
  944. return filename, pkgdir
  945. @classmethod
  946. def find_spec(cls, fullname, path=None, target=None):
  947. info = _call_with_frames_removed(_imp.find_frozen, fullname)
  948. if info is None:
  949. return None
  950. # We get the marshaled data in exec_module() (the loader
  951. # part of the importer), instead of here (the finder part).
  952. # The loader is the usual place to get the data that will
  953. # be loaded into the module. (For example, see _LoaderBasics
  954. # in _bootstra_external.py.) Most importantly, this importer
  955. # is simpler if we wait to get the data.
  956. # However, getting as much data in the finder as possible
  957. # to later load the module is okay, and sometimes important.
  958. # (That's why ModuleSpec.loader_state exists.) This is
  959. # especially true if it avoids throwing away expensive data
  960. # the loader would otherwise duplicate later and can be done
  961. # efficiently. In this case it isn't worth it.
  962. _, ispkg, origname = info
  963. spec = spec_from_loader(fullname, cls,
  964. origin=cls._ORIGIN,
  965. is_package=ispkg)
  966. filename, pkgdir = cls._resolve_filename(origname, fullname, ispkg)
  967. spec.loader_state = type(sys.implementation)(
  968. filename=filename,
  969. origname=origname,
  970. )
  971. if pkgdir:
  972. spec.submodule_search_locations.insert(0, pkgdir)
  973. return spec
  974. @staticmethod
  975. def create_module(spec):
  976. """Set __file__, if able."""
  977. module = _new_module(spec.name)
  978. try:
  979. filename = spec.loader_state.filename
  980. except AttributeError:
  981. pass
  982. else:
  983. if filename:
  984. module.__file__ = filename
  985. return module
  986. @staticmethod
  987. def exec_module(module):
  988. spec = module.__spec__
  989. name = spec.name
  990. code = _call_with_frames_removed(_imp.get_frozen_object, name)
  991. exec(code, module.__dict__)
  992. @classmethod
  993. def load_module(cls, fullname):
  994. """Load a frozen module.
  995. This method is deprecated. Use exec_module() instead.
  996. """
  997. # Warning about deprecation implemented in _load_module_shim().
  998. module = _load_module_shim(cls, fullname)
  999. info = _imp.find_frozen(fullname)
  1000. assert info is not None
  1001. _, ispkg, origname = info
  1002. module.__origname__ = origname
  1003. vars(module).pop('__file__', None)
  1004. if ispkg:
  1005. module.__path__ = []
  1006. cls._fix_up_module(module)
  1007. return module
  1008. @classmethod
  1009. @_requires_frozen
  1010. def get_code(cls, fullname):
  1011. """Return the code object for the frozen module."""
  1012. return _imp.get_frozen_object(fullname)
  1013. @classmethod
  1014. @_requires_frozen
  1015. def get_source(cls, fullname):
  1016. """Return None as frozen modules do not have source code."""
  1017. return None
  1018. @classmethod
  1019. @_requires_frozen
  1020. def is_package(cls, fullname):
  1021. """Return True if the frozen module is a package."""
  1022. return _imp.is_frozen_package(fullname)
  1023. # Import itself ###############################################################
  1024. class _ImportLockContext:
  1025. """Context manager for the import lock."""
  1026. def __enter__(self):
  1027. """Acquire the import lock."""
  1028. _imp.acquire_lock()
  1029. def __exit__(self, exc_type, exc_value, exc_traceback):
  1030. """Release the import lock regardless of any raised exceptions."""
  1031. _imp.release_lock()
  1032. def _resolve_name(name, package, level):
  1033. """Resolve a relative module name to an absolute one."""
  1034. bits = package.rsplit('.', level - 1)
  1035. if len(bits) < level:
  1036. raise ImportError('attempted relative import beyond top-level package')
  1037. base = bits[0]
  1038. return f'{base}.{name}' if name else base
  1039. def _find_spec(name, path, target=None):
  1040. """Find a module's spec."""
  1041. meta_path = sys.meta_path
  1042. if meta_path is None:
  1043. # PyImport_Cleanup() is running or has been called.
  1044. raise ImportError("sys.meta_path is None, Python is likely "
  1045. "shutting down")
  1046. if not meta_path:
  1047. _warnings.warn('sys.meta_path is empty', ImportWarning)
  1048. # We check sys.modules here for the reload case. While a passed-in
  1049. # target will usually indicate a reload there is no guarantee, whereas
  1050. # sys.modules provides one.
  1051. is_reload = name in sys.modules
  1052. for finder in meta_path:
  1053. with _ImportLockContext():
  1054. try:
  1055. find_spec = finder.find_spec
  1056. except AttributeError:
  1057. continue
  1058. else:
  1059. spec = find_spec(name, path, target)
  1060. if spec is not None:
  1061. # The parent import may have already imported this module.
  1062. if not is_reload and name in sys.modules:
  1063. module = sys.modules[name]
  1064. try:
  1065. __spec__ = module.__spec__
  1066. except AttributeError:
  1067. # We use the found spec since that is the one that
  1068. # we would have used if the parent module hadn't
  1069. # beaten us to the punch.
  1070. return spec
  1071. else:
  1072. if __spec__ is None:
  1073. return spec
  1074. else:
  1075. return __spec__
  1076. else:
  1077. return spec
  1078. else:
  1079. return None
  1080. def _sanity_check(name, package, level):
  1081. """Verify arguments are "sane"."""
  1082. if not isinstance(name, str):
  1083. raise TypeError(f'module name must be str, not {type(name)}')
  1084. if level < 0:
  1085. raise ValueError('level must be >= 0')
  1086. if level > 0:
  1087. if not isinstance(package, str):
  1088. raise TypeError('__package__ not set to a string')
  1089. elif not package:
  1090. raise ImportError('attempted relative import with no known parent '
  1091. 'package')
  1092. if not name and level == 0:
  1093. raise ValueError('Empty module name')
  1094. _ERR_MSG_PREFIX = 'No module named '
  1095. _ERR_MSG = _ERR_MSG_PREFIX + '{!r}'
  1096. def _find_and_load_unlocked(name, import_):
  1097. path = None
  1098. parent = name.rpartition('.')[0]
  1099. parent_spec = None
  1100. if parent:
  1101. if parent not in sys.modules:
  1102. _call_with_frames_removed(import_, parent)
  1103. # Crazy side-effects!
  1104. if name in sys.modules:
  1105. return sys.modules[name]
  1106. parent_module = sys.modules[parent]
  1107. try:
  1108. path = parent_module.__path__
  1109. except AttributeError:
  1110. msg = f'{_ERR_MSG_PREFIX}{name!r}; {parent!r} is not a package'
  1111. raise ModuleNotFoundError(msg, name=name) from None
  1112. parent_spec = parent_module.__spec__
  1113. child = name.rpartition('.')[2]
  1114. spec = _find_spec(name, path)
  1115. if spec is None:
  1116. raise ModuleNotFoundError(f'{_ERR_MSG_PREFIX}{name!r}', name=name)
  1117. else:
  1118. if parent_spec:
  1119. # Temporarily add child we are currently importing to parent's
  1120. # _uninitialized_submodules for circular import tracking.
  1121. parent_spec._uninitialized_submodules.append(child)
  1122. try:
  1123. module = _load_unlocked(spec)
  1124. finally:
  1125. if parent_spec:
  1126. parent_spec._uninitialized_submodules.pop()
  1127. if parent:
  1128. # Set the module as an attribute on its parent.
  1129. parent_module = sys.modules[parent]
  1130. try:
  1131. setattr(parent_module, child, module)
  1132. except AttributeError:
  1133. msg = f"Cannot set an attribute on {parent!r} for child module {child!r}"
  1134. _warnings.warn(msg, ImportWarning)
  1135. return module
  1136. _NEEDS_LOADING = object()
  1137. def _find_and_load(name, import_):
  1138. """Find and load the module."""
  1139. # Optimization: we avoid unneeded module locking if the module
  1140. # already exists in sys.modules and is fully initialized.
  1141. module = sys.modules.get(name, _NEEDS_LOADING)
  1142. if (module is _NEEDS_LOADING or
  1143. getattr(getattr(module, "__spec__", None), "_initializing", False)):
  1144. with _ModuleLockManager(name):
  1145. module = sys.modules.get(name, _NEEDS_LOADING)
  1146. if module is _NEEDS_LOADING:
  1147. return _find_and_load_unlocked(name, import_)
  1148. # Optimization: only call _bootstrap._lock_unlock_module() if
  1149. # module.__spec__._initializing is True.
  1150. # NOTE: because of this, initializing must be set *before*
  1151. # putting the new module in sys.modules.
  1152. _lock_unlock_module(name)
  1153. if module is None:
  1154. message = f'import of {name} halted; None in sys.modules'
  1155. raise ModuleNotFoundError(message, name=name)
  1156. return module
  1157. def _gcd_import(name, package=None, level=0):
  1158. """Import and return the module based on its name, the package the call is
  1159. being made from, and the level adjustment.
  1160. This function represents the greatest common denominator of functionality
  1161. between import_module and __import__. This includes setting __package__ if
  1162. the loader did not.
  1163. """
  1164. _sanity_check(name, package, level)
  1165. if level > 0:
  1166. name = _resolve_name(name, package, level)
  1167. return _find_and_load(name, _gcd_import)
  1168. def _handle_fromlist(module, fromlist, import_, *, recursive=False):
  1169. """Figure out what __import__ should return.
  1170. The import_ parameter is a callable which takes the name of module to
  1171. import. It is required to decouple the function from assuming importlib's
  1172. import implementation is desired.
  1173. """
  1174. # The hell that is fromlist ...
  1175. # If a package was imported, try to import stuff from fromlist.
  1176. for x in fromlist:
  1177. if not isinstance(x, str):
  1178. if recursive:
  1179. where = module.__name__ + '.__all__'
  1180. else:
  1181. where = "``from list''"
  1182. raise TypeError(f"Item in {where} must be str, "
  1183. f"not {type(x).__name__}")
  1184. elif x == '*':
  1185. if not recursive and hasattr(module, '__all__'):
  1186. _handle_fromlist(module, module.__all__, import_,
  1187. recursive=True)
  1188. elif not hasattr(module, x):
  1189. from_name = f'{module.__name__}.{x}'
  1190. try:
  1191. _call_with_frames_removed(import_, from_name)
  1192. except ModuleNotFoundError as exc:
  1193. # Backwards-compatibility dictates we ignore failed
  1194. # imports triggered by fromlist for modules that don't
  1195. # exist.
  1196. if (exc.name == from_name and
  1197. sys.modules.get(from_name, _NEEDS_LOADING) is not None):
  1198. continue
  1199. raise
  1200. return module
  1201. def _calc___package__(globals):
  1202. """Calculate what __package__ should be.
  1203. __package__ is not guaranteed to be defined or could be set to None
  1204. to represent that its proper value is unknown.
  1205. """
  1206. package = globals.get('__package__')
  1207. spec = globals.get('__spec__')
  1208. if package is not None:
  1209. if spec is not None and package != spec.parent:
  1210. _warnings.warn("__package__ != __spec__.parent "
  1211. f"({package!r} != {spec.parent!r})",
  1212. DeprecationWarning, stacklevel=3)
  1213. return package
  1214. elif spec is not None:
  1215. return spec.parent
  1216. else:
  1217. _warnings.warn("can't resolve package from __spec__ or __package__, "
  1218. "falling back on __name__ and __path__",
  1219. ImportWarning, stacklevel=3)
  1220. package = globals['__name__']
  1221. if '__path__' not in globals:
  1222. package = package.rpartition('.')[0]
  1223. return package
  1224. def __import__(name, globals=None, locals=None, fromlist=(), level=0):
  1225. """Import a module.
  1226. The 'globals' argument is used to infer where the import is occurring from
  1227. to handle relative imports. The 'locals' argument is ignored. The
  1228. 'fromlist' argument specifies what should exist as attributes on the module
  1229. being imported (e.g. ``from module import <fromlist>``). The 'level'
  1230. argument represents the package location to import from in a relative
  1231. import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
  1232. """
  1233. if level == 0:
  1234. module = _gcd_import(name)
  1235. else:
  1236. globals_ = globals if globals is not None else {}
  1237. package = _calc___package__(globals_)
  1238. module = _gcd_import(name, package, level)
  1239. if not fromlist:
  1240. # Return up to the first dot in 'name'. This is complicated by the fact
  1241. # that 'name' may be relative.
  1242. if level == 0:
  1243. return _gcd_import(name.partition('.')[0])
  1244. elif not name:
  1245. return module
  1246. else:
  1247. # Figure out where to slice the module's name up to the first dot
  1248. # in 'name'.
  1249. cut_off = len(name) - len(name.partition('.')[0])
  1250. # Slice end needs to be positive to alleviate need to special-case
  1251. # when ``'.' not in name``.
  1252. return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  1253. elif hasattr(module, '__path__'):
  1254. return _handle_fromlist(module, fromlist, _gcd_import)
  1255. else:
  1256. return module
  1257. def _builtin_from_name(name):
  1258. spec = BuiltinImporter.find_spec(name)
  1259. if spec is None:
  1260. raise ImportError('no built-in module named ' + name)
  1261. return _load_unlocked(spec)
  1262. def _setup(sys_module, _imp_module):
  1263. """Setup importlib by importing needed built-in modules and injecting them
  1264. into the global namespace.
  1265. As sys is needed for sys.modules access and _imp is needed to load built-in
  1266. modules, those two modules must be explicitly passed in.
  1267. """
  1268. global _imp, sys, _blocking_on
  1269. _imp = _imp_module
  1270. sys = sys_module
  1271. # Set up the spec for existing builtin/frozen modules.
  1272. module_type = type(sys)
  1273. for name, module in sys.modules.items():
  1274. if isinstance(module, module_type):
  1275. if name in sys.builtin_module_names:
  1276. loader = BuiltinImporter
  1277. elif _imp.is_frozen(name):
  1278. loader = FrozenImporter
  1279. else:
  1280. continue
  1281. spec = _spec_from_module(module, loader)
  1282. _init_module_attrs(spec, module)
  1283. if loader is FrozenImporter:
  1284. loader._fix_up_module(module)
  1285. # Directly load built-in modules needed during bootstrap.
  1286. self_module = sys.modules[__name__]
  1287. for builtin_name in ('_thread', '_warnings', '_weakref'):
  1288. if builtin_name not in sys.modules:
  1289. builtin_module = _builtin_from_name(builtin_name)
  1290. else:
  1291. builtin_module = sys.modules[builtin_name]
  1292. setattr(self_module, builtin_name, builtin_module)
  1293. # Instantiation requires _weakref to have been set.
  1294. _blocking_on = _WeakValueDictionary()
  1295. def _install(sys_module, _imp_module):
  1296. """Install importers for builtin and frozen modules"""
  1297. _setup(sys_module, _imp_module)
  1298. sys.meta_path.append(BuiltinImporter)
  1299. sys.meta_path.append(FrozenImporter)
  1300. def _install_external_importers():
  1301. """Install importers that require external filesystem access"""
  1302. global _bootstrap_external
  1303. import _frozen_importlib_external
  1304. _bootstrap_external = _frozen_importlib_external
  1305. _frozen_importlib_external._install(sys.modules[__name__])