PageRenderTime 67ms CodeModel.GetById 20ms 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
  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, where path is a str.
  1196. Raises IOError when the path cannot be handled.
  1197. """
  1198. raise IOError
  1199. def path_stats(self, path):
  1200. """Optional method returning a metadata dict for the specified path
  1201. to by the path (str).
  1202. Possible keys:
  1203. - 'mtime' (mandatory) is the numeric timestamp of last source
  1204. code modification;
  1205. - 'size' (optional) is the size in bytes of the source code.
  1206. Implementing this method allows the loader to read bytecode files.
  1207. Raises IOError when the path cannot be handled.
  1208. """
  1209. return {'mtime': self.path_mtime(path)}
  1210. def _cache_bytecode(self, source_path, cache_path, data):
  1211. """Optional method which writes data (bytes) to a file path (a str).
  1212. Implementing this method allows for the writing of bytecode files.
  1213. The source path is needed in order to correctly transfer permissions
  1214. """
  1215. # For backwards compatibility, we delegate to set_data()
  1216. return self.set_data(cache_path, data)
  1217. def set_data(self, path, data):
  1218. """Optional method which writes data (bytes) to a file path (a str).
  1219. Implementing this method allows for the writing of bytecode files.
  1220. """
  1221. def get_source(self, fullname):
  1222. """Concrete implementation of InspectLoader.get_source."""
  1223. path = self.get_filename(fullname)
  1224. try:
  1225. source_bytes = self.get_data(path)
  1226. except OSError as exc:
  1227. raise ImportError('source not available through get_data()',
  1228. name=fullname) from exc
  1229. return decode_source(source_bytes)
  1230. def source_to_code(self, data, path, *, _optimize=-1):
  1231. """Return the code object compiled from source.
  1232. The 'data' argument can be any object type that compile() supports.
  1233. """
  1234. return _call_with_frames_removed(compile, data, path, 'exec',
  1235. dont_inherit=True, optimize=_optimize)
  1236. def get_code(self, fullname):
  1237. """Concrete implementation of InspectLoader.get_code.
  1238. Reading of bytecode requires path_stats to be implemented. To write
  1239. bytecode, set_data must also be implemented.
  1240. """
  1241. source_path = self.get_filename(fullname)
  1242. source_mtime = None
  1243. try:
  1244. bytecode_path = cache_from_source(source_path)
  1245. except NotImplementedError:
  1246. bytecode_path = None
  1247. else:
  1248. try:
  1249. st = self.path_stats(source_path)
  1250. except IOError:
  1251. pass
  1252. else:
  1253. source_mtime = int(st['mtime'])
  1254. try:
  1255. data = self.get_data(bytecode_path)
  1256. except OSError:
  1257. pass
  1258. else:
  1259. try:
  1260. bytes_data = _validate_bytecode_header(data,
  1261. source_stats=st, name=fullname,
  1262. path=bytecode_path)
  1263. except (ImportError, EOFError):
  1264. pass
  1265. else:
  1266. _verbose_message('{} matches {}', bytecode_path,
  1267. source_path)
  1268. return _compile_bytecode(bytes_data, name=fullname,
  1269. bytecode_path=bytecode_path,
  1270. source_path=source_path)
  1271. source_bytes = self.get_data(source_path)
  1272. code_object = self.source_to_code(source_bytes, source_path)
  1273. _verbose_message('code object from {}', source_path)
  1274. if (not sys.dont_write_bytecode and bytecode_path is not None and
  1275. source_mtime is not None):
  1276. data = _code_to_bytecode(code_object, source_mtime,
  1277. len(source_bytes))
  1278. try:
  1279. self._cache_bytecode(source_path, bytecode_path, data)
  1280. _verbose_message('wrote {!r}', bytecode_path)
  1281. except NotImplementedError:
  1282. pass
  1283. return code_object
  1284. class FileLoader:
  1285. """Base file loader class which implements the loader protocol methods that
  1286. require file system usage."""
  1287. def __init__(self, fullname, path):
  1288. """Cache the module name and the path to the file found by the
  1289. finder."""
  1290. self.name = fullname
  1291. self.path = path
  1292. def __eq__(self, other):
  1293. return (self.__class__ == other.__class__ and
  1294. self.__dict__ == other.__dict__)
  1295. def __hash__(self):
  1296. return hash(self.name) ^ hash(self.path)
  1297. @_check_name
  1298. def load_module(self, fullname):
  1299. """Load a module from a file.
  1300. This method is deprecated. Use exec_module() instead.
  1301. """
  1302. # The only reason for this method is for the name check.
  1303. # Issue #14857: Avoid the zero-argument form of super so the implementation
  1304. # of that form can be updated without breaking the frozen module
  1305. return super(FileLoader, self).load_module(fullname)
  1306. @_check_name
  1307. def get_filename(self, fullname):
  1308. """Return the path to the source file as found by the finder."""
  1309. return self.path
  1310. def get_data(self, path):
  1311. """Return the data from path as raw bytes."""
  1312. with _io.FileIO(path, 'r') as file:
  1313. return file.read()
  1314. class SourceFileLoader(FileLoader, SourceLoader):
  1315. """Concrete implementation of SourceLoader using the file system."""
  1316. def path_stats(self, path):
  1317. """Return the metadata for the path."""
  1318. st = _path_stat(path)
  1319. return {'mtime': st.st_mtime, 'size': st.st_size}
  1320. def _cache_bytecode(self, source_path, bytecode_path, data):
  1321. # Adapt between the two APIs
  1322. mode = _calc_mode(source_path)
  1323. return self.set_data(bytecode_path, data, _mode=mode)
  1324. def set_data(self, path, data, *, _mode=0o666):
  1325. """Write bytes data to a file."""
  1326. parent, filename = _path_split(path)
  1327. path_parts = []
  1328. # Figure out what directories are missing.
  1329. while parent and not _path_isdir(parent):
  1330. parent, part = _path_split(parent)
  1331. path_parts.append(part)
  1332. # Create needed directories.
  1333. for part in reversed(path_parts):
  1334. parent = _path_join(parent, part)
  1335. try:
  1336. _os.mkdir(parent)
  1337. except FileExistsError:
  1338. # Probably another Python process already created the dir.
  1339. continue
  1340. except OSError as exc:
  1341. # Could be a permission error, read-only filesystem: just forget
  1342. # about writing the data.
  1343. _verbose_message('could not create {!r}: {!r}', parent, exc)
  1344. return
  1345. try:
  1346. _write_atomic(path, data, _mode)
  1347. _verbose_message('created {!r}', path)
  1348. except OSError as exc:
  1349. # Same as above: just don't write the bytecode.
  1350. _verbose_message('could not create {!r}: {!r}', path, exc)
  1351. class SourcelessFileLoader(FileLoader, _LoaderBasics):
  1352. """Loader which handles sourceless file imports."""
  1353. def get_code(self, fullname):
  1354. path = self.get_filename(fullname)
  1355. data = self.get_data(path)
  1356. bytes_data = _validate_bytecode_header(data, name=fullname, path=path)
  1357. return _compile_bytecode(bytes_data, name=fullname, bytecode_path=path)
  1358. def get_source(self, fullname):
  1359. """Return None as there is no source code."""
  1360. return None
  1361. # Filled in by _setup().
  1362. EXTENSION_SUFFIXES = []
  1363. class ExtensionFileLoader:
  1364. """Loader for extension modules.
  1365. The constructor is designed to work with FileFinder.
  1366. """
  1367. def __init__(self, name, path):
  1368. self.name = name
  1369. self.path = path
  1370. def __eq__(self, other):
  1371. return (self.__class__ == other.__class__ and
  1372. self.__dict__ == other.__dict__)
  1373. def __hash__(self):
  1374. return hash(self.name) ^ hash(self.path)
  1375. @_check_name
  1376. def load_module(self, fullname):
  1377. """Load an extension module."""
  1378. # Once an exec_module() implementation is added we can also
  1379. # add a deprecation warning here.
  1380. with _ManageReload(fullname):
  1381. module = _call_with_frames_removed(_imp.load_dynamic,
  1382. fullname, self.path)
  1383. _verbose_message('extension module loaded from {!r}', self.path)
  1384. is_package = self.is_package(fullname)
  1385. if is_package and not hasattr(module, '__path__'):
  1386. module.__path__ = [_path_split(self.path)[0]]
  1387. module.__loader__ = self
  1388. module.__package__ = module.__name__
  1389. if not is_package:
  1390. module.__package__ = module.__package__.rpartition('.')[0]
  1391. return module
  1392. def is_package(self, fullname):
  1393. """Return True if the extension module is a package."""
  1394. file_name = _path_split(self.path)[1]
  1395. return any(file_name == '__init__' + suffix
  1396. for suffix in EXTENSION_SUFFIXES)
  1397. def get_code(self, fullname):
  1398. """Return None as an extension module cannot create a code object."""
  1399. return None
  1400. def get_source(self, fullname):
  1401. """Return None as extension modules have no source code."""
  1402. return None
  1403. @_check_name
  1404. def get_filename(self, fullname):
  1405. """Return the path to the source file as found by the finder."""
  1406. return self.path
  1407. class _NamespacePath:
  1408. """Represents a namespace package's path. It uses the module name
  1409. to find its parent module, and from there it looks up the parent's
  1410. __path__. When this changes, the module's own path is recomputed,
  1411. using path_finder. For top-level modules, the parent module's path
  1412. is sys.path."""
  1413. def __init__(self, name, path, path_finder):
  1414. self._name = name
  1415. self._path = path
  1416. self._last_parent_path = tuple(self._get_parent_path())
  1417. self._path_finder = path_finder
  1418. def _find_parent_path_names(self):
  1419. """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
  1420. parent, dot, me = self._name.rpartition('.')
  1421. if dot == '':
  1422. # This is a top-level module. sys.path contains the parent path.
  1423. return 'sys', 'path'
  1424. # Not a top-level module. parent-module.__path__ contains the
  1425. # parent path.
  1426. return parent, '__path__'
  1427. def _get_parent_path(self):
  1428. parent_module_name, path_attr_name = self._find_parent_path_names()
  1429. return getattr(sys.modules[parent_module_name], path_attr_name)
  1430. def _recalculate(self):
  1431. # If the parent's path has changed, recalculate _path
  1432. parent_path = tuple(self._get_parent_path()) # Make a copy
  1433. if parent_path != self._last_parent_path:
  1434. spec = self._path_finder(self._name, parent_path)
  1435. # Note that no changes are made if a loader is returned, but we
  1436. # do remember the new parent path
  1437. if spec is not None and spec.loader is None:
  1438. if spec.submodule_search_locations:
  1439. self._path = spec.submodule_search_locations
  1440. self._last_parent_path = parent_path # Save the copy
  1441. return self._path
  1442. def __iter__(self):
  1443. return iter(self._recalculate())
  1444. def __len__(self):
  1445. return len(self._recalculate())
  1446. def __repr__(self):
  1447. return '_NamespacePath({!r})'.format(self._path)
  1448. def __contains__(self, item):
  1449. return item in self._recalculate()
  1450. def append(self, item):
  1451. self._path.append(item)
  1452. # We use this exclusively in init_module_attrs() for backward-compatibility.
  1453. class _NamespaceLoader:
  1454. def __init__(self, name, path, path_finder):
  1455. self._path = _NamespacePath(name, path, path_finder)
  1456. @classmethod
  1457. def module_repr(cls, module):
  1458. """Return repr for the module.
  1459. The method is deprecated. The import machinery does the job itself.
  1460. """
  1461. return '<module {!r} (namespace)>'.format(module.__name__)
  1462. def is_package(self, fullname):
  1463. return True
  1464. def get_source(self, fullname):
  1465. return ''
  1466. def get_code(self, fullname):
  1467. return compile('', '<string>', 'exec', dont_inherit=True)
  1468. def exec_module(self, module):
  1469. pass
  1470. def load_module(self, fullname):
  1471. """Load a namespace module.
  1472. This method is deprecated. Use exec_module() instead.
  1473. """
  1474. # The import system never calls this method.
  1475. _verbose_message('namespace module loaded with path {!r}', self._path)
  1476. return _load_module_shim(self, fullname)
  1477. # Finders #####################################################################
  1478. class PathFinder:
  1479. """Meta path finder for sys.path and package __path__ attributes."""
  1480. @classmethod
  1481. def invalidate_caches(cls):
  1482. """Call the invalidate_caches() method on all path entry finders
  1483. stored in sys.path_importer_caches (where implemented)."""
  1484. for finder in sys.path_importer_cache.values():
  1485. if hasattr(finder, 'invalidate_caches'):
  1486. finder.invalidate_caches()
  1487. @classmethod
  1488. def _path_hooks(cls, path):
  1489. """Search sequence of hooks for a finder for 'path'.
  1490. If 'hooks' is false then use sys.path_hooks.
  1491. """
  1492. if not sys.path_hooks:
  1493. _warnings.warn('sys.path_hooks is empty', ImportWarning)
  1494. for hook in sys.path_hooks:
  1495. try:
  1496. return hook(path)
  1497. except ImportError:
  1498. continue
  1499. else:
  1500. return None
  1501. @classmethod
  1502. def _path_importer_cache(cls, path):
  1503. """Get the finder for the path entry from sys.path_importer_cache.
  1504. If the path entry is not in the cache, find the appropriate finder
  1505. and cache it. If no finder is available, store None.
  1506. """
  1507. if path == '':
  1508. path = _os.getcwd()
  1509. try:
  1510. finder = sys.path_importer_cache[path]
  1511. except KeyError:
  1512. finder = cls._path_hooks(path)
  1513. sys.path_importer_cache[path] = finder
  1514. return finder
  1515. @classmethod
  1516. def _legacy_get_spec(cls, fullname, finder):
  1517. # This would be a good place for a DeprecationWarning if
  1518. # we ended up going that route.
  1519. if hasattr(finder, 'find_loader'):
  1520. loader, portions = finder.find_loader(fullname)
  1521. else:
  1522. loader = finder.find_module(fullname)
  1523. portions = []
  1524. if loader is not None:
  1525. return spec_from_loader(fullname, loader)
  1526. spec = ModuleSpec(fullname, None)
  1527. spec.submodule_search_locations = portions
  1528. return spec
  1529. @classmethod
  1530. def _get_spec(cls, fullname, path, target=None):
  1531. """Find the loader or namespace_path for this module/package name."""
  1532. # If this ends up being a namespace package, namespace_path is
  1533. # the list of paths that will become its __path__
  1534. namespace_path = []
  1535. for entry in path:
  1536. if not isinstance(entry, (str, bytes)):
  1537. continue
  1538. finder = cls._path_importer_cache(entry)
  1539. if finder is not None:
  1540. if hasattr(finder, 'find_spec'):
  1541. spec = finder.find_spec(fullname, target)
  1542. else:
  1543. spec = cls._legacy_get_spec(fullname, finder)
  1544. if spec is None:
  1545. continue
  1546. if spec.loader is not None:
  1547. return spec
  1548. portions = spec.submodule_search_locations
  1549. if portions is None:
  1550. raise ImportError('spec missing loader')
  1551. # This is possibly part of a namespace package.
  1552. # Remember these path entries (if any) for when we
  1553. # create a namespace package, and continue iterating
  1554. # on path.
  1555. namespace_path.extend(portions)
  1556. else:
  1557. spec = ModuleSpec(fullname, None)
  1558. spec.submodule_search_locations = namespace_path
  1559. return spec
  1560. @classmethod
  1561. def find_spec(cls, fullname, path=None, target=None):
  1562. """find the module on sys.path or 'path' based on sys.path_hooks and
  1563. sys.path_importer_cache."""
  1564. if path is None:
  1565. path = sys.path
  1566. spec = cls._get_spec(fullname, path, target)
  1567. if spec is None:
  1568. return None
  1569. elif spec.loader is None:
  1570. namespace_path = spec.submodule_search_locations
  1571. if namespace_path:
  1572. # We found at least one namespace path. Return a
  1573. # spec which can create the namespace package.
  1574. spec.origin = 'namespace'
  1575. spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
  1576. return spec
  1577. else:
  1578. return None
  1579. else:
  1580. return spec
  1581. @classmethod
  1582. def find_module(cls, fullname, path=None):
  1583. """find the module on sys.path or 'path' based on sys.path_hooks and
  1584. sys.path_importer_cache.
  1585. This method is deprecated. Use find_spec() instead.
  1586. """
  1587. spec = cls.find_spec(fullname, path)
  1588. if spec is None:
  1589. return None
  1590. return spec.loader
  1591. class FileFinder:
  1592. """File-based finder.
  1593. Interactions with the file system are cached for performance, being
  1594. refreshed when the directory the finder is handling has been modified.
  1595. """
  1596. def __init__(self, path, *loader_details):
  1597. """Initialize with the path to search on and a variable number of
  1598. 2-tuples containing the loader and the file suffixes the loader
  1599. recognizes."""
  1600. loaders = []
  1601. for loader, suffixes in loader_details:
  1602. loaders.extend((suffix, loader) for suffix in suffixes)
  1603. self._loaders = loaders
  1604. # Base (directory) path
  1605. self.path = path or '.'
  1606. self._path_mtime = -1
  1607. self._path_cache = set()
  1608. self._relaxed_path_cache = set()
  1609. def invalidate_caches(self):
  1610. """Invalidate the directory mtime."""
  1611. self._path_mtime = -1
  1612. find_module = _find_module_shim
  1613. def find_loader(self, fullname):
  1614. """Try to find a loader for the specified module, or the namespace
  1615. package portions. Returns (loader, list-of-portions).
  1616. This method is deprecated. Use find_spec() instead.
  1617. """
  1618. spec = self.find_spec(fullname)
  1619. if spec is None:
  1620. return None, []
  1621. return spec.loader, spec.submodule_search_locations or []
  1622. def _get_spec(self, loader_class, fullname, path, smsl, target):
  1623. loader = loader_class(fullname, path)
  1624. return spec_from_file_location(fullname, path, loader=loader,
  1625. submodule_search_locations=smsl)
  1626. def find_spec(self, fullname, target=None):
  1627. """Try to find a loader for the specified module, or the namespace
  1628. package portions. Returns (loader, list-of-portions)."""
  1629. is_namespace = False
  1630. tail_module = fullname.rpartition('.')[2]
  1631. try:
  1632. mtime = _path_stat(self.path or _os.getcwd()).st_mtime
  1633. except OSError:
  1634. mtime = -1
  1635. if mtime != self._path_mtime:
  1636. self._fill_cache()
  1637. self._path_mtime = mtime
  1638. # tail_module keeps the original casing, for __file__ and friends
  1639. if _relax_case():
  1640. cache = self._relaxed_path_cache
  1641. cache_module = tail_module.lower()
  1642. else:
  1643. cache = self._path_cache
  1644. cache_module = tail_module
  1645. # Check if the module is the name of a directory (and thus a package).
  1646. if cache_module in cache:
  1647. base_path = _path_join(self.path, tail_module)
  1648. for suffix, loader_class in self._loaders:
  1649. init_filename = '__init__' + suffix
  1650. full_path = _path_join(base_path, init_filename)
  1651. if _path_isfile(full_path):
  1652. return self._get_spec(loader_class, fullname, full_path, [base_path], target)
  1653. else:
  1654. # If a namespace package, return the path if we don't
  1655. # find a module in the next section.
  1656. is_namespace = _path_isdir(base_path)
  1657. # Check for a file w/ a proper suffix exists.
  1658. for suffix, loader_class in self._loaders:
  1659. full_path = _path_join(self.path, tail_module + suffix)
  1660. _verbose_message('trying {}'.format(full_path), verbosity=2)
  1661. if cache_module + suffix in cache:
  1662. if _path_isfile(full_path):
  1663. return self._get_spec(loader_class, fullname, full_path, None, target)
  1664. if is_namespace:
  1665. _verbose_message('possible namespace for {}'.format(base_path))
  1666. spec = ModuleSpec(fullname, None)
  1667. spec.submodule_search_locations = [base_path]
  1668. return spec
  1669. return None
  1670. def _fill_cache(self):
  1671. """Fill the cache of potential modules and packages for this directory."""
  1672. path = self.path
  1673. try:
  1674. contents = _os.listdir(path or _os.getcwd())
  1675. except (FileNotFoundError, PermissionError, NotADirectoryError):
  1676. # Directory has either been removed, turned into a file, or made
  1677. # unreadable.
  1678. contents = []
  1679. # We store two cached versions, to handle runtime changes of the
  1680. # PYTHONCASEOK environment variable.
  1681. if not sys.platform.startswith('win'):
  1682. self._path_cache = set(contents)
  1683. else:
  1684. # Windows users can import modules with case-insensitive file
  1685. # suffixes (for legacy reasons). Make the suffix lowercase here
  1686. # so it's done once instead of for every import. This is safe as
  1687. # the specified suffixes to check against are always specified in a
  1688. # case-sensitive manner.
  1689. lower_suffix_contents = set()
  1690. for item in contents:
  1691. name, dot, suffix = item.partition('.')
  1692. if dot:
  1693. new_name = '{}.{}'.format(name, suffix.lower())
  1694. else:
  1695. new_name = name
  1696. lower_suffix_contents.add(new_name)
  1697. self._path_cache = lower_suffix_contents
  1698. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  1699. self._relaxed_path_cache = {fn.lower() for fn in contents}
  1700. @classmethod
  1701. def path_hook(cls, *loader_details):
  1702. """A class method which returns a closure to use on sys.path_hook
  1703. which will return an instance using the specified loaders and the path
  1704. called on the closure.
  1705. If the path called on the closure is not a directory, ImportError is
  1706. raised.
  1707. """
  1708. def path_hook_for_FileFinder(path):
  1709. """Path hook for importlib.machinery.FileFinder."""
  1710. if not _path_isdir(path):
  1711. raise ImportError('only directories are supported', path=path)
  1712. return cls(path, *loader_details)
  1713. return path_hook_for_FileFinder
  1714. def __repr__(self):
  1715. return 'FileFinder({!r})'.format(self.path)
  1716. # Import itself ###############################################################
  1717. class _ImportLockContext:
  1718. """Context manager for the import lock."""
  1719. def __enter__(self):
  1720. """Acquire the import lock."""
  1721. _imp.acquire_lock()
  1722. def __exit__(self, exc_type, exc_value, exc_traceback):
  1723. """Release the import lock regardless of any raised exceptions."""
  1724. _imp.release_lock()
  1725. def _resolve_name(name, package, level):
  1726. """Resolve a relative module name to an absolute one."""
  1727. bits = package.rsplit('.', level - 1)
  1728. if len(bits) < level:
  1729. raise ValueError('attempted relative import beyond top-level package')
  1730. base = bits[0]
  1731. return '{}.{}'.format(base, name) if name else base
  1732. def _find_spec_legacy(finder, name, path):
  1733. # This would be a good place for a DeprecationWarning if
  1734. # we ended up going that route.
  1735. loader = finder.find_module(name, path)
  1736. if loader is None:
  1737. return None
  1738. return spec_from_loader(name, loader)
  1739. def _find_spec(name, path, target=None):
  1740. """Find a module's loader."""
  1741. if not sys.meta_path:
  1742. _warnings.warn('sys.meta_path is empty', ImportWarning)
  1743. # We check sys.modules here for the reload case. While a passed-in
  1744. # target will usually indicate a reload there is no guarantee, whereas
  1745. # sys.modules provides one.
  1746. is_reload = name in sys.modules
  1747. for finder in sys.meta_path:
  1748. with _ImportLockContext():
  1749. try:
  1750. find_spec = finder.find_spec
  1751. except AttributeError:
  1752. spec = _find_spec_legacy(finder, name, path)
  1753. if spec is None:
  1754. continue
  1755. else:
  1756. spec = find_spec(name, path, target)
  1757. if spec is not None:
  1758. # The parent import may have already imported this module.
  1759. if not is_reload and name in sys.modules:
  1760. module = sys.modules[name]
  1761. try:
  1762. __spec__ = module.__spec__
  1763. except AttributeError:
  1764. # We use the found spec since that is the one that
  1765. # we would have used if the parent module hadn't
  1766. # beaten us to the punch.
  1767. return spec
  1768. else:
  1769. if __spec__ is None:
  1770. return spec
  1771. else:
  1772. return __spec__
  1773. else:
  1774. return spec
  1775. else:
  1776. return None
  1777. def _sanity_check(name, package, level):
  1778. """Verify arguments are "sane"."""
  1779. if not isinstance(name, str):
  1780. raise TypeError('module name must be str, not {}'.format(type(name)))
  1781. if level < 0:
  1782. raise ValueError('level must be >= 0')
  1783. if package:
  1784. if not isinstance(package, str):
  1785. raise TypeError('__package__ not set to a string')
  1786. elif package not in sys.modules:
  1787. msg = ('Parent module {!r} not loaded, cannot perform relative '
  1788. 'import')
  1789. raise SystemError(msg.format(package))
  1790. if not name and level == 0:
  1791. raise ValueError('Empty module name')
  1792. _ERR_MSG_PREFIX = 'No module named '
  1793. _ERR_MSG = _ERR_MSG_PREFIX + '{!r}'
  1794. def _find_and_load_unlocked(name, import_):
  1795. path = None
  1796. parent = name.rpartition('.')[0]
  1797. if parent:
  1798. if parent not in sys.modules:
  1799. _call_with_frames_removed(import_, parent)
  1800. # Crazy side-effects!
  1801. if name in sys.modules:
  1802. return sys.modules[name]
  1803. parent_module = sys.modules[parent]
  1804. try:
  1805. path = parent_module.__path__
  1806. except AttributeError:
  1807. msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
  1808. raise ImportError(msg, name=name)
  1809. spec = _find_spec(name, path)
  1810. if spec is None:
  1811. raise ImportError(_ERR_MSG.format(name), name=name)
  1812. else:
  1813. module = _SpecMethods(spec)._load_unlocked()
  1814. if parent:
  1815. # Set the module as an attribute on its parent.
  1816. parent_module = sys.modules[parent]
  1817. setattr(parent_module, name.rpartition('.')[2], module)
  1818. return module
  1819. def _find_and_load(name, import_):
  1820. """Find and load the module, and release the import lock."""
  1821. with _ModuleLockManager(name):
  1822. return _find_and_load_unlocked(name, import_)
  1823. def _gcd_import(name, package=None, level=0):
  1824. """Import and return the module based on its name, the package the call is
  1825. being made from, and the level adjustment.
  1826. This function represents the greatest common denominator of functionality
  1827. between import_module and __import__. This includes setting __package__ if
  1828. the loader did not.
  1829. """
  1830. _sanity_check(name, package, level)
  1831. if level > 0:
  1832. name = _resolve_name(name, package, level)
  1833. _imp.acquire_lock()
  1834. if name not in sys.modules:
  1835. return _find_and_load(name, _gcd_import)
  1836. module = sys.modules[name]
  1837. if module is None:
  1838. _imp.release_lock()
  1839. message = ('import of {} halted; '
  1840. 'None in sys.modules'.format(name))
  1841. raise ImportError(message, name=name)
  1842. _lock_unlock_module(name)
  1843. return module
  1844. def _handle_fromlist(module, fromlist, import_):
  1845. """Figure out what __import__ should return.
  1846. The import_ parameter is a callable which takes the name of module to
  1847. import. It is required to decouple the function from assuming importlib's
  1848. import implementation is desired.
  1849. """
  1850. # The hell that is fromlist ...
  1851. # If a package was imported, try to import stuff from fromlist.
  1852. if hasattr(module, '__path__'):
  1853. if '*' in fromlist:
  1854. fromlist = list(fromlist)
  1855. fromlist.remove('*')
  1856. if hasattr(module, '__all__'):
  1857. fromlist.extend(module.__all__)
  1858. for x in fromlist:
  1859. if not hasattr(module, x):
  1860. from_name = '{}.{}'.format(module.__name__, x)
  1861. try:
  1862. _call_with_frames_removed(import_, from_name)
  1863. except ImportError as exc:
  1864. # Backwards-compatibility dictates we ignore failed
  1865. # imports triggered by fromlist for modules that don't
  1866. # exist.
  1867. if str(exc).startswith(_ERR_MSG_PREFIX):
  1868. if exc.name == from_name:
  1869. continue
  1870. raise
  1871. return module
  1872. def _calc___package__(globals):
  1873. """Calculate what __package__ should be.
  1874. __package__ is not guaranteed to be defined or could be set to None
  1875. to represent that its proper value is unknown.
  1876. """
  1877. package = globals.get('__package__')
  1878. if package is None:
  1879. package = globals['__name__']
  1880. if '__path__' not in globals:
  1881. package = package.rpartition('.')[0]
  1882. return package
  1883. def _get_supported_file_loaders():
  1884. """Returns a list of file-based module loaders.
  1885. Each item is a tuple (loader, suffixes).
  1886. """
  1887. extensions = ExtensionFileLoader, _imp.extension_suffixes()
  1888. source = SourceFileLoader, SOURCE_SUFFIXES
  1889. bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
  1890. return [extensions, source, bytecode]
  1891. def __import__(name, globals=None, locals=None, fromlist=(), level=0):
  1892. """Import a module.
  1893. The 'globals' argument is used to infer where the import is occuring from
  1894. to handle relative imports. The 'locals' argument is ignored. The
  1895. 'fromlist' argument specifies what should exist as attributes on the module
  1896. being imported (e.g. ``from module import <fromlist>``). The 'level'
  1897. argument represents the package location to import from in a relative
  1898. import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
  1899. """
  1900. if level == 0:
  1901. module = _gcd_import(name)
  1902. else:
  1903. globals_ = globals if globals is not None else {}
  1904. package = _calc___package__(globals_)
  1905. module = _gcd_import(name, package, level)
  1906. if not fromlist:
  1907. # Return up to the first dot in 'name'. This is complicated by the fact
  1908. # that 'name' may be relative.
  1909. if level == 0:
  1910. return _gcd_import(name.partition('.')[0])
  1911. elif not name:
  1912. return module
  1913. else:
  1914. # Figure out where to slice the module's name up to the first dot
  1915. # in 'name'.
  1916. cut_off = len(name) - len(name.partition('.')[0])
  1917. # Slice end needs to be positive to alleviate need to special-case
  1918. # when ``'.' not in name``.
  1919. return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  1920. else:
  1921. return _handle_fromlist(module, fromlist, _gcd_import)
  1922. def _builtin_from_name(name):
  1923. spec = BuiltinImporter.find_spec(name)
  1924. if spec is None:
  1925. raise ImportError('no built-in module named ' + name)
  1926. methods = _SpecMethods(spec)
  1927. return methods._load_unlocked()
  1928. def _setup(sys_module, _imp_module):
  1929. """Setup importlib by importing needed built-in modules and injecting them
  1930. into the global namespace.
  1931. As sys is needed for sys.modules access and _imp is needed to load built-in
  1932. modules, those two modules must be explicitly passed in.
  1933. """
  1934. global _imp, sys, BYTECODE_SUFFIXES
  1935. _imp = _imp_module
  1936. sys = sys_module
  1937. if sys.flags.optimize:
  1938. BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES
  1939. else:
  1940. BYTECODE_SUFFIXES = DEBUG_BYTECODE_SUFFIXES
  1941. # Set up the spec for existing builtin/frozen modules.
  1942. module_type = type(sys)
  1943. for name, module in sys.modules.items():
  1944. if isinstance(module, module_type):
  1945. if name in sys.builtin_module_names:
  1946. loader = BuiltinImporter
  1947. elif _imp.is_frozen(name):
  1948. loader = FrozenImporter
  1949. else:
  1950. continue
  1951. spec = _spec_from_module(module, loader)
  1952. methods = _SpecMethods(spec)
  1953. methods.init_module_attrs(module)
  1954. # Directly load built-in modules needed during bootstrap.
  1955. self_module = sys.modules[__name__]
  1956. for builtin_name in ('_io', '_warnings', 'builtins', 'marshal'):
  1957. if builtin_name not in sys.modules:
  1958. builtin_module = _builtin_from_name(builtin_name)
  1959. else:
  1960. builtin_module = sys.modules[builtin_name]
  1961. setattr(self_module, builtin_name, builtin_module)
  1962. # Directly load the os module (needed during bootstrap).
  1963. os_details = ('posix', ['/']), ('nt', ['\\', '/'])
  1964. for builtin_os, path_separators in os_details:
  1965. # Assumption made in _path_join()
  1966. assert all(len(sep) == 1 for sep in path_separators)
  1967. path_sep = path_separators[0]
  1968. if builtin_os in sys.modules:
  1969. os_module = sys.modules[builtin_os]
  1970. break
  1971. else:
  1972. try:
  1973. os_module = _builtin_from_name(builtin_os)
  1974. break
  1975. except ImportError:
  1976. continue
  1977. else:
  1978. raise ImportError('importlib requires posix or nt')
  1979. setattr(self_module, '_os', os_module)
  1980. setattr(self_module, 'path_sep', path_sep)
  1981. setattr(self_module, 'path_separators', ''.join(path_separators))
  1982. # Directly load the _thread module (needed during bootstrap).
  1983. try:
  1984. thread_module = _builtin_from_name('_thread')
  1985. except ImportError:
  1986. # Python was built without threads
  1987. thread_module = None
  1988. setattr(self_module, '_thread', thread_module)
  1989. # Directly load the _weakref module (needed during bootstrap).
  1990. weakref_module = _builtin_from_name('_weakref')
  1991. setattr(self_module, '_weakref', weakref_module)
  1992. # Directly load the winreg module (needed during bootstrap).
  1993. if builtin_os == 'nt':
  1994. winreg_module = _builtin_from_name('winreg')
  1995. setattr(self_module, '_winreg', winreg_module)
  1996. # Constants
  1997. setattr(self_module, '_relax_case', _make_relax_case())
  1998. EXTENSION_SUFFIXES.extend(_imp.extension_suffixes())
  1999. if builtin_os == 'nt':
  2000. SOURCE_SUFFIXES.append('.pyw')
  2001. if '_d.pyd' in EXTENSION_SUFFIXES:
  2002. WindowsRegistryFinder.DEBUG_BUILD = True
  2003. def _install(sys_module, _imp_module):
  2004. """Install importlib as the implementation of import."""
  2005. _setup(sys_module, _imp_module)
  2006. supported_loaders = _get_supported_file_loaders()
  2007. sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
  2008. sys.meta_path.append(BuiltinImporter)
  2009. sys.meta_path.append(FrozenImporter)
  2010. if _os.__name__ == 'nt':
  2011. sys.meta_path.append(WindowsRegistryFinder)
  2012. sys.meta_path.append(PathFinder)