_bootstrap.py 37 KB

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