imp.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. """This module provides the components needed to build your own __import__
  2. function. Undocumented functions are obsolete.
  3. In most cases it is preferred you consider using the importlib module's
  4. functionality over this module.
  5. """
  6. # (Probably) need to stay in _imp
  7. from _imp import (lock_held, acquire_lock, release_lock,
  8. get_frozen_object, is_frozen_package,
  9. init_frozen, is_builtin, is_frozen,
  10. _fix_co_filename)
  11. try:
  12. from _imp import create_dynamic
  13. except ImportError:
  14. # Platform doesn't support dynamic loading.
  15. create_dynamic = None
  16. from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
  17. from importlib._bootstrap_external import SourcelessFileLoader
  18. from importlib import machinery
  19. from importlib import util
  20. import importlib
  21. import os
  22. import sys
  23. import tokenize
  24. import types
  25. import warnings
  26. warnings.warn("the imp module is deprecated in favour of importlib; "
  27. "see the module's documentation for alternative uses",
  28. DeprecationWarning, stacklevel=2)
  29. # DEPRECATED
  30. SEARCH_ERROR = 0
  31. PY_SOURCE = 1
  32. PY_COMPILED = 2
  33. C_EXTENSION = 3
  34. PY_RESOURCE = 4
  35. PKG_DIRECTORY = 5
  36. C_BUILTIN = 6
  37. PY_FROZEN = 7
  38. PY_CODERESOURCE = 8
  39. IMP_HOOK = 9
  40. def new_module(name):
  41. """**DEPRECATED**
  42. Create a new module.
  43. The module is not entered into sys.modules.
  44. """
  45. return types.ModuleType(name)
  46. def get_magic():
  47. """**DEPRECATED**
  48. Return the magic number for .pyc files.
  49. """
  50. return util.MAGIC_NUMBER
  51. def get_tag():
  52. """Return the magic tag for .pyc files."""
  53. return sys.implementation.cache_tag
  54. def cache_from_source(path, debug_override=None):
  55. """**DEPRECATED**
  56. Given the path to a .py file, return the path to its .pyc file.
  57. The .py file does not need to exist; this simply returns the path to the
  58. .pyc file calculated as if the .py file were imported.
  59. If debug_override is not None, then it must be a boolean and is used in
  60. place of sys.flags.optimize.
  61. If sys.implementation.cache_tag is None then NotImplementedError is raised.
  62. """
  63. with warnings.catch_warnings():
  64. warnings.simplefilter('ignore')
  65. return util.cache_from_source(path, debug_override)
  66. def source_from_cache(path):
  67. """**DEPRECATED**
  68. Given the path to a .pyc. file, return the path to its .py file.
  69. The .pyc file does not need to exist; this simply returns the path to
  70. the .py file calculated to correspond to the .pyc file. If path does
  71. not conform to PEP 3147 format, ValueError will be raised. If
  72. sys.implementation.cache_tag is None then NotImplementedError is raised.
  73. """
  74. return util.source_from_cache(path)
  75. def get_suffixes():
  76. """**DEPRECATED**"""
  77. extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
  78. source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
  79. bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
  80. return extensions + source + bytecode
  81. class NullImporter:
  82. """**DEPRECATED**
  83. Null import object.
  84. """
  85. def __init__(self, path):
  86. if path == '':
  87. raise ImportError('empty pathname', path='')
  88. elif os.path.isdir(path):
  89. raise ImportError('existing directory', path=path)
  90. def find_module(self, fullname):
  91. """Always returns None."""
  92. return None
  93. class _HackedGetData:
  94. """Compatibility support for 'file' arguments of various load_*()
  95. functions."""
  96. def __init__(self, fullname, path, file=None):
  97. super().__init__(fullname, path)
  98. self.file = file
  99. def get_data(self, path):
  100. """Gross hack to contort loader to deal w/ load_*()'s bad API."""
  101. if self.file and path == self.path:
  102. # The contract of get_data() requires us to return bytes. Reopen the
  103. # file in binary mode if needed.
  104. if not self.file.closed:
  105. file = self.file
  106. if 'b' not in file.mode:
  107. file.close()
  108. if self.file.closed:
  109. self.file = file = open(self.path, 'rb')
  110. with file:
  111. return file.read()
  112. else:
  113. return super().get_data(path)
  114. class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
  115. """Compatibility support for implementing load_source()."""
  116. def load_source(name, pathname, file=None):
  117. loader = _LoadSourceCompatibility(name, pathname, file)
  118. spec = util.spec_from_file_location(name, pathname, loader=loader)
  119. if name in sys.modules:
  120. module = _exec(spec, sys.modules[name])
  121. else:
  122. module = _load(spec)
  123. # To allow reloading to potentially work, use a non-hacked loader which
  124. # won't rely on a now-closed file object.
  125. module.__loader__ = machinery.SourceFileLoader(name, pathname)
  126. module.__spec__.loader = module.__loader__
  127. return module
  128. class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
  129. """Compatibility support for implementing load_compiled()."""
  130. def load_compiled(name, pathname, file=None):
  131. """**DEPRECATED**"""
  132. loader = _LoadCompiledCompatibility(name, pathname, file)
  133. spec = util.spec_from_file_location(name, pathname, loader=loader)
  134. if name in sys.modules:
  135. module = _exec(spec, sys.modules[name])
  136. else:
  137. module = _load(spec)
  138. # To allow reloading to potentially work, use a non-hacked loader which
  139. # won't rely on a now-closed file object.
  140. module.__loader__ = SourcelessFileLoader(name, pathname)
  141. module.__spec__.loader = module.__loader__
  142. return module
  143. def load_package(name, path):
  144. """**DEPRECATED**"""
  145. if os.path.isdir(path):
  146. extensions = (machinery.SOURCE_SUFFIXES[:] +
  147. machinery.BYTECODE_SUFFIXES[:])
  148. for extension in extensions:
  149. init_path = os.path.join(path, '__init__' + extension)
  150. if os.path.exists(init_path):
  151. path = init_path
  152. break
  153. else:
  154. raise ValueError('{!r} is not a package'.format(path))
  155. spec = util.spec_from_file_location(name, path,
  156. submodule_search_locations=[])
  157. if name in sys.modules:
  158. return _exec(spec, sys.modules[name])
  159. else:
  160. return _load(spec)
  161. def load_module(name, file, filename, details):
  162. """**DEPRECATED**
  163. Load a module, given information returned by find_module().
  164. The module name must include the full package name, if any.
  165. """
  166. suffix, mode, type_ = details
  167. if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
  168. raise ValueError('invalid file open mode {!r}'.format(mode))
  169. elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
  170. msg = 'file object required for import (type code {})'.format(type_)
  171. raise ValueError(msg)
  172. elif type_ == PY_SOURCE:
  173. return load_source(name, filename, file)
  174. elif type_ == PY_COMPILED:
  175. return load_compiled(name, filename, file)
  176. elif type_ == C_EXTENSION and load_dynamic is not None:
  177. if file is None:
  178. with open(filename, 'rb') as opened_file:
  179. return load_dynamic(name, filename, opened_file)
  180. else:
  181. return load_dynamic(name, filename, file)
  182. elif type_ == PKG_DIRECTORY:
  183. return load_package(name, filename)
  184. elif type_ == C_BUILTIN:
  185. return init_builtin(name)
  186. elif type_ == PY_FROZEN:
  187. return init_frozen(name)
  188. else:
  189. msg = "Don't know how to import {} (type code {})".format(name, type_)
  190. raise ImportError(msg, name=name)
  191. def find_module(name, path=None):
  192. """**DEPRECATED**
  193. Search for a module.
  194. If path is omitted or None, search for a built-in, frozen or special
  195. module and continue search in sys.path. The module name cannot
  196. contain '.'; to search for a submodule of a package, pass the
  197. submodule name and the package's __path__.
  198. """
  199. if not isinstance(name, str):
  200. raise TypeError("'name' must be a str, not {}".format(type(name)))
  201. elif not isinstance(path, (type(None), list)):
  202. # Backwards-compatibility
  203. raise RuntimeError("'path' must be None or a list, "
  204. "not {}".format(type(path)))
  205. if path is None:
  206. if is_builtin(name):
  207. return None, None, ('', '', C_BUILTIN)
  208. elif is_frozen(name):
  209. return None, None, ('', '', PY_FROZEN)
  210. else:
  211. path = sys.path
  212. for entry in path:
  213. package_directory = os.path.join(entry, name)
  214. for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
  215. package_file_name = '__init__' + suffix
  216. file_path = os.path.join(package_directory, package_file_name)
  217. if os.path.isfile(file_path):
  218. return None, package_directory, ('', '', PKG_DIRECTORY)
  219. for suffix, mode, type_ in get_suffixes():
  220. file_name = name + suffix
  221. file_path = os.path.join(entry, file_name)
  222. if os.path.isfile(file_path):
  223. break
  224. else:
  225. continue
  226. break # Break out of outer loop when breaking out of inner loop.
  227. else:
  228. raise ImportError(_ERR_MSG.format(name), name=name)
  229. encoding = None
  230. if 'b' not in mode:
  231. with open(file_path, 'rb') as file:
  232. encoding = tokenize.detect_encoding(file.readline)[0]
  233. file = open(file_path, mode, encoding=encoding)
  234. return file, file_path, (suffix, mode, type_)
  235. def reload(module):
  236. """**DEPRECATED**
  237. Reload the module and return it.
  238. The module must have been successfully imported before.
  239. """
  240. return importlib.reload(module)
  241. def init_builtin(name):
  242. """**DEPRECATED**
  243. Load and return a built-in module by name, or None is such module doesn't
  244. exist
  245. """
  246. try:
  247. return _builtin_from_name(name)
  248. except ImportError:
  249. return None
  250. if create_dynamic:
  251. def load_dynamic(name, path, file=None):
  252. """**DEPRECATED**
  253. Load an extension module.
  254. """
  255. import importlib.machinery
  256. loader = importlib.machinery.ExtensionFileLoader(name, path)
  257. # Issue #24748: Skip the sys.modules check in _load_module_shim;
  258. # always load new extension
  259. spec = importlib.machinery.ModuleSpec(
  260. name=name, loader=loader, origin=path)
  261. return _load(spec)
  262. else:
  263. load_dynamic = None