abc.py 15 KB

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