PageRenderTime 24ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/kbe/res/scripts/common/Lib/importlib/abc.py

https://bitbucket.org/kbengine/kbengine
Python | 304 lines | 192 code | 32 blank | 80 comment | 0 complexity | b6029558eb7acaaef34eddbcbcca0dd6 MD5 | raw file
  1. """Abstract base classes related to import."""
  2. from . import _bootstrap
  3. from . import machinery
  4. from . import util
  5. import abc
  6. import imp
  7. import io
  8. import marshal
  9. import os.path
  10. import sys
  11. import tokenize
  12. import types
  13. import warnings
  14. class Loader(metaclass=abc.ABCMeta):
  15. """Abstract base class for import loaders."""
  16. @abc.abstractmethod
  17. def load_module(self, fullname):
  18. """Abstract method which when implemented should load a module.
  19. The fullname is a str."""
  20. raise NotImplementedError
  21. class Finder(metaclass=abc.ABCMeta):
  22. """Abstract base class for import finders."""
  23. @abc.abstractmethod
  24. def find_module(self, fullname, path=None):
  25. """Abstract method which when implemented should find a module.
  26. The fullname is a str and the optional path is a str or None.
  27. Returns a Loader object.
  28. """
  29. raise NotImplementedError
  30. Finder.register(machinery.BuiltinImporter)
  31. Finder.register(machinery.FrozenImporter)
  32. Finder.register(machinery.PathFinder)
  33. class ResourceLoader(Loader):
  34. """Abstract base class for loaders which can return data from their
  35. back-end storage.
  36. This ABC represents one of the optional protocols specified by PEP 302.
  37. """
  38. @abc.abstractmethod
  39. def get_data(self, path):
  40. """Abstract method which when implemented should return the bytes for
  41. the specified path. The path must be a str."""
  42. raise NotImplementedError
  43. class InspectLoader(Loader):
  44. """Abstract base class for loaders which support inspection about the
  45. modules they can load.
  46. This ABC represents one of the optional protocols specified by PEP 302.
  47. """
  48. @abc.abstractmethod
  49. def is_package(self, fullname):
  50. """Abstract method which when implemented should return whether the
  51. module is a package. The fullname is a str. Returns a bool."""
  52. raise NotImplementedError
  53. @abc.abstractmethod
  54. def get_code(self, fullname):
  55. """Abstract method which when implemented should return the code object
  56. for the module. The fullname is a str. Returns a types.CodeType."""
  57. raise NotImplementedError
  58. @abc.abstractmethod
  59. def get_source(self, fullname):
  60. """Abstract method which should return the source code for the
  61. module. The fullname is a str. Returns a str."""
  62. raise NotImplementedError
  63. InspectLoader.register(machinery.BuiltinImporter)
  64. InspectLoader.register(machinery.FrozenImporter)
  65. class ExecutionLoader(InspectLoader):
  66. """Abstract base class for loaders that wish to support the execution of
  67. modules as scripts.
  68. This ABC represents one of the optional protocols specified in PEP 302.
  69. """
  70. @abc.abstractmethod
  71. def get_filename(self, fullname):
  72. """Abstract method which should return the value that __file__ is to be
  73. set to."""
  74. raise NotImplementedError
  75. class SourceLoader(_bootstrap.SourceLoader, ResourceLoader, ExecutionLoader):
  76. """Abstract base class for loading source code (and optionally any
  77. corresponding bytecode).
  78. To support loading from source code, the abstractmethods inherited from
  79. ResourceLoader and ExecutionLoader need to be implemented. To also support
  80. loading from bytecode, the optional methods specified directly by this ABC
  81. is required.
  82. Inherited abstractmethods not implemented in this ABC:
  83. * ResourceLoader.get_data
  84. * ExecutionLoader.get_filename
  85. """
  86. def path_mtime(self, path):
  87. """Return the (int) modification time for the path (str)."""
  88. raise NotImplementedError
  89. def set_data(self, path, data):
  90. """Write the bytes to the path (if possible).
  91. Accepts a str path and data as bytes.
  92. Any needed intermediary directories are to be created. If for some
  93. reason the file cannot be written because of permissions, fail
  94. silently.
  95. """
  96. raise NotImplementedError
  97. class PyLoader(SourceLoader):
  98. """Implement the deprecated PyLoader ABC in terms of SourceLoader.
  99. This class has been deprecated! It is slated for removal in Python 3.4.
  100. If compatibility with Python 3.1 is not needed then implement the
  101. SourceLoader ABC instead of this class. If Python 3.1 compatibility is
  102. needed, then use the following idiom to have a single class that is
  103. compatible with Python 3.1 onwards::
  104. try:
  105. from importlib.abc import SourceLoader
  106. except ImportError:
  107. from importlib.abc import PyLoader as SourceLoader
  108. class CustomLoader(SourceLoader):
  109. def get_filename(self, fullname):
  110. # Implement ...
  111. def source_path(self, fullname):
  112. '''Implement source_path in terms of get_filename.'''
  113. try:
  114. return self.get_filename(fullname)
  115. except ImportError:
  116. return None
  117. def is_package(self, fullname):
  118. filename = os.path.basename(self.get_filename(fullname))
  119. return os.path.splitext(filename)[0] == '__init__'
  120. """
  121. @abc.abstractmethod
  122. def is_package(self, fullname):
  123. raise NotImplementedError
  124. @abc.abstractmethod
  125. def source_path(self, fullname):
  126. """Abstract method. Accepts a str module name and returns the path to
  127. the source code for the module."""
  128. raise NotImplementedError
  129. def get_filename(self, fullname):
  130. """Implement get_filename in terms of source_path.
  131. As get_filename should only return a source file path there is no
  132. chance of the path not existing but loading still being possible, so
  133. ImportError should propagate instead of being turned into returning
  134. None.
  135. """
  136. warnings.warn("importlib.abc.PyLoader is deprecated and is "
  137. "slated for removal in Python 3.4; "
  138. "use SourceLoader instead. "
  139. "See the importlib documentation on how to be "
  140. "compatible with Python 3.1 onwards.",
  141. PendingDeprecationWarning)
  142. path = self.source_path(fullname)
  143. if path is None:
  144. raise ImportError
  145. else:
  146. return path
  147. class PyPycLoader(PyLoader):
  148. """Abstract base class to assist in loading source and bytecode by
  149. requiring only back-end storage methods to be implemented.
  150. This class has been deprecated! Removal is slated for Python 3.4. Implement
  151. the SourceLoader ABC instead. If Python 3.1 compatibility is needed, see
  152. PyLoader.
  153. The methods get_code, get_source, and load_module are implemented for the
  154. user.
  155. """
  156. def get_filename(self, fullname):
  157. """Return the source or bytecode file path."""
  158. path = self.source_path(fullname)
  159. if path is not None:
  160. return path
  161. path = self.bytecode_path(fullname)
  162. if path is not None:
  163. return path
  164. raise ImportError("no source or bytecode path available for "
  165. "{0!r}".format(fullname))
  166. def get_code(self, fullname):
  167. """Get a code object from source or bytecode."""
  168. warnings.warn("importlib.abc.PyPycLoader is deprecated and slated for "
  169. "removal in Python 3.4; use SourceLoader instead. "
  170. "If Python 3.1 compatibility is required, see the "
  171. "latest documentation for PyLoader.",
  172. PendingDeprecationWarning)
  173. source_timestamp = self.source_mtime(fullname)
  174. # Try to use bytecode if it is available.
  175. bytecode_path = self.bytecode_path(fullname)
  176. if bytecode_path:
  177. data = self.get_data(bytecode_path)
  178. try:
  179. magic = data[:4]
  180. if len(magic) < 4:
  181. raise ImportError("bad magic number in {}".format(fullname))
  182. raw_timestamp = data[4:8]
  183. if len(raw_timestamp) < 4:
  184. raise EOFError("bad timestamp in {}".format(fullname))
  185. pyc_timestamp = marshal._r_long(raw_timestamp)
  186. bytecode = data[8:]
  187. # Verify that the magic number is valid.
  188. if imp.get_magic() != magic:
  189. raise ImportError("bad magic number in {}".format(fullname))
  190. # Verify that the bytecode is not stale (only matters when
  191. # there is source to fall back on.
  192. if source_timestamp:
  193. if pyc_timestamp < source_timestamp:
  194. raise ImportError("bytecode is stale")
  195. except (ImportError, EOFError):
  196. # If source is available give it a shot.
  197. if source_timestamp is not None:
  198. pass
  199. else:
  200. raise
  201. else:
  202. # Bytecode seems fine, so try to use it.
  203. return marshal.loads(bytecode)
  204. elif source_timestamp is None:
  205. raise ImportError("no source or bytecode available to create code "
  206. "object for {0!r}".format(fullname))
  207. # Use the source.
  208. source_path = self.source_path(fullname)
  209. if source_path is None:
  210. message = "a source path must exist to load {0}".format(fullname)
  211. raise ImportError(message)
  212. source = self.get_data(source_path)
  213. code_object = compile(source, source_path, 'exec', dont_inherit=True)
  214. # Generate bytecode and write it out.
  215. if not sys.dont_write_bytecode:
  216. data = bytearray(imp.get_magic())
  217. data.extend(marshal._w_long(source_timestamp))
  218. data.extend(marshal.dumps(code_object))
  219. self.write_bytecode(fullname, data)
  220. return code_object
  221. @abc.abstractmethod
  222. def source_mtime(self, fullname):
  223. """Abstract method. Accepts a str filename and returns an int
  224. modification time for the source of the module."""
  225. raise NotImplementedError
  226. @abc.abstractmethod
  227. def bytecode_path(self, fullname):
  228. """Abstract method. Accepts a str filename and returns the str pathname
  229. to the bytecode for the module."""
  230. raise NotImplementedError
  231. @abc.abstractmethod
  232. def write_bytecode(self, fullname, bytecode):
  233. """Abstract method. Accepts a str filename and bytes object
  234. representing the bytecode for the module. Returns a boolean
  235. representing whether the bytecode was written or not."""
  236. raise NotImplementedError