PageRenderTime 25ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/imp.py

https://gitlab.com/areema/myproject
Python | 345 lines | 266 code | 23 blank | 56 comment | 6 complexity | 8a869959375b83bce053abecaea2a5aa MD5 | raw file
  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. PendingDeprecationWarning, 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. if not self.file.closed:
  103. file = self.file
  104. else:
  105. self.file = file = open(self.path, 'r')
  106. with file:
  107. # Technically should be returning bytes, but
  108. # SourceLoader.get_code() just passed what is returned to
  109. # compile() which can handle str. And converting to bytes would
  110. # require figuring out the encoding to decode to and
  111. # tokenize.detect_encoding() only accepts bytes.
  112. return file.read()
  113. else:
  114. return super().get_data(path)
  115. class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
  116. """Compatibility support for implementing load_source()."""
  117. def load_source(name, pathname, file=None):
  118. loader = _LoadSourceCompatibility(name, pathname, file)
  119. spec = util.spec_from_file_location(name, pathname, loader=loader)
  120. if name in sys.modules:
  121. module = _exec(spec, sys.modules[name])
  122. else:
  123. module = _load(spec)
  124. # To allow reloading to potentially work, use a non-hacked loader which
  125. # won't rely on a now-closed file object.
  126. module.__loader__ = machinery.SourceFileLoader(name, pathname)
  127. module.__spec__.loader = module.__loader__
  128. return module
  129. class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
  130. """Compatibility support for implementing load_compiled()."""
  131. def load_compiled(name, pathname, file=None):
  132. """**DEPRECATED**"""
  133. loader = _LoadCompiledCompatibility(name, pathname, file)
  134. spec = util.spec_from_file_location(name, pathname, loader=loader)
  135. if name in sys.modules:
  136. module = _exec(spec, sys.modules[name])
  137. else:
  138. module = _load(spec)
  139. # To allow reloading to potentially work, use a non-hacked loader which
  140. # won't rely on a now-closed file object.
  141. module.__loader__ = SourcelessFileLoader(name, pathname)
  142. module.__spec__.loader = module.__loader__
  143. return module
  144. def load_package(name, path):
  145. """**DEPRECATED**"""
  146. if os.path.isdir(path):
  147. extensions = (machinery.SOURCE_SUFFIXES[:] +
  148. machinery.BYTECODE_SUFFIXES[:])
  149. for extension in extensions:
  150. path = os.path.join(path, '__init__'+extension)
  151. if os.path.exists(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("'list' must be None or a list, "
  204. "not {}".format(type(name)))
  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