abc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. """Abstract base classes related to import."""
  2. from . import _bootstrap
  3. from . import _bootstrap_external
  4. from . import machinery
  5. try:
  6. import _frozen_importlib
  7. except ImportError as exc:
  8. if exc.name != '_frozen_importlib':
  9. raise
  10. _frozen_importlib = None
  11. try:
  12. import _frozen_importlib_external
  13. except ImportError as exc:
  14. _frozen_importlib_external = _bootstrap_external
  15. import abc
  16. import warnings
  17. def _register(abstract_cls, *classes):
  18. for cls in classes:
  19. abstract_cls.register(cls)
  20. if _frozen_importlib is not None:
  21. try:
  22. frozen_cls = getattr(_frozen_importlib, cls.__name__)
  23. except AttributeError:
  24. frozen_cls = getattr(_frozen_importlib_external, cls.__name__)
  25. abstract_cls.register(frozen_cls)
  26. class Finder(metaclass=abc.ABCMeta):
  27. """Legacy abstract base class for import finders.
  28. It may be subclassed for compatibility with legacy third party
  29. reimplementations of the import system. Otherwise, finder
  30. implementations should derive from the more specific MetaPathFinder
  31. or PathEntryFinder ABCs.
  32. Deprecated since Python 3.3
  33. """
  34. @abc.abstractmethod
  35. def find_module(self, fullname, path=None):
  36. """An abstract method that should find a module.
  37. The fullname is a str and the optional path is a str or None.
  38. Returns a Loader object or None.
  39. """
  40. class MetaPathFinder(Finder):
  41. """Abstract base class for import finders on sys.meta_path."""
  42. # We don't define find_spec() here since that would break
  43. # hasattr checks we do to support backward compatibility.
  44. def find_module(self, fullname, path):
  45. """Return a loader for the module.
  46. If no module is found, return None. The fullname is a str and
  47. the path is a list of strings or None.
  48. This method is deprecated since Python 3.4 in favor of
  49. finder.find_spec(). If find_spec() exists then backwards-compatible
  50. functionality is provided for this method.
  51. """
  52. warnings.warn("MetaPathFinder.find_module() is deprecated since Python "
  53. "3.4 in favor of MetaPathFinder.find_spec() "
  54. "(available since 3.4)",
  55. DeprecationWarning,
  56. stacklevel=2)
  57. if not hasattr(self, 'find_spec'):
  58. return None
  59. found = self.find_spec(fullname, path)
  60. return found.loader if found is not None else None
  61. def invalidate_caches(self):
  62. """An optional method for clearing the finder's cache, if any.
  63. This method is used by importlib.invalidate_caches().
  64. """
  65. _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter,
  66. machinery.PathFinder, machinery.WindowsRegistryFinder)
  67. class PathEntryFinder(Finder):
  68. """Abstract base class for path entry finders used by PathFinder."""
  69. # We don't define find_spec() here since that would break
  70. # hasattr checks we do to support backward compatibility.
  71. def find_loader(self, fullname):
  72. """Return (loader, namespace portion) for the path entry.
  73. The fullname is a str. The namespace portion is a sequence of
  74. path entries contributing to part of a namespace package. The
  75. sequence may be empty. If loader is not None, the portion will
  76. be ignored.
  77. The portion will be discarded if another path entry finder
  78. locates the module as a normal module or package.
  79. This method is deprecated since Python 3.4 in favor of
  80. finder.find_spec(). If find_spec() is provided than backwards-compatible
  81. functionality is provided.
  82. """
  83. warnings.warn("PathEntryFinder.find_loader() is deprecated since Python "
  84. "3.4 in favor of PathEntryFinder.find_spec() "
  85. "(available since 3.4)",
  86. DeprecationWarning,
  87. stacklevel=2)
  88. if not hasattr(self, 'find_spec'):
  89. return None, []
  90. found = self.find_spec(fullname)
  91. if found is not None:
  92. if not found.submodule_search_locations:
  93. portions = []
  94. else:
  95. portions = found.submodule_search_locations
  96. return found.loader, portions
  97. else:
  98. return None, []
  99. find_module = _bootstrap_external._find_module_shim
  100. def invalidate_caches(self):
  101. """An optional method for clearing the finder's cache, if any.
  102. This method is used by PathFinder.invalidate_caches().
  103. """
  104. _register(PathEntryFinder, machinery.FileFinder)
  105. class Loader(metaclass=abc.ABCMeta):
  106. """Abstract base class for import loaders."""
  107. def create_module(self, spec):
  108. """Return a module to initialize and into which to load.
  109. This method should raise ImportError if anything prevents it
  110. from creating a new module. It may return None to indicate
  111. that the spec should create the new module.
  112. """
  113. # By default, defer to default semantics for the new module.
  114. return None
  115. # We don't define exec_module() here since that would break
  116. # hasattr checks we do to support backward compatibility.
  117. def load_module(self, fullname):
  118. """Return the loaded module.
  119. The module must be added to sys.modules and have import-related
  120. attributes set properly. The fullname is a str.
  121. ImportError is raised on failure.
  122. This method is deprecated in favor of loader.exec_module(). If
  123. exec_module() exists then it is used to provide a backwards-compatible
  124. functionality for this method.
  125. """
  126. if not hasattr(self, 'exec_module'):
  127. raise ImportError
  128. return _bootstrap._load_module_shim(self, fullname)
  129. def module_repr(self, module):
  130. """Return a module's repr.
  131. Used by the module type when the method does not raise
  132. NotImplementedError.
  133. This method is deprecated.
  134. """
  135. # The exception will cause ModuleType.__repr__ to ignore this method.
  136. raise NotImplementedError
  137. class ResourceLoader(Loader):
  138. """Abstract base class for loaders which can return data from their
  139. back-end storage.
  140. This ABC represents one of the optional protocols specified by PEP 302.
  141. """
  142. @abc.abstractmethod
  143. def get_data(self, path):
  144. """Abstract method which when implemented should return the bytes for
  145. the specified path. The path must be a str."""
  146. raise OSError
  147. class InspectLoader(Loader):
  148. """Abstract base class for loaders which support inspection about the
  149. modules they can load.
  150. This ABC represents one of the optional protocols specified by PEP 302.
  151. """
  152. def is_package(self, fullname):
  153. """Optional method which when implemented should return whether the
  154. module is a package. The fullname is a str. Returns a bool.
  155. Raises ImportError if the module cannot be found.
  156. """
  157. raise ImportError
  158. def get_code(self, fullname):
  159. """Method which returns the code object for the module.
  160. The fullname is a str. Returns a types.CodeType if possible, else
  161. returns None if a code object does not make sense
  162. (e.g. built-in module). Raises ImportError if the module cannot be
  163. found.
  164. """
  165. source = self.get_source(fullname)
  166. if source is None:
  167. return None
  168. return self.source_to_code(source)
  169. @abc.abstractmethod
  170. def get_source(self, fullname):
  171. """Abstract method which should return the source code for the
  172. module. The fullname is a str. Returns a str.
  173. Raises ImportError if the module cannot be found.
  174. """
  175. raise ImportError
  176. @staticmethod
  177. def source_to_code(data, path='<string>'):
  178. """Compile 'data' into a code object.
  179. The 'data' argument can be anything that compile() can handle. The'path'
  180. argument should be where the data was retrieved (when applicable)."""
  181. return compile(data, path, 'exec', dont_inherit=True)
  182. exec_module = _bootstrap_external._LoaderBasics.exec_module
  183. load_module = _bootstrap_external._LoaderBasics.load_module
  184. _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter)
  185. class ExecutionLoader(InspectLoader):
  186. """Abstract base class for loaders that wish to support the execution of
  187. modules as scripts.
  188. This ABC represents one of the optional protocols specified in PEP 302.
  189. """
  190. @abc.abstractmethod
  191. def get_filename(self, fullname):
  192. """Abstract method which should return the value that __file__ is to be
  193. set to.
  194. Raises ImportError if the module cannot be found.
  195. """
  196. raise ImportError
  197. def get_code(self, fullname):
  198. """Method to return the code object for fullname.
  199. Should return None if not applicable (e.g. built-in module).
  200. Raise ImportError if the module cannot be found.
  201. """
  202. source = self.get_source(fullname)
  203. if source is None:
  204. return None
  205. try:
  206. path = self.get_filename(fullname)
  207. except ImportError:
  208. return self.source_to_code(source)
  209. else:
  210. return self.source_to_code(source, path)
  211. _register(ExecutionLoader, machinery.ExtensionFileLoader)
  212. class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader):
  213. """Abstract base class partially implementing the ResourceLoader and
  214. ExecutionLoader ABCs."""
  215. _register(FileLoader, machinery.SourceFileLoader,
  216. machinery.SourcelessFileLoader)
  217. class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader):
  218. """Abstract base class for loading source code (and optionally any
  219. corresponding bytecode).
  220. To support loading from source code, the abstractmethods inherited from
  221. ResourceLoader and ExecutionLoader need to be implemented. To also support
  222. loading from bytecode, the optional methods specified directly by this ABC
  223. is required.
  224. Inherited abstractmethods not implemented in this ABC:
  225. * ResourceLoader.get_data
  226. * ExecutionLoader.get_filename
  227. """
  228. def path_mtime(self, path):
  229. """Return the (int) modification time for the path (str)."""
  230. if self.path_stats.__func__ is SourceLoader.path_stats:
  231. raise OSError
  232. return int(self.path_stats(path)['mtime'])
  233. def path_stats(self, path):
  234. """Return a metadata dict for the source pointed to by the path (str).
  235. Possible keys:
  236. - 'mtime' (mandatory) is the numeric timestamp of last source
  237. code modification;
  238. - 'size' (optional) is the size in bytes of the source code.
  239. """
  240. if self.path_mtime.__func__ is SourceLoader.path_mtime:
  241. raise OSError
  242. return {'mtime': self.path_mtime(path)}
  243. def set_data(self, path, data):
  244. """Write the bytes to the path (if possible).
  245. Accepts a str path and data as bytes.
  246. Any needed intermediary directories are to be created. If for some
  247. reason the file cannot be written because of permissions, fail
  248. silently.
  249. """
  250. _register(SourceLoader, machinery.SourceFileLoader)
  251. class ResourceReader(metaclass=abc.ABCMeta):
  252. """Abstract base class to provide resource-reading support.
  253. Loaders that support resource reading are expected to implement
  254. the ``get_resource_reader(fullname)`` method and have it either return None
  255. or an object compatible with this ABC.
  256. """
  257. @abc.abstractmethod
  258. def open_resource(self, resource):
  259. """Return an opened, file-like object for binary reading.
  260. The 'resource' argument is expected to represent only a file name
  261. and thus not contain any subdirectory components.
  262. If the resource cannot be found, FileNotFoundError is raised.
  263. """
  264. raise FileNotFoundError
  265. @abc.abstractmethod
  266. def resource_path(self, resource):
  267. """Return the file system path to the specified resource.
  268. The 'resource' argument is expected to represent only a file name
  269. and thus not contain any subdirectory components.
  270. If the resource does not exist on the file system, raise
  271. FileNotFoundError.
  272. """
  273. raise FileNotFoundError
  274. @abc.abstractmethod
  275. def is_resource(self, name):
  276. """Return True if the named 'name' is consider a resource."""
  277. raise FileNotFoundError
  278. @abc.abstractmethod
  279. def contents(self):
  280. """Return an iterable of strings over the contents of the package."""
  281. return []
  282. _register(ResourceReader, machinery.SourceFileLoader)