PageRenderTime 57ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/importlib/_bootstrap.py

https://github.com/anton-afanasyev/cpython
Python | 2439 lines | 2165 code | 57 blank | 217 comment | 63 complexity | 5db0b9ea578788ae58d6c02e42a3c464 MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD

Large files files are truncated, but you can click here to view the full file

  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. # update. 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. _CASE_INSENSITIVE_PLATFORMS = 'win', 'cygwin', 'darwin'
  20. def _make_relax_case():
  21. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  22. def _relax_case():
  23. """True if filenames must be checked case-insensitively."""
  24. return b'PYTHONCASEOK' in _os.environ
  25. else:
  26. def _relax_case():
  27. """True if filenames must be checked case-insensitively."""
  28. return False
  29. return _relax_case
  30. def _w_long(x):
  31. """Convert a 32-bit integer to little-endian."""
  32. return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
  33. def _r_long(int_bytes):
  34. """Convert 4 bytes in little-endian to an integer."""
  35. return int.from_bytes(int_bytes, 'little')
  36. def _path_join(*path_parts):
  37. """Replacement for os.path.join()."""
  38. return path_sep.join([part.rstrip(path_separators)
  39. for part in path_parts if part])
  40. def _path_split(path):
  41. """Replacement for os.path.split()."""
  42. if len(path_separators) == 1:
  43. front, _, tail = path.rpartition(path_sep)
  44. return front, tail
  45. for x in reversed(path):
  46. if x in path_separators:
  47. front, tail = path.rsplit(x, maxsplit=1)
  48. return front, tail
  49. return '', path
  50. def _path_stat(path):
  51. """Stat the path.
  52. Made a separate function to make it easier to override in experiments
  53. (e.g. cache stat results).
  54. """
  55. return _os.stat(path)
  56. def _path_is_mode_type(path, mode):
  57. """Test whether the path is the specified mode type."""
  58. try:
  59. stat_info = _path_stat(path)
  60. except OSError:
  61. return False
  62. return (stat_info.st_mode & 0o170000) == mode
  63. def _path_isfile(path):
  64. """Replacement for os.path.isfile."""
  65. return _path_is_mode_type(path, 0o100000)
  66. def _path_isdir(path):
  67. """Replacement for os.path.isdir."""
  68. if not path:
  69. path = _os.getcwd()
  70. return _path_is_mode_type(path, 0o040000)
  71. def _write_atomic(path, data, mode=0o666):
  72. """Best-effort function to write data to a path atomically.
  73. Be prepared to handle a FileExistsError if concurrent writing of the
  74. temporary file is attempted."""
  75. # id() is used to generate a pseudo-random filename.
  76. path_tmp = '{}.{}'.format(path, id(path))
  77. fd = _os.open(path_tmp,
  78. _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
  79. try:
  80. # We first write data to a temporary file, and then use os.replace() to
  81. # perform an atomic rename.
  82. with _io.FileIO(fd, 'wb') as file:
  83. file.write(data)
  84. _os.replace(path_tmp, path)
  85. except OSError:
  86. try:
  87. _os.unlink(path_tmp)
  88. except OSError:
  89. pass
  90. raise
  91. def _wrap(new, old):
  92. """Simple substitute for functools.update_wrapper."""
  93. for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
  94. if hasattr(old, replace):
  95. setattr(new, replace, getattr(old, replace))
  96. new.__dict__.update(old.__dict__)
  97. def _new_module(name):
  98. return type(sys)(name)
  99. _code_type = type(_wrap.__code__)
  100. class _ManageReload:
  101. """Manages the possible clean-up of sys.modules for load_module()."""
  102. def __init__(self, name):
  103. self._name = name
  104. def __enter__(self):
  105. self._is_reload = self._name in sys.modules
  106. def __exit__(self, *args):
  107. if any(arg is not None for arg in args) and not self._is_reload:
  108. try:
  109. del sys.modules[self._name]
  110. except KeyError:
  111. pass
  112. # Module-level locking ########################################################
  113. # A dict mapping module names to weakrefs of _ModuleLock instances
  114. _module_locks = {}
  115. # A dict mapping thread ids to _ModuleLock instances
  116. _blocking_on = {}
  117. class _DeadlockError(RuntimeError):
  118. pass
  119. class _ModuleLock:
  120. """A recursive lock implementation which is able to detect deadlocks
  121. (e.g. thread 1 trying to take locks A then B, and thread 2 trying to
  122. take locks B then A).
  123. """
  124. def __init__(self, name):
  125. self.lock = _thread.allocate_lock()
  126. self.wakeup = _thread.allocate_lock()
  127. self.name = name
  128. self.owner = None
  129. self.count = 0
  130. self.waiters = 0
  131. def has_deadlock(self):
  132. # Deadlock avoidance for concurrent circular imports.
  133. me = _thread.get_ident()
  134. tid = self.owner
  135. while True:
  136. lock = _blocking_on.get(tid)
  137. if lock is None:
  138. return False
  139. tid = lock.owner
  140. if tid == me:
  141. return True
  142. def acquire(self):
  143. """
  144. Acquire the module lock. If a potential deadlock is detected,
  145. a _DeadlockError is raised.
  146. Otherwise, the lock is always acquired and True is returned.
  147. """
  148. tid = _thread.get_ident()
  149. _blocking_on[tid] = self
  150. try:
  151. while True:
  152. with self.lock:
  153. if self.count == 0 or self.owner == tid:
  154. self.owner = tid
  155. self.count += 1
  156. return True
  157. if self.has_deadlock():
  158. raise _DeadlockError('deadlock detected by %r' % self)
  159. if self.wakeup.acquire(False):
  160. self.waiters += 1
  161. # Wait for a release() call
  162. self.wakeup.acquire()
  163. self.wakeup.release()
  164. finally:
  165. del _blocking_on[tid]
  166. def release(self):
  167. tid = _thread.get_ident()
  168. with self.lock:
  169. if self.owner != tid:
  170. raise RuntimeError('cannot release un-acquired lock')
  171. assert self.count > 0
  172. self.count -= 1
  173. if self.count == 0:
  174. self.owner = None
  175. if self.waiters:
  176. self.waiters -= 1
  177. self.wakeup.release()
  178. def __repr__(self):
  179. return '_ModuleLock({!r}) at {}'.format(self.name, id(self))
  180. class _DummyModuleLock:
  181. """A simple _ModuleLock equivalent for Python builds without
  182. multi-threading support."""
  183. def __init__(self, name):
  184. self.name = name
  185. self.count = 0
  186. def acquire(self):
  187. self.count += 1
  188. return True
  189. def release(self):
  190. if self.count == 0:
  191. raise RuntimeError('cannot release un-acquired lock')
  192. self.count -= 1
  193. def __repr__(self):
  194. return '_DummyModuleLock({!r}) at {}'.format(self.name, id(self))
  195. class _ModuleLockManager:
  196. def __init__(self, name):
  197. self._name = name
  198. self._lock = None
  199. def __enter__(self):
  200. try:
  201. self._lock = _get_module_lock(self._name)
  202. finally:
  203. _imp.release_lock()
  204. self._lock.acquire()
  205. def __exit__(self, *args, **kwargs):
  206. self._lock.release()
  207. # The following two functions are for consumption by Python/import.c.
  208. def _get_module_lock(name):
  209. """Get or create the module lock for a given module name.
  210. Should only be called with the import lock taken."""
  211. lock = None
  212. try:
  213. lock = _module_locks[name]()
  214. except KeyError:
  215. pass
  216. if lock is None:
  217. if _thread is None:
  218. lock = _DummyModuleLock(name)
  219. else:
  220. lock = _ModuleLock(name)
  221. def cb(_):
  222. del _module_locks[name]
  223. _module_locks[name] = _weakref.ref(lock, cb)
  224. return lock
  225. def _lock_unlock_module(name):
  226. """Release the global import lock, and acquires then release the
  227. module lock for a given module name.
  228. This is used to ensure a module is completely initialized, in the
  229. event it is being imported by another thread.
  230. Should only be called with the import lock taken."""
  231. lock = _get_module_lock(name)
  232. _imp.release_lock()
  233. try:
  234. lock.acquire()
  235. except _DeadlockError:
  236. # Concurrent circular import, we'll accept a partially initialized
  237. # module object.
  238. pass
  239. else:
  240. lock.release()
  241. # Frame stripping magic ###############################################
  242. def _call_with_frames_removed(f, *args, **kwds):
  243. """remove_importlib_frames in import.c will always remove sequences
  244. of importlib frames that end with a call to this function
  245. Use it instead of a normal call in places where including the importlib
  246. frames introduces unwanted noise into the traceback (e.g. when executing
  247. module code)
  248. """
  249. return f(*args, **kwds)
  250. # Finder/loader utility code ###############################################
  251. # Magic word to reject .pyc files generated by other Python versions.
  252. # It should change for each incompatible change to the bytecode.
  253. #
  254. # The value of CR and LF is incorporated so if you ever read or write
  255. # a .pyc file in text mode the magic number will be wrong; also, the
  256. # Apple MPW compiler swaps their values, botching string constants.
  257. #
  258. # The magic numbers must be spaced apart at least 2 values, as the
  259. # -U interpeter flag will cause MAGIC+1 being used. They have been
  260. # odd numbers for some time now.
  261. #
  262. # There were a variety of old schemes for setting the magic number.
  263. # The current working scheme is to increment the previous value by
  264. # 10.
  265. #
  266. # Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
  267. # number also includes a new "magic tag", i.e. a human readable string used
  268. # to represent the magic number in __pycache__ directories. When you change
  269. # the magic number, you must also set a new unique magic tag. Generally this
  270. # can be named after the Python major version of the magic number bump, but
  271. # it can really be anything, as long as it's different than anything else
  272. # that's come before. The tags are included in the following table, starting
  273. # with Python 3.2a0.
  274. #
  275. # Known values:
  276. # Python 1.5: 20121
  277. # Python 1.5.1: 20121
  278. # Python 1.5.2: 20121
  279. # Python 1.6: 50428
  280. # Python 2.0: 50823
  281. # Python 2.0.1: 50823
  282. # Python 2.1: 60202
  283. # Python 2.1.1: 60202
  284. # Python 2.1.2: 60202
  285. # Python 2.2: 60717
  286. # Python 2.3a0: 62011
  287. # Python 2.3a0: 62021
  288. # Python 2.3a0: 62011 (!)
  289. # Python 2.4a0: 62041
  290. # Python 2.4a3: 62051
  291. # Python 2.4b1: 62061
  292. # Python 2.5a0: 62071
  293. # Python 2.5a0: 62081 (ast-branch)
  294. # Python 2.5a0: 62091 (with)
  295. # Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
  296. # Python 2.5b3: 62101 (fix wrong code: for x, in ...)
  297. # Python 2.5b3: 62111 (fix wrong code: x += yield)
  298. # Python 2.5c1: 62121 (fix wrong lnotab with for loops and
  299. # storing constants that should have been removed)
  300. # Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
  301. # Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
  302. # Python 2.6a1: 62161 (WITH_CLEANUP optimization)
  303. # Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
  304. # Python 2.7a0: 62181 (optimize conditional branches:
  305. # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
  306. # Python 2.7a0 62191 (introduce SETUP_WITH)
  307. # Python 2.7a0 62201 (introduce BUILD_SET)
  308. # Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
  309. # Python 3000: 3000
  310. # 3010 (removed UNARY_CONVERT)
  311. # 3020 (added BUILD_SET)
  312. # 3030 (added keyword-only parameters)
  313. # 3040 (added signature annotations)
  314. # 3050 (print becomes a function)
  315. # 3060 (PEP 3115 metaclass syntax)
  316. # 3061 (string literals become unicode)
  317. # 3071 (PEP 3109 raise changes)
  318. # 3081 (PEP 3137 make __file__ and __name__ unicode)
  319. # 3091 (kill str8 interning)
  320. # 3101 (merge from 2.6a0, see 62151)
  321. # 3103 (__file__ points to source file)
  322. # Python 3.0a4: 3111 (WITH_CLEANUP optimization).
  323. # Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
  324. # Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
  325. # change LIST_APPEND and SET_ADD, add MAP_ADD)
  326. # Python 3.1a0: 3151 (optimize conditional branches:
  327. # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
  328. # Python 3.2a0: 3160 (add SETUP_WITH)
  329. # tag: cpython-32
  330. # Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
  331. # tag: cpython-32
  332. # Python 3.2a2 3180 (add DELETE_DEREF)
  333. # Python 3.3a0 3190 __class__ super closure changed
  334. # Python 3.3a0 3200 (__qualname__ added)
  335. # 3210 (added size modulo 2**32 to the pyc header)
  336. # Python 3.3a1 3220 (changed PEP 380 implementation)
  337. # Python 3.3a4 3230 (revert changes to implicit __class__ closure)
  338. # Python 3.4a1 3250 (evaluate positional default arguments before
  339. # keyword-only defaults)
  340. # Python 3.4a1 3260 (add LOAD_CLASSDEREF; allow locals of class to override
  341. # free vars)
  342. # Python 3.4a1 3270 (various tweaks to the __class__ closure)
  343. # Python 3.4a1 3280 (remove implicit class argument)
  344. # Python 3.4a4 3290 (changes to __qualname__ computation)
  345. # Python 3.4a4 3300 (more changes to __qualname__ computation)
  346. # Python 3.4rc2 3310 (alter __qualname__ computation)
  347. # Python 3.5a0 3320 (matrix multiplication operator)
  348. #
  349. # MAGIC must change whenever the bytecode emitted by the compiler may no
  350. # longer be understood by older implementations of the eval loop (usually
  351. # due to the addition of new opcodes).
  352. MAGIC_NUMBER = (3320).to_bytes(2, 'little') + b'\r\n'
  353. _RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c
  354. _PYCACHE = '__pycache__'
  355. SOURCE_SUFFIXES = ['.py'] # _setup() adds .pyw as needed.
  356. DEBUG_BYTECODE_SUFFIXES = ['.pyc']
  357. OPTIMIZED_BYTECODE_SUFFIXES = ['.pyo']
  358. def cache_from_source(path, debug_override=None):
  359. """Given the path to a .py file, return the path to its .pyc/.pyo file.
  360. The .py file does not need to exist; this simply returns the path to the
  361. .pyc/.pyo file calculated as if the .py file were imported. The extension
  362. will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo.
  363. If debug_override is not None, then it must be a boolean and is used in
  364. place of sys.flags.optimize.
  365. If sys.implementation.cache_tag is None then NotImplementedError is raised.
  366. """
  367. debug = not sys.flags.optimize if debug_override is None else debug_override
  368. if debug:
  369. suffixes = DEBUG_BYTECODE_SUFFIXES
  370. else:
  371. suffixes = OPTIMIZED_BYTECODE_SUFFIXES
  372. head, tail = _path_split(path)
  373. base_filename, sep, _ = tail.partition('.')
  374. tag = sys.implementation.cache_tag
  375. if tag is None:
  376. raise NotImplementedError('sys.implementation.cache_tag is None')
  377. filename = ''.join([base_filename, sep, tag, suffixes[0]])
  378. return _path_join(head, _PYCACHE, filename)
  379. def source_from_cache(path):
  380. """Given the path to a .pyc./.pyo file, return the path to its .py file.
  381. The .pyc/.pyo file does not need to exist; this simply returns the path to
  382. the .py file calculated to correspond to the .pyc/.pyo file. If path does
  383. not conform to PEP 3147 format, ValueError will be raised. If
  384. sys.implementation.cache_tag is None then NotImplementedError is raised.
  385. """
  386. if sys.implementation.cache_tag is None:
  387. raise NotImplementedError('sys.implementation.cache_tag is None')
  388. head, pycache_filename = _path_split(path)
  389. head, pycache = _path_split(head)
  390. if pycache != _PYCACHE:
  391. raise ValueError('{} not bottom-level directory in '
  392. '{!r}'.format(_PYCACHE, path))
  393. if pycache_filename.count('.') != 2:
  394. raise ValueError('expected only 2 dots in '
  395. '{!r}'.format(pycache_filename))
  396. base_filename = pycache_filename.partition('.')[0]
  397. return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
  398. def _get_sourcefile(bytecode_path):
  399. """Convert a bytecode file path to a source path (if possible).
  400. This function exists purely for backwards-compatibility for
  401. PyImport_ExecCodeModuleWithFilenames() in the C API.
  402. """
  403. if len(bytecode_path) == 0:
  404. return None
  405. rest, _, extension = bytecode_path.rpartition('.')
  406. if not rest or extension.lower()[-3:-1] != 'py':
  407. return bytecode_path
  408. try:
  409. source_path = source_from_cache(bytecode_path)
  410. except (NotImplementedError, ValueError):
  411. source_path = bytecode_path[:-1]
  412. return source_path if _path_isfile(source_path) else bytecode_path
  413. def _calc_mode(path):
  414. """Calculate the mode permissions for a bytecode file."""
  415. try:
  416. mode = _path_stat(path).st_mode
  417. except OSError:
  418. mode = 0o666
  419. # We always ensure write access so we can update cached files
  420. # later even when the source files are read-only on Windows (#6074)
  421. mode |= 0o200
  422. return mode
  423. def _verbose_message(message, *args, verbosity=1):
  424. """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
  425. if sys.flags.verbose >= verbosity:
  426. if not message.startswith(('#', 'import ')):
  427. message = '# ' + message
  428. print(message.format(*args), file=sys.stderr)
  429. def _check_name(method):
  430. """Decorator to verify that the module being requested matches the one the
  431. loader can handle.
  432. The first argument (self) must define _name which the second argument is
  433. compared against. If the comparison fails then ImportError is raised.
  434. """
  435. def _check_name_wrapper(self, name=None, *args, **kwargs):
  436. if name is None:
  437. name = self.name
  438. elif self.name != name:
  439. raise ImportError('loader cannot handle %s' % name, name=name)
  440. return method(self, name, *args, **kwargs)
  441. _wrap(_check_name_wrapper, method)
  442. return _check_name_wrapper
  443. def _requires_builtin(fxn):
  444. """Decorator to verify the named module is built-in."""
  445. def _requires_builtin_wrapper(self, fullname):
  446. if fullname not in sys.builtin_module_names:
  447. raise ImportError('{!r} is not a built-in module'.format(fullname),
  448. name=fullname)
  449. return fxn(self, fullname)
  450. _wrap(_requires_builtin_wrapper, fxn)
  451. return _requires_builtin_wrapper
  452. def _requires_frozen(fxn):
  453. """Decorator to verify the named module is frozen."""
  454. def _requires_frozen_wrapper(self, fullname):
  455. if not _imp.is_frozen(fullname):
  456. raise ImportError('{!r} is not a frozen module'.format(fullname),
  457. name=fullname)
  458. return fxn(self, fullname)
  459. _wrap(_requires_frozen_wrapper, fxn)
  460. return _requires_frozen_wrapper
  461. def _find_module_shim(self, fullname):
  462. """Try to find a loader for the specified module by delegating to
  463. self.find_loader().
  464. This method is deprecated in favor of finder.find_spec().
  465. """
  466. # Call find_loader(). If it returns a string (indicating this
  467. # is a namespace package portion), generate a warning and
  468. # return None.
  469. loader, portions = self.find_loader(fullname)
  470. if loader is None and len(portions):
  471. msg = 'Not importing directory {}: missing __init__'
  472. _warnings.warn(msg.format(portions[0]), ImportWarning)
  473. return loader
  474. def _load_module_shim(self, fullname):
  475. """Load the specified module into sys.modules and return it.
  476. This method is deprecated. Use loader.exec_module instead.
  477. """
  478. spec = spec_from_loader(fullname, self)
  479. methods = _SpecMethods(spec)
  480. if fullname in sys.modules:
  481. module = sys.modules[fullname]
  482. methods.exec(module)
  483. return sys.modules[fullname]
  484. else:
  485. return methods.load()
  486. def _validate_bytecode_header(data, source_stats=None, name=None, path=None):
  487. """Validate the header of the passed-in bytecode against source_stats (if
  488. given) and returning the bytecode that can be compiled by compile().
  489. All other arguments are used to enhance error reporting.
  490. ImportError is raised when the magic number is incorrect or the bytecode is
  491. found to be stale. EOFError is raised when the data is found to be
  492. truncated.
  493. """
  494. exc_details = {}
  495. if name is not None:
  496. exc_details['name'] = name
  497. else:
  498. # To prevent having to make all messages have a conditional name.
  499. name = '<bytecode>'
  500. if path is not None:
  501. exc_details['path'] = path
  502. magic = data[:4]
  503. raw_timestamp = data[4:8]
  504. raw_size = data[8:12]
  505. if magic != MAGIC_NUMBER:
  506. message = 'bad magic number in {!r}: {!r}'.format(name, magic)
  507. _verbose_message(message)
  508. raise ImportError(message, **exc_details)
  509. elif len(raw_timestamp) != 4:
  510. message = 'reached EOF while reading timestamp in {!r}'.format(name)
  511. _verbose_message(message)
  512. raise EOFError(message)
  513. elif len(raw_size) != 4:
  514. message = 'reached EOF while reading size of source in {!r}'.format(name)
  515. _verbose_message(message)
  516. raise EOFError(message)
  517. if source_stats is not None:
  518. try:
  519. source_mtime = int(source_stats['mtime'])
  520. except KeyError:
  521. pass
  522. else:
  523. if _r_long(raw_timestamp) != source_mtime:
  524. message = 'bytecode is stale for {!r}'.format(name)
  525. _verbose_message(message)
  526. raise ImportError(message, **exc_details)
  527. try:
  528. source_size = source_stats['size'] & 0xFFFFFFFF
  529. except KeyError:
  530. pass
  531. else:
  532. if _r_long(raw_size) != source_size:
  533. raise ImportError('bytecode is stale for {!r}'.format(name),
  534. **exc_details)
  535. return data[12:]
  536. def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
  537. """Compile bytecode as returned by _validate_bytecode_header()."""
  538. code = marshal.loads(data)
  539. if isinstance(code, _code_type):
  540. _verbose_message('code object from {!r}', bytecode_path)
  541. if source_path is not None:
  542. _imp._fix_co_filename(code, source_path)
  543. return code
  544. else:
  545. raise ImportError('Non-code object in {!r}'.format(bytecode_path),
  546. name=name, path=bytecode_path)
  547. def _code_to_bytecode(code, mtime=0, source_size=0):
  548. """Compile a code object into bytecode for writing out to a byte-compiled
  549. file."""
  550. data = bytearray(MAGIC_NUMBER)
  551. data.extend(_w_long(mtime))
  552. data.extend(_w_long(source_size))
  553. data.extend(marshal.dumps(code))
  554. return data
  555. def decode_source(source_bytes):
  556. """Decode bytes representing source code and return the string.
  557. Universal newline support is used in the decoding.
  558. """
  559. import tokenize # To avoid bootstrap issues.
  560. source_bytes_readline = _io.BytesIO(source_bytes).readline
  561. encoding = tokenize.detect_encoding(source_bytes_readline)
  562. newline_decoder = _io.IncrementalNewlineDecoder(None, True)
  563. return newline_decoder.decode(source_bytes.decode(encoding[0]))
  564. # Module specifications #######################################################
  565. def _module_repr(module):
  566. # The implementation of ModuleType__repr__().
  567. loader = getattr(module, '__loader__', None)
  568. if hasattr(loader, 'module_repr'):
  569. # As soon as BuiltinImporter, FrozenImporter, and NamespaceLoader
  570. # drop their implementations for module_repr. we can add a
  571. # deprecation warning here.
  572. try:
  573. return loader.module_repr(module)
  574. except Exception:
  575. pass
  576. try:
  577. spec = module.__spec__
  578. except AttributeError:
  579. pass
  580. else:
  581. if spec is not None:
  582. return _SpecMethods(spec).module_repr()
  583. # We could use module.__class__.__name__ instead of 'module' in the
  584. # various repr permutations.
  585. try:
  586. name = module.__name__
  587. except AttributeError:
  588. name = '?'
  589. try:
  590. filename = module.__file__
  591. except AttributeError:
  592. if loader is None:
  593. return '<module {!r}>'.format(name)
  594. else:
  595. return '<module {!r} ({!r})>'.format(name, loader)
  596. else:
  597. return '<module {!r} from {!r}>'.format(name, filename)
  598. class _installed_safely:
  599. def __init__(self, module):
  600. self._module = module
  601. self._spec = module.__spec__
  602. def __enter__(self):
  603. # This must be done before putting the module in sys.modules
  604. # (otherwise an optimization shortcut in import.c becomes
  605. # wrong)
  606. self._spec._initializing = True
  607. sys.modules[self._spec.name] = self._module
  608. def __exit__(self, *args):
  609. try:
  610. spec = self._spec
  611. if any(arg is not None for arg in args):
  612. try:
  613. del sys.modules[spec.name]
  614. except KeyError:
  615. pass
  616. else:
  617. _verbose_message('import {!r} # {!r}', spec.name, spec.loader)
  618. finally:
  619. self._spec._initializing = False
  620. class ModuleSpec:
  621. """The specification for a module, used for loading.
  622. A module's spec is the source for information about the module. For
  623. data associated with the module, including source, use the spec's
  624. loader.
  625. `name` is the absolute name of the module. `loader` is the loader
  626. to use when loading the module. `parent` is the name of the
  627. package the module is in. The parent is derived from the name.
  628. `is_package` determines if the module is considered a package or
  629. not. On modules this is reflected by the `__path__` attribute.
  630. `origin` is the specific location used by the loader from which to
  631. load the module, if that information is available. When filename is
  632. set, origin will match.
  633. `has_location` indicates that a spec's "origin" reflects a location.
  634. When this is True, `__file__` attribute of the module is set.
  635. `cached` is the location of the cached bytecode file, if any. It
  636. corresponds to the `__cached__` attribute.
  637. `submodule_search_locations` is the sequence of path entries to
  638. search when importing submodules. If set, is_package should be
  639. True--and False otherwise.
  640. Packages are simply modules that (may) have submodules. If a spec
  641. has a non-None value in `submodule_search_locations`, the import
  642. system will consider modules loaded from the spec as packages.
  643. Only finders (see importlib.abc.MetaPathFinder and
  644. importlib.abc.PathEntryFinder) should modify ModuleSpec instances.
  645. """
  646. def __init__(self, name, loader, *, origin=None, loader_state=None,
  647. is_package=None):
  648. self.name = name
  649. self.loader = loader
  650. self.origin = origin
  651. self.loader_state = loader_state
  652. self.submodule_search_locations = [] if is_package else None
  653. # file-location attributes
  654. self._set_fileattr = False
  655. self._cached = None
  656. def __repr__(self):
  657. args = ['name={!r}'.format(self.name),
  658. 'loader={!r}'.format(self.loader)]
  659. if self.origin is not None:
  660. args.append('origin={!r}'.format(self.origin))
  661. if self.submodule_search_locations is not None:
  662. args.append('submodule_search_locations={}'
  663. .format(self.submodule_search_locations))
  664. return '{}({})'.format(self.__class__.__name__, ', '.join(args))
  665. def __eq__(self, other):
  666. smsl = self.submodule_search_locations
  667. try:
  668. return (self.name == other.name and
  669. self.loader == other.loader and
  670. self.origin == other.origin and
  671. smsl == other.submodule_search_locations and
  672. self.cached == other.cached and
  673. self.has_location == other.has_location)
  674. except AttributeError:
  675. return False
  676. @property
  677. def cached(self):
  678. if self._cached is None:
  679. if self.origin is not None and self._set_fileattr:
  680. filename = self.origin
  681. if filename.endswith(tuple(SOURCE_SUFFIXES)):
  682. try:
  683. self._cached = cache_from_source(filename)
  684. except NotImplementedError:
  685. pass
  686. elif filename.endswith(tuple(BYTECODE_SUFFIXES)):
  687. self._cached = filename
  688. return self._cached
  689. @cached.setter
  690. def cached(self, cached):
  691. self._cached = cached
  692. @property
  693. def parent(self):
  694. """The name of the module's parent."""
  695. if self.submodule_search_locations is None:
  696. return self.name.rpartition('.')[0]
  697. else:
  698. return self.name
  699. @property
  700. def has_location(self):
  701. return self._set_fileattr
  702. @has_location.setter
  703. def has_location(self, value):
  704. self._set_fileattr = bool(value)
  705. def spec_from_loader(name, loader, *, origin=None, is_package=None):
  706. """Return a module spec based on various loader methods."""
  707. if hasattr(loader, 'get_filename'):
  708. if is_package is None:
  709. return spec_from_file_location(name, loader=loader)
  710. search = [] if is_package else None
  711. return spec_from_file_location(name, loader=loader,
  712. submodule_search_locations=search)
  713. if is_package is None:
  714. if hasattr(loader, 'is_package'):
  715. try:
  716. is_package = loader.is_package(name)
  717. except ImportError:
  718. is_package = None # aka, undefined
  719. else:
  720. # the default
  721. is_package = False
  722. return ModuleSpec(name, loader, origin=origin, is_package=is_package)
  723. _POPULATE = object()
  724. def spec_from_file_location(name, location=None, *, loader=None,
  725. submodule_search_locations=_POPULATE):
  726. """Return a module spec based on a file location.
  727. To indicate that the module is a package, set
  728. submodule_search_locations to a list of directory paths. An
  729. empty list is sufficient, though its not otherwise useful to the
  730. import system.
  731. The loader must take a spec as its only __init__() arg.
  732. """
  733. if location is None:
  734. # The caller may simply want a partially populated location-
  735. # oriented spec. So we set the location to a bogus value and
  736. # fill in as much as we can.
  737. location = '<unknown>'
  738. if hasattr(loader, 'get_filename'):
  739. # ExecutionLoader
  740. try:
  741. location = loader.get_filename(name)
  742. except ImportError:
  743. pass
  744. # If the location is on the filesystem, but doesn't actually exist,
  745. # we could return None here, indicating that the location is not
  746. # valid. However, we don't have a good way of testing since an
  747. # indirect location (e.g. a zip file or URL) will look like a
  748. # non-existent file relative to the filesystem.
  749. spec = ModuleSpec(name, loader, origin=location)
  750. spec._set_fileattr = True
  751. # Pick a loader if one wasn't provided.
  752. if loader is None:
  753. for loader_class, suffixes in _get_supported_file_loaders():
  754. if location.endswith(tuple(suffixes)):
  755. loader = loader_class(name, location)
  756. spec.loader = loader
  757. break
  758. else:
  759. return None
  760. # Set submodule_search_paths appropriately.
  761. if submodule_search_locations is _POPULATE:
  762. # Check the loader.
  763. if hasattr(loader, 'is_package'):
  764. try:
  765. is_package = loader.is_package(name)
  766. except ImportError:
  767. pass
  768. else:
  769. if is_package:
  770. spec.submodule_search_locations = []
  771. else:
  772. spec.submodule_search_locations = submodule_search_locations
  773. if spec.submodule_search_locations == []:
  774. if location:
  775. dirname = _path_split(location)[0]
  776. spec.submodule_search_locations.append(dirname)
  777. return spec
  778. def _spec_from_module(module, loader=None, origin=None):
  779. # This function is meant for use in _setup().
  780. try:
  781. spec = module.__spec__
  782. except AttributeError:
  783. pass
  784. else:
  785. if spec is not None:
  786. return spec
  787. name = module.__name__
  788. if loader is None:
  789. try:
  790. loader = module.__loader__
  791. except AttributeError:
  792. # loader will stay None.
  793. pass
  794. try:
  795. location = module.__file__
  796. except AttributeError:
  797. location = None
  798. if origin is None:
  799. if location is None:
  800. try:
  801. origin = loader._ORIGIN
  802. except AttributeError:
  803. origin = None
  804. else:
  805. origin = location
  806. try:
  807. cached = module.__cached__
  808. except AttributeError:
  809. cached = None
  810. try:
  811. submodule_search_locations = list(module.__path__)
  812. except AttributeError:
  813. submodule_search_locations = None
  814. spec = ModuleSpec(name, loader, origin=origin)
  815. spec._set_fileattr = False if location is None else True
  816. spec.cached = cached
  817. spec.submodule_search_locations = submodule_search_locations
  818. return spec
  819. class _SpecMethods:
  820. """Convenience wrapper around spec objects to provide spec-specific
  821. methods."""
  822. # The various spec_from_* functions could be made factory methods here.
  823. def __init__(self, spec):
  824. self.spec = spec
  825. def module_repr(self):
  826. """Return the repr to use for the module."""
  827. # We mostly replicate _module_repr() using the spec attributes.
  828. spec = self.spec
  829. name = '?' if spec.name is None else spec.name
  830. if spec.origin is None:
  831. if spec.loader is None:
  832. return '<module {!r}>'.format(name)
  833. else:
  834. return '<module {!r} ({!r})>'.format(name, spec.loader)
  835. else:
  836. if spec.has_location:
  837. return '<module {!r} from {!r}>'.format(name, spec.origin)
  838. else:
  839. return '<module {!r} ({})>'.format(spec.name, spec.origin)
  840. def init_module_attrs(self, module, *, _override=False, _force_name=True):
  841. """Set the module's attributes.
  842. All missing import-related module attributes will be set. Here
  843. is how the spec attributes map onto the module:
  844. spec.name -> module.__name__
  845. spec.loader -> module.__loader__
  846. spec.parent -> module.__package__
  847. spec -> module.__spec__
  848. Optional:
  849. spec.origin -> module.__file__ (if spec.set_fileattr is true)
  850. spec.cached -> module.__cached__ (if __file__ also set)
  851. spec.submodule_search_locations -> module.__path__ (if set)
  852. """
  853. spec = self.spec
  854. # The passed in module may be not support attribute assignment,
  855. # in which case we simply don't set the attributes.
  856. # __name__
  857. if (_override or _force_name or
  858. getattr(module, '__name__', None) is None):
  859. try:
  860. module.__name__ = spec.name
  861. except AttributeError:
  862. pass
  863. # __loader__
  864. if _override or getattr(module, '__loader__', None) is None:
  865. loader = spec.loader
  866. if loader is None:
  867. # A backward compatibility hack.
  868. if spec.submodule_search_locations is not None:
  869. loader = _NamespaceLoader.__new__(_NamespaceLoader)
  870. loader._path = spec.submodule_search_locations
  871. try:
  872. module.__loader__ = loader
  873. except AttributeError:
  874. pass
  875. # __package__
  876. if _override or getattr(module, '__package__', None) is None:
  877. try:
  878. module.__package__ = spec.parent
  879. except AttributeError:
  880. pass
  881. # __spec__
  882. try:
  883. module.__spec__ = spec
  884. except AttributeError:
  885. pass
  886. # __path__
  887. if _override or getattr(module, '__path__', None) is None:
  888. if spec.submodule_search_locations is not None:
  889. try:
  890. module.__path__ = spec.submodule_search_locations
  891. except AttributeError:
  892. pass
  893. if spec.has_location:
  894. # __file__
  895. if _override or getattr(module, '__file__', None) is None:
  896. try:
  897. module.__file__ = spec.origin
  898. except AttributeError:
  899. pass
  900. # __cached__
  901. if _override or getattr(module, '__cached__', None) is None:
  902. if spec.cached is not None:
  903. try:
  904. module.__cached__ = spec.cached
  905. except AttributeError:
  906. pass
  907. def create(self):
  908. """Return a new module to be loaded.
  909. The import-related module attributes are also set with the
  910. appropriate values from the spec.
  911. """
  912. spec = self.spec
  913. # Typically loaders will not implement create_module().
  914. if hasattr(spec.loader, 'create_module'):
  915. # If create_module() returns `None` it means the default
  916. # module creation should be used.
  917. module = spec.loader.create_module(spec)
  918. else:
  919. module = None
  920. if module is None:
  921. # This must be done before open() is ever called as the 'io'
  922. # module implicitly imports 'locale' and would otherwise
  923. # trigger an infinite loop.
  924. module = _new_module(spec.name)
  925. self.init_module_attrs(module)
  926. return module
  927. def _exec(self, module):
  928. """Do everything necessary to execute the module.
  929. The namespace of `module` is used as the target of execution.
  930. This method uses the loader's `exec_module()` method.
  931. """
  932. self.spec.loader.exec_module(module)
  933. # Used by importlib.reload() and _load_module_shim().
  934. def exec(self, module):
  935. """Execute the spec in an existing module's namespace."""
  936. name = self.spec.name
  937. _imp.acquire_lock()
  938. with _ModuleLockManager(name):
  939. if sys.modules.get(name) is not module:
  940. msg = 'module {!r} not in sys.modules'.format(name)
  941. raise ImportError(msg, name=name)
  942. if self.spec.loader is None:
  943. if self.spec.submodule_search_locations is None:
  944. raise ImportError('missing loader', name=self.spec.name)
  945. # namespace package
  946. self.init_module_attrs(module, _override=True)
  947. return module
  948. self.init_module_attrs(module, _override=True)
  949. if not hasattr(self.spec.loader, 'exec_module'):
  950. # (issue19713) Once BuiltinImporter and ExtensionFileLoader
  951. # have exec_module() implemented, we can add a deprecation
  952. # warning here.
  953. self.spec.loader.load_module(name)
  954. else:
  955. self._exec(module)
  956. return sys.modules[name]
  957. def _load_backward_compatible(self):
  958. # (issue19713) Once BuiltinImporter and ExtensionFileLoader
  959. # have exec_module() implemented, we can add a deprecation
  960. # warning here.
  961. spec = self.spec
  962. spec.loader.load_module(spec.name)
  963. # The module must be in sys.modules at this point!
  964. module = sys.modules[spec.name]
  965. if getattr(module, '__loader__', None) is None:
  966. try:
  967. module.__loader__ = spec.loader
  968. except AttributeError:
  969. pass
  970. if getattr(module, '__package__', None) is None:
  971. try:
  972. # Since module.__path__ may not line up with
  973. # spec.submodule_search_paths, we can't necessarily rely
  974. # on spec.parent here.
  975. module.__package__ = module.__name__
  976. if not hasattr(module, '__path__'):
  977. module.__package__ = spec.name.rpartition('.')[0]
  978. except AttributeError:
  979. pass
  980. if getattr(module, '__spec__', None) is None:
  981. try:
  982. module.__spec__ = spec
  983. except AttributeError:
  984. pass
  985. return module
  986. def _load_unlocked(self):
  987. # A helper for direct use by the import system.
  988. if self.spec.loader is not None:
  989. # not a namespace package
  990. if not hasattr(self.spec.loader, 'exec_module'):
  991. return self._load_backward_compatible()
  992. module = self.create()
  993. with _installed_safely(module):
  994. if self.spec.loader is None:
  995. if self.spec.submodule_search_locations is None:
  996. raise ImportError('missing loader', name=self.spec.name)
  997. # A namespace package so do nothing.
  998. else:
  999. self._exec(module)
  1000. # We don't ensure that the import-related module attributes get
  1001. # set in the sys.modules replacement case. Such modules are on
  1002. # their own.
  1003. return sys.modules[self.spec.name]
  1004. # A method used during testing of _load_unlocked() and by
  1005. # _load_module_shim().
  1006. def load(self):
  1007. """Return a new module object, loaded by the spec's loader.
  1008. The module is not added to its parent.
  1009. If a module is already in sys.modules, that existing module gets
  1010. clobbered.
  1011. """
  1012. _imp.acquire_lock()
  1013. with _ModuleLockManager(self.spec.name):
  1014. return self._load_unlocked()
  1015. # Loaders #####################################################################
  1016. class BuiltinImporter:
  1017. """Meta path import for built-in modules.
  1018. All methods are either class or static methods to avoid the need to
  1019. instantiate the class.
  1020. """
  1021. @staticmethod
  1022. def module_repr(module):
  1023. """Return repr for the module.
  1024. The method is deprecated. The import machinery does the job itself.
  1025. """
  1026. return '<module {!r} (built-in)>'.format(module.__name__)
  1027. @classmethod
  1028. def find_spec(cls, fullname, path=None, target=None):
  1029. if path is not None:
  1030. return None
  1031. if _imp.is_builtin(fullname):
  1032. return spec_from_loader(fullname, cls, origin='built-in')
  1033. else:
  1034. return None
  1035. @classmethod
  1036. def find_module(cls, fullname, path=None):
  1037. """Find the built-in module.
  1038. If 'path' is ever specified then the search is considered a failure.
  1039. This method is deprecated. Use find_spec() instead.
  1040. """
  1041. spec = cls.find_spec(fullname, path)
  1042. return spec.loader if spec is not None else None
  1043. @classmethod
  1044. @_requires_builtin
  1045. def load_module(cls, fullname):
  1046. """Load a built-in module."""
  1047. # Once an exec_module() implementation is added we can also
  1048. # add a deprecation warning here.
  1049. with _ManageReload(fullname):
  1050. module = _call_with_frames_removed(_imp.init_builtin, fullname)
  1051. module.__loader__ = cls
  1052. module.__package__ = ''
  1053. return module
  1054. @classmethod
  1055. @_requires_builtin
  1056. def get_code(cls, fullname):
  1057. """Return None as built-in modules do not have code objects."""
  1058. return None
  1059. @classmethod
  1060. @_requires_builtin
  1061. def get_source(cls, fullname):
  1062. """Return None as built-in modules do not have source code."""
  1063. return None
  1064. @classmethod
  1065. @_requires_builtin
  1066. def is_package(cls, fullname):
  1067. """Return False as built-in modules are never packages."""
  1068. return False
  1069. class FrozenImporter:
  1070. """Meta path import for frozen modules.
  1071. All methods are either class or static methods to avoid the need to
  1072. instantiate the class.
  1073. """
  1074. @staticmethod
  1075. def module_repr(m):
  1076. """Return repr for the module.
  1077. The method is deprecated. The import machinery does the job itself.
  1078. """
  1079. return '<module {!r} (frozen)>'.format(m.__name__)
  1080. @classmethod
  1081. def find_spec(cls, fullname, path=None, target=None):
  1082. if _imp.is_frozen(fullname):
  1083. return spec_from_loader(fullname, cls, origin='frozen')
  1084. else:
  1085. return None
  1086. @classmethod
  1087. def find_module(cls, fullname, path=None):
  1088. """Find a frozen module.
  1089. This method is deprecated. Use find_spec() instead.
  1090. """
  1091. return cls if _imp.is_frozen(fullname) else None
  1092. @staticmethod
  1093. def exec_module(module):
  1094. name = module.__spec__.name
  1095. if not _imp.is_frozen(name):
  1096. raise ImportError('{!r} is not a frozen module'.format(name),
  1097. name=name)
  1098. code = _call_with_frames_removed(_imp.get_frozen_object, name)
  1099. exec(code, module.__dict__)
  1100. @classmethod
  1101. def load_module(cls, fullname):
  1102. """Load a frozen module.
  1103. This method is deprecated. Use exec_module() instead.
  1104. """
  1105. return _load_module_shim(cls, fullname)
  1106. @classmethod
  1107. @_requires_frozen
  1108. def get_code(cls, fullname):
  1109. """Return the code object for the frozen module."""
  1110. return _imp.get_frozen_object(fullname)
  1111. @classmethod
  1112. @_requires_frozen
  1113. def get_source(cls, fullname):
  1114. """Return None as frozen modules do not have source code."""
  1115. return None
  1116. @classmethod
  1117. @_requires_frozen
  1118. def is_package(cls, fullname):
  1119. """Return True if the frozen module is a package."""
  1120. return _imp.is_frozen_package(fullname)
  1121. class WindowsRegistryFinder:
  1122. """Meta path finder for modules declared in the Windows registry."""
  1123. REGISTRY_KEY = (
  1124. 'Software\\Python\\PythonCore\\{sys_version}'
  1125. '\\Modules\\{fullname}')
  1126. REGISTRY_KEY_DEBUG = (
  1127. 'Software\\Python\\PythonCore\\{sys_version}'
  1128. '\\Modules\\{fullname}\\Debug')
  1129. DEBUG_BUILD = False # Changed in _setup()
  1130. @classmethod
  1131. def _open_registry(cls, key):
  1132. try:
  1133. return _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key)
  1134. except OSError:
  1135. return _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
  1136. @classmethod
  1137. def _search_registry(cls, fullname):
  1138. if cls.DEBUG_BUILD:
  1139. registry_key = cls.REGISTRY_KEY_DEBUG
  1140. else:
  1141. registry_key = cls.REGISTRY_KEY
  1142. key = registry_key.format(fullname=fullname,
  1143. sys_version=sys.version[:3])
  1144. try:
  1145. with cls._open_registry(key) as hkey:
  1146. filepath = _winreg.QueryValue(hkey, '')
  1147. except OSError:
  1148. return None
  1149. return filepath
  1150. @classmethod
  1151. def find_spec(cls, fullname, path=None, target=None):
  1152. filepath = cls._search_registry(fullname)
  1153. if filepath is None:
  1154. return None
  1155. try:
  1156. _path_stat(filepath)
  1157. except OSError:
  1158. return None
  1159. for loader, suffixes in _get_supported_file_loaders():
  1160. if filepath.endswith(tuple(suffixes)):
  1161. spec = spec_from_loader(fullname, loader(fullname, filepath),
  1162. origin=filepath)
  1163. return spec
  1164. @classmethod
  1165. def find_module(cls, fullname, path=None):
  1166. """Find module named in the registry.
  1167. This method is deprecated. Use exec_module() instead.
  1168. """
  1169. spec = cls.find_spec(fullname, path)
  1170. if spec is not None:
  1171. return spec.loader
  1172. else:
  1173. return None
  1174. class _LoaderBasics:
  1175. """Base class of common code needed by both SourceLoader and
  1176. SourcelessFileLoader."""
  1177. def is_package(self, fullname):
  1178. """Concrete implementation of InspectLoader.is_package by checking if
  1179. the path returned by get_filename has a filename of '__init__.py'."""
  1180. filename = _path_split(self.get_filename(fullname))[1]
  1181. filename_base = filename.rsplit('.', 1)[0]
  1182. tail_name = fullname.rpartition('.')[2]
  1183. return filename_base == '__init__' and tail_name != '__init__'
  1184. def exec_module(self, module):
  1185. """Execute the module."""
  1186. code = self.get_code(module.__name__)
  1187. if code is None:
  1188. raise ImportError('cannot load module {!r} when get_code() '
  1189. 'returns None'.format(module.__name__))
  1190. _call_with_frames_removed(exec, code, module.__dict__)
  1191. load_module = _load_module_shim
  1192. class SourceLoader(_LoaderBasics):
  1193. def path_mtime(self, path):
  1194. """Optional method that returns the modification time (an int) for the
  1195. specified path, wher

Large files files are truncated, but you can click here to view the full file