Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 1 | """Abstract base classes related to import.""" |
Eric Snow | 183a941 | 2015-05-15 21:54:59 -0600 | [diff] [blame] | 2 | from . import _bootstrap |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 3 | from . import _bootstrap_external |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 4 | from . import machinery |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 5 | try: |
| 6 | import _frozen_importlib |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 7 | except ImportError as exc: |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 8 | if exc.name != '_frozen_importlib': |
| 9 | raise |
| 10 | _frozen_importlib = None |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 11 | try: |
| 12 | import _frozen_importlib_external |
Pablo Galindo | 293dd23 | 2019-11-19 21:34:03 +0000 | [diff] [blame] | 13 | except ImportError: |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 14 | _frozen_importlib_external = _bootstrap_external |
Victor Stinner | 9e09849 | 2020-06-17 23:15:59 +0200 | [diff] [blame^] | 15 | from ._abc import Loader |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 16 | import abc |
Matthias Bussonnier | 1d4601c | 2017-02-15 18:00:32 -0800 | [diff] [blame] | 17 | import warnings |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 18 | from typing import Protocol, runtime_checkable |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 19 | |
| 20 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 21 | def _register(abstract_cls, *classes): |
| 22 | for cls in classes: |
| 23 | abstract_cls.register(cls) |
| 24 | if _frozen_importlib is not None: |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 25 | try: |
| 26 | frozen_cls = getattr(_frozen_importlib, cls.__name__) |
| 27 | except AttributeError: |
| 28 | frozen_cls = getattr(_frozen_importlib_external, cls.__name__) |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 29 | abstract_cls.register(frozen_cls) |
| 30 | |
| 31 | |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 32 | class Finder(metaclass=abc.ABCMeta): |
| 33 | |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 34 | """Legacy abstract base class for import finders. |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 35 | |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 36 | It may be subclassed for compatibility with legacy third party |
| 37 | reimplementations of the import system. Otherwise, finder |
| 38 | implementations should derive from the more specific MetaPathFinder |
| 39 | or PathEntryFinder ABCs. |
Matthias Bussonnier | 1d4601c | 2017-02-15 18:00:32 -0800 | [diff] [blame] | 40 | |
| 41 | Deprecated since Python 3.3 |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 42 | """ |
| 43 | |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 44 | @abc.abstractmethod |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 45 | def find_module(self, fullname, path=None): |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 46 | """An abstract method that should find a module. |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 47 | The fullname is a str and the optional path is a str or None. |
Brett Cannon | 100883f | 2013-04-09 16:59:39 -0400 | [diff] [blame] | 48 | Returns a Loader object or None. |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 49 | """ |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 50 | |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 51 | |
| 52 | class MetaPathFinder(Finder): |
| 53 | |
| 54 | """Abstract base class for import finders on sys.meta_path.""" |
| 55 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 56 | # We don't define find_spec() here since that would break |
| 57 | # hasattr checks we do to support backward compatibility. |
| 58 | |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 59 | def find_module(self, fullname, path): |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 60 | """Return a loader for the module. |
| 61 | |
| 62 | If no module is found, return None. The fullname is a str and |
| 63 | the path is a list of strings or None. |
| 64 | |
Matthias Bussonnier | 1d4601c | 2017-02-15 18:00:32 -0800 | [diff] [blame] | 65 | This method is deprecated since Python 3.4 in favor of |
| 66 | finder.find_spec(). If find_spec() exists then backwards-compatible |
| 67 | functionality is provided for this method. |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 68 | |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 69 | """ |
Matthias Bussonnier | 1d4601c | 2017-02-15 18:00:32 -0800 | [diff] [blame] | 70 | warnings.warn("MetaPathFinder.find_module() is deprecated since Python " |
Serhiy Storchaka | 34fd4c2 | 2018-11-05 16:20:25 +0200 | [diff] [blame] | 71 | "3.4 in favor of MetaPathFinder.find_spec() " |
Matthias Bussonnier | 1d4601c | 2017-02-15 18:00:32 -0800 | [diff] [blame] | 72 | "(available since 3.4)", |
| 73 | DeprecationWarning, |
| 74 | stacklevel=2) |
Brett Cannon | 8d94229 | 2014-01-07 15:52:42 -0500 | [diff] [blame] | 75 | if not hasattr(self, 'find_spec'): |
| 76 | return None |
| 77 | found = self.find_spec(fullname, path) |
| 78 | return found.loader if found is not None else None |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 79 | |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 80 | def invalidate_caches(self): |
| 81 | """An optional method for clearing the finder's cache, if any. |
| 82 | This method is used by importlib.invalidate_caches(). |
| 83 | """ |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 84 | |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 85 | _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, |
Nick Coghlan | ff79486 | 2012-08-02 21:45:24 +1000 | [diff] [blame] | 86 | machinery.PathFinder, machinery.WindowsRegistryFinder) |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 87 | |
| 88 | |
| 89 | class PathEntryFinder(Finder): |
| 90 | |
| 91 | """Abstract base class for path entry finders used by PathFinder.""" |
| 92 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 93 | # We don't define find_spec() here since that would break |
| 94 | # hasattr checks we do to support backward compatibility. |
| 95 | |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 96 | def find_loader(self, fullname): |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 97 | """Return (loader, namespace portion) for the path entry. |
| 98 | |
| 99 | The fullname is a str. The namespace portion is a sequence of |
| 100 | path entries contributing to part of a namespace package. The |
| 101 | sequence may be empty. If loader is not None, the portion will |
| 102 | be ignored. |
| 103 | |
| 104 | The portion will be discarded if another path entry finder |
| 105 | locates the module as a normal module or package. |
| 106 | |
Matthias Bussonnier | 1d4601c | 2017-02-15 18:00:32 -0800 | [diff] [blame] | 107 | This method is deprecated since Python 3.4 in favor of |
| 108 | finder.find_spec(). If find_spec() is provided than backwards-compatible |
| 109 | functionality is provided. |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 110 | """ |
Matthias Bussonnier | 1d4601c | 2017-02-15 18:00:32 -0800 | [diff] [blame] | 111 | warnings.warn("PathEntryFinder.find_loader() is deprecated since Python " |
| 112 | "3.4 in favor of PathEntryFinder.find_spec() " |
| 113 | "(available since 3.4)", |
| 114 | DeprecationWarning, |
| 115 | stacklevel=2) |
Brett Cannon | 8d94229 | 2014-01-07 15:52:42 -0500 | [diff] [blame] | 116 | if not hasattr(self, 'find_spec'): |
| 117 | return None, [] |
| 118 | found = self.find_spec(fullname) |
| 119 | if found is not None: |
| 120 | if not found.submodule_search_locations: |
| 121 | portions = [] |
| 122 | else: |
| 123 | portions = found.submodule_search_locations |
| 124 | return found.loader, portions |
| 125 | else: |
| 126 | return None, [] |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 127 | |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 128 | find_module = _bootstrap_external._find_module_shim |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 129 | |
| 130 | def invalidate_caches(self): |
| 131 | """An optional method for clearing the finder's cache, if any. |
| 132 | This method is used by PathFinder.invalidate_caches(). |
| 133 | """ |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 134 | |
Nick Coghlan | 8a9080f | 2012-08-02 21:26:03 +1000 | [diff] [blame] | 135 | _register(PathEntryFinder, machinery.FileFinder) |
| 136 | |
| 137 | |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 138 | class ResourceLoader(Loader): |
| 139 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 140 | """Abstract base class for loaders which can return data from their |
| 141 | back-end storage. |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 142 | |
| 143 | This ABC represents one of the optional protocols specified by PEP 302. |
| 144 | |
| 145 | """ |
| 146 | |
| 147 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 148 | def get_data(self, path): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 149 | """Abstract method which when implemented should return the bytes for |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 150 | the specified path. The path must be a str.""" |
Serhiy Storchaka | 55fe1ae | 2017-04-16 10:46:38 +0300 | [diff] [blame] | 151 | raise OSError |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 152 | |
| 153 | |
| 154 | class InspectLoader(Loader): |
| 155 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 156 | """Abstract base class for loaders which support inspection about the |
| 157 | modules they can load. |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 158 | |
| 159 | This ABC represents one of the optional protocols specified by PEP 302. |
| 160 | |
| 161 | """ |
| 162 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 163 | def is_package(self, fullname): |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 164 | """Optional method which when implemented should return whether the |
Brett Cannon | 100883f | 2013-04-09 16:59:39 -0400 | [diff] [blame] | 165 | module is a package. The fullname is a str. Returns a bool. |
| 166 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 167 | Raises ImportError if the module cannot be found. |
Brett Cannon | 100883f | 2013-04-09 16:59:39 -0400 | [diff] [blame] | 168 | """ |
| 169 | raise ImportError |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 170 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 171 | def get_code(self, fullname): |
Brett Cannon | 3b62ca8 | 2013-05-27 21:11:04 -0400 | [diff] [blame] | 172 | """Method which returns the code object for the module. |
Brett Cannon | 100883f | 2013-04-09 16:59:39 -0400 | [diff] [blame] | 173 | |
Brett Cannon | 3b62ca8 | 2013-05-27 21:11:04 -0400 | [diff] [blame] | 174 | The fullname is a str. Returns a types.CodeType if possible, else |
| 175 | returns None if a code object does not make sense |
| 176 | (e.g. built-in module). Raises ImportError if the module cannot be |
| 177 | found. |
Brett Cannon | 100883f | 2013-04-09 16:59:39 -0400 | [diff] [blame] | 178 | """ |
Brett Cannon | 3b62ca8 | 2013-05-27 21:11:04 -0400 | [diff] [blame] | 179 | source = self.get_source(fullname) |
| 180 | if source is None: |
| 181 | return None |
| 182 | return self.source_to_code(source) |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 183 | |
| 184 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 185 | def get_source(self, fullname): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 186 | """Abstract method which should return the source code for the |
Brett Cannon | 100883f | 2013-04-09 16:59:39 -0400 | [diff] [blame] | 187 | module. The fullname is a str. Returns a str. |
| 188 | |
| 189 | Raises ImportError if the module cannot be found. |
| 190 | """ |
| 191 | raise ImportError |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 192 | |
Brett Cannon | 6eaac13 | 2014-05-09 12:28:22 -0400 | [diff] [blame] | 193 | @staticmethod |
| 194 | def source_to_code(data, path='<string>'): |
Brett Cannon | 9ffe85e | 2013-05-26 16:45:10 -0400 | [diff] [blame] | 195 | """Compile 'data' into a code object. |
| 196 | |
| 197 | The 'data' argument can be anything that compile() can handle. The'path' |
| 198 | argument should be where the data was retrieved (when applicable).""" |
| 199 | return compile(data, path, 'exec', dont_inherit=True) |
| 200 | |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 201 | exec_module = _bootstrap_external._LoaderBasics.exec_module |
| 202 | load_module = _bootstrap_external._LoaderBasics.load_module |
Brett Cannon | 0dbb4c7 | 2013-05-31 18:56:47 -0400 | [diff] [blame] | 203 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 204 | _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter) |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 205 | |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 206 | |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 207 | class ExecutionLoader(InspectLoader): |
| 208 | |
| 209 | """Abstract base class for loaders that wish to support the execution of |
| 210 | modules as scripts. |
| 211 | |
| 212 | This ABC represents one of the optional protocols specified in PEP 302. |
| 213 | |
| 214 | """ |
| 215 | |
| 216 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 217 | def get_filename(self, fullname): |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 218 | """Abstract method which should return the value that __file__ is to be |
Brett Cannon | 100883f | 2013-04-09 16:59:39 -0400 | [diff] [blame] | 219 | set to. |
| 220 | |
| 221 | Raises ImportError if the module cannot be found. |
| 222 | """ |
| 223 | raise ImportError |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 224 | |
Brett Cannon | 3b62ca8 | 2013-05-27 21:11:04 -0400 | [diff] [blame] | 225 | def get_code(self, fullname): |
| 226 | """Method to return the code object for fullname. |
| 227 | |
| 228 | Should return None if not applicable (e.g. built-in module). |
| 229 | Raise ImportError if the module cannot be found. |
| 230 | """ |
| 231 | source = self.get_source(fullname) |
| 232 | if source is None: |
| 233 | return None |
| 234 | try: |
| 235 | path = self.get_filename(fullname) |
| 236 | except ImportError: |
| 237 | return self.source_to_code(source) |
| 238 | else: |
| 239 | return self.source_to_code(source, path) |
| 240 | |
Eric Snow | 7e70fa5 | 2013-10-04 20:28:52 -0600 | [diff] [blame] | 241 | _register(ExecutionLoader, machinery.ExtensionFileLoader) |
Eric Snow | 5179445 | 2013-10-03 12:08:55 -0600 | [diff] [blame] | 242 | |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 243 | |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 244 | class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader): |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 245 | |
| 246 | """Abstract base class partially implementing the ResourceLoader and |
| 247 | ExecutionLoader ABCs.""" |
| 248 | |
| 249 | _register(FileLoader, machinery.SourceFileLoader, |
Marc-Andre Lemburg | 4fe29c9 | 2012-04-25 02:31:37 +0200 | [diff] [blame] | 250 | machinery.SourcelessFileLoader) |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 251 | |
| 252 | |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 253 | class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader): |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 254 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 255 | """Abstract base class for loading source code (and optionally any |
| 256 | corresponding bytecode). |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 257 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 258 | To support loading from source code, the abstractmethods inherited from |
| 259 | ResourceLoader and ExecutionLoader need to be implemented. To also support |
| 260 | loading from bytecode, the optional methods specified directly by this ABC |
| 261 | is required. |
| 262 | |
| 263 | Inherited abstractmethods not implemented in this ABC: |
| 264 | |
| 265 | * ResourceLoader.get_data |
| 266 | * ExecutionLoader.get_filename |
| 267 | |
| 268 | """ |
| 269 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 270 | def path_mtime(self, path): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 271 | """Return the (int) modification time for the path (str).""" |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 272 | if self.path_stats.__func__ is SourceLoader.path_stats: |
Serhiy Storchaka | 55fe1ae | 2017-04-16 10:46:38 +0300 | [diff] [blame] | 273 | raise OSError |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 274 | return int(self.path_stats(path)['mtime']) |
| 275 | |
| 276 | def path_stats(self, path): |
| 277 | """Return a metadata dict for the source pointed to by the path (str). |
| 278 | Possible keys: |
| 279 | - 'mtime' (mandatory) is the numeric timestamp of last source |
| 280 | code modification; |
| 281 | - 'size' (optional) is the size in bytes of the source code. |
| 282 | """ |
| 283 | if self.path_mtime.__func__ is SourceLoader.path_mtime: |
Serhiy Storchaka | 55fe1ae | 2017-04-16 10:46:38 +0300 | [diff] [blame] | 284 | raise OSError |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 285 | return {'mtime': self.path_mtime(path)} |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 286 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 287 | def set_data(self, path, data): |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 288 | """Write the bytes to the path (if possible). |
| 289 | |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 290 | Accepts a str path and data as bytes. |
| 291 | |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 292 | Any needed intermediary directories are to be created. If for some |
| 293 | reason the file cannot be written because of permissions, fail |
| 294 | silently. |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 295 | """ |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 296 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 297 | _register(SourceLoader, machinery.SourceFileLoader) |
Brett Cannon | 4ac5150 | 2017-12-15 16:29:35 -0800 | [diff] [blame] | 298 | |
| 299 | |
Barry Warsaw | 5ec0fee | 2018-01-15 15:07:11 -0800 | [diff] [blame] | 300 | class ResourceReader(metaclass=abc.ABCMeta): |
Brett Cannon | 4ac5150 | 2017-12-15 16:29:35 -0800 | [diff] [blame] | 301 | |
Brett Cannon | bca4218 | 2018-01-12 15:08:59 -0800 | [diff] [blame] | 302 | """Abstract base class to provide resource-reading support. |
| 303 | |
| 304 | Loaders that support resource reading are expected to implement |
| 305 | the ``get_resource_reader(fullname)`` method and have it either return None |
| 306 | or an object compatible with this ABC. |
| 307 | """ |
Brett Cannon | 4ac5150 | 2017-12-15 16:29:35 -0800 | [diff] [blame] | 308 | |
| 309 | @abc.abstractmethod |
| 310 | def open_resource(self, resource): |
| 311 | """Return an opened, file-like object for binary reading. |
| 312 | |
| 313 | The 'resource' argument is expected to represent only a file name |
| 314 | and thus not contain any subdirectory components. |
| 315 | |
| 316 | If the resource cannot be found, FileNotFoundError is raised. |
| 317 | """ |
| 318 | raise FileNotFoundError |
| 319 | |
| 320 | @abc.abstractmethod |
| 321 | def resource_path(self, resource): |
| 322 | """Return the file system path to the specified resource. |
| 323 | |
| 324 | The 'resource' argument is expected to represent only a file name |
| 325 | and thus not contain any subdirectory components. |
| 326 | |
| 327 | If the resource does not exist on the file system, raise |
| 328 | FileNotFoundError. |
| 329 | """ |
| 330 | raise FileNotFoundError |
| 331 | |
| 332 | @abc.abstractmethod |
| 333 | def is_resource(self, name): |
| 334 | """Return True if the named 'name' is consider a resource.""" |
| 335 | raise FileNotFoundError |
| 336 | |
| 337 | @abc.abstractmethod |
| 338 | def contents(self): |
Brett Cannon | 3ab9365 | 2018-04-30 11:31:45 -0700 | [diff] [blame] | 339 | """Return an iterable of strings over the contents of the package.""" |
| 340 | return [] |
Barry Warsaw | 5ec0fee | 2018-01-15 15:07:11 -0800 | [diff] [blame] | 341 | |
| 342 | |
| 343 | _register(ResourceReader, machinery.SourceFileLoader) |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 344 | |
| 345 | |
| 346 | @runtime_checkable |
| 347 | class Traversable(Protocol): |
| 348 | """ |
| 349 | An object with a subset of pathlib.Path methods suitable for |
| 350 | traversing directories and opening files. |
| 351 | """ |
| 352 | |
| 353 | @abc.abstractmethod |
| 354 | def iterdir(self): |
| 355 | """ |
| 356 | Yield Traversable objects in self |
| 357 | """ |
| 358 | |
| 359 | @abc.abstractmethod |
| 360 | def read_bytes(self): |
| 361 | """ |
| 362 | Read contents of self as bytes |
| 363 | """ |
| 364 | |
| 365 | @abc.abstractmethod |
| 366 | def read_text(self, encoding=None): |
| 367 | """ |
| 368 | Read contents of self as bytes |
| 369 | """ |
| 370 | |
| 371 | @abc.abstractmethod |
| 372 | def is_dir(self): |
| 373 | """ |
| 374 | Return True if self is a dir |
| 375 | """ |
| 376 | |
| 377 | @abc.abstractmethod |
| 378 | def is_file(self): |
| 379 | """ |
| 380 | Return True if self is a file |
| 381 | """ |
| 382 | |
| 383 | @abc.abstractmethod |
| 384 | def joinpath(self, child): |
| 385 | """ |
| 386 | Return Traversable child in self |
| 387 | """ |
| 388 | |
| 389 | @abc.abstractmethod |
| 390 | def __truediv__(self, child): |
| 391 | """ |
| 392 | Return Traversable child in self |
| 393 | """ |
| 394 | |
| 395 | @abc.abstractmethod |
| 396 | def open(self, mode='r', *args, **kwargs): |
| 397 | """ |
| 398 | mode may be 'r' or 'rb' to open as text or binary. Return a handle |
| 399 | suitable for reading (same as pathlib.Path.open). |
| 400 | |
| 401 | When opening as text, accepts encoding parameters such as those |
| 402 | accepted by io.TextIOWrapper. |
| 403 | """ |
| 404 | |
| 405 | @abc.abstractproperty |
| 406 | def name(self): |
| 407 | # type: () -> str |
| 408 | """ |
| 409 | The base name of this object without any parent references. |
| 410 | """ |
| 411 | |
| 412 | |
| 413 | class TraversableResources(ResourceReader): |
| 414 | @abc.abstractmethod |
| 415 | def files(self): |
| 416 | """Return a Traversable object for the loaded package.""" |
| 417 | |
| 418 | def open_resource(self, resource): |
| 419 | return self.files().joinpath(resource).open('rb') |
| 420 | |
| 421 | def resource_path(self, resource): |
| 422 | raise FileNotFoundError(resource) |
| 423 | |
| 424 | def is_resource(self, path): |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 425 | return self.files().joinpath(path).is_file() |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 426 | |
| 427 | def contents(self): |
| 428 | return (item.name for item in self.files().iterdir()) |