Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 1 | """Abstract base classes related to import.""" |
| 2 | from . import _bootstrap |
| 3 | from . import machinery |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 4 | from . import util |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 5 | import abc |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 6 | import imp |
| 7 | import io |
| 8 | import marshal |
| 9 | import os.path |
| 10 | import sys |
| 11 | import tokenize |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 12 | import types |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 13 | import warnings |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 14 | |
| 15 | |
| 16 | class Loader(metaclass=abc.ABCMeta): |
| 17 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 18 | """Abstract base class for import loaders.""" |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 19 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 20 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 21 | def load_module(self, fullname): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 22 | """Abstract method which when implemented should load a module. |
| 23 | The fullname is a str.""" |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 24 | raise NotImplementedError |
| 25 | |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 26 | |
| 27 | class Finder(metaclass=abc.ABCMeta): |
| 28 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 29 | """Abstract base class for import finders.""" |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 30 | |
| 31 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 32 | def find_module(self, fullname, path=None): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 33 | """Abstract method which when implemented should find a module. |
| 34 | The fullname is a str and the optional path is a str or None. |
| 35 | Returns a Loader object. |
| 36 | """ |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 37 | raise NotImplementedError |
| 38 | |
| 39 | Finder.register(machinery.BuiltinImporter) |
| 40 | Finder.register(machinery.FrozenImporter) |
| 41 | Finder.register(machinery.PathFinder) |
| 42 | |
| 43 | |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 44 | class ResourceLoader(Loader): |
| 45 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 46 | """Abstract base class for loaders which can return data from their |
| 47 | back-end storage. |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 48 | |
| 49 | This ABC represents one of the optional protocols specified by PEP 302. |
| 50 | |
| 51 | """ |
| 52 | |
| 53 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 54 | def get_data(self, path): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 55 | """Abstract method which when implemented should return the bytes for |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 56 | the specified path. The path must be a str.""" |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 57 | raise NotImplementedError |
| 58 | |
| 59 | |
| 60 | class InspectLoader(Loader): |
| 61 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 62 | """Abstract base class for loaders which support inspection about the |
| 63 | modules they can load. |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 64 | |
| 65 | This ABC represents one of the optional protocols specified by PEP 302. |
| 66 | |
| 67 | """ |
| 68 | |
| 69 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 70 | def is_package(self, fullname): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 71 | """Abstract method which when implemented should return whether the |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 72 | module is a package. The fullname is a str. Returns a bool.""" |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 73 | raise NotImplementedError |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 74 | |
| 75 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 76 | def get_code(self, fullname): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 77 | """Abstract method which when implemented should return the code object |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 78 | for the module. The fullname is a str. Returns a types.CodeType.""" |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 79 | raise NotImplementedError |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 80 | |
| 81 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 82 | def get_source(self, fullname): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 83 | """Abstract method which should return the source code for the |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 84 | module. The fullname is a str. Returns a str.""" |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 85 | raise NotImplementedError |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 86 | |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 87 | InspectLoader.register(machinery.BuiltinImporter) |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 88 | InspectLoader.register(machinery.FrozenImporter) |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 89 | |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 90 | |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 91 | class ExecutionLoader(InspectLoader): |
| 92 | |
| 93 | """Abstract base class for loaders that wish to support the execution of |
| 94 | modules as scripts. |
| 95 | |
| 96 | This ABC represents one of the optional protocols specified in PEP 302. |
| 97 | |
| 98 | """ |
| 99 | |
| 100 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 101 | def get_filename(self, fullname): |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 102 | """Abstract method which should return the value that __file__ is to be |
| 103 | set to.""" |
| 104 | raise NotImplementedError |
| 105 | |
| 106 | |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 107 | class SourceLoader(_bootstrap.SourceLoader, ResourceLoader, ExecutionLoader): |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 108 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 109 | """Abstract base class for loading source code (and optionally any |
| 110 | corresponding bytecode). |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 111 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 112 | To support loading from source code, the abstractmethods inherited from |
| 113 | ResourceLoader and ExecutionLoader need to be implemented. To also support |
| 114 | loading from bytecode, the optional methods specified directly by this ABC |
| 115 | is required. |
| 116 | |
| 117 | Inherited abstractmethods not implemented in this ABC: |
| 118 | |
| 119 | * ResourceLoader.get_data |
| 120 | * ExecutionLoader.get_filename |
| 121 | |
| 122 | """ |
| 123 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 124 | def path_mtime(self, path): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 125 | """Return the (int) modification time for the path (str).""" |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 126 | if self.path_stats.__func__ is SourceLoader.path_stats: |
| 127 | raise NotImplementedError |
| 128 | return int(self.path_stats(path)['mtime']) |
| 129 | |
| 130 | def path_stats(self, path): |
| 131 | """Return a metadata dict for the source pointed to by the path (str). |
| 132 | Possible keys: |
| 133 | - 'mtime' (mandatory) is the numeric timestamp of last source |
| 134 | code modification; |
| 135 | - 'size' (optional) is the size in bytes of the source code. |
| 136 | """ |
| 137 | if self.path_mtime.__func__ is SourceLoader.path_mtime: |
| 138 | raise NotImplementedError |
| 139 | return {'mtime': self.path_mtime(path)} |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 140 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 141 | def set_data(self, path, data): |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 142 | """Write the bytes to the path (if possible). |
| 143 | |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 144 | Accepts a str path and data as bytes. |
| 145 | |
Brett Cannon | 8d18907 | 2010-08-22 20:38:47 +0000 | [diff] [blame] | 146 | Any needed intermediary directories are to be created. If for some |
| 147 | reason the file cannot be written because of permissions, fail |
| 148 | silently. |
| 149 | |
| 150 | """ |
| 151 | raise NotImplementedError |
| 152 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 153 | |
| 154 | class PyLoader(SourceLoader): |
| 155 | |
| 156 | """Implement the deprecated PyLoader ABC in terms of SourceLoader. |
| 157 | |
| 158 | This class has been deprecated! It is slated for removal in Python 3.4. |
| 159 | If compatibility with Python 3.1 is not needed then implement the |
| 160 | SourceLoader ABC instead of this class. If Python 3.1 compatibility is |
| 161 | needed, then use the following idiom to have a single class that is |
| 162 | compatible with Python 3.1 onwards:: |
| 163 | |
| 164 | try: |
| 165 | from importlib.abc import SourceLoader |
| 166 | except ImportError: |
| 167 | from importlib.abc import PyLoader as SourceLoader |
| 168 | |
| 169 | |
| 170 | class CustomLoader(SourceLoader): |
| 171 | def get_filename(self, fullname): |
| 172 | # Implement ... |
| 173 | |
| 174 | def source_path(self, fullname): |
| 175 | '''Implement source_path in terms of get_filename.''' |
| 176 | try: |
| 177 | return self.get_filename(fullname) |
| 178 | except ImportError: |
| 179 | return None |
| 180 | |
| 181 | def is_package(self, fullname): |
| 182 | filename = os.path.basename(self.get_filename(fullname)) |
| 183 | return os.path.splitext(filename)[0] == '__init__' |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 184 | |
| 185 | """ |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 186 | |
| 187 | @abc.abstractmethod |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 188 | def is_package(self, fullname): |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 189 | raise NotImplementedError |
| 190 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 191 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 192 | def source_path(self, fullname): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 193 | """Abstract method. Accepts a str module name and returns the path to |
| 194 | the source code for the module.""" |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 195 | raise NotImplementedError |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 196 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 197 | def get_filename(self, fullname): |
| 198 | """Implement get_filename in terms of source_path. |
| 199 | |
| 200 | As get_filename should only return a source file path there is no |
| 201 | chance of the path not existing but loading still being possible, so |
| 202 | ImportError should propagate instead of being turned into returning |
| 203 | None. |
| 204 | |
| 205 | """ |
| 206 | warnings.warn("importlib.abc.PyLoader is deprecated and is " |
| 207 | "slated for removal in Python 3.4; " |
| 208 | "use SourceLoader instead. " |
| 209 | "See the importlib documentation on how to be " |
| 210 | "compatible with Python 3.1 onwards.", |
Florent Xicluna | 6731775 | 2011-12-10 11:07:42 +0100 | [diff] [blame] | 211 | DeprecationWarning) |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 212 | path = self.source_path(fullname) |
| 213 | if path is None: |
| 214 | raise ImportError |
| 215 | else: |
| 216 | return path |
| 217 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 218 | |
| 219 | class PyPycLoader(PyLoader): |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 220 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 221 | """Abstract base class to assist in loading source and bytecode by |
| 222 | requiring only back-end storage methods to be implemented. |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 223 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 224 | This class has been deprecated! Removal is slated for Python 3.4. Implement |
| 225 | the SourceLoader ABC instead. If Python 3.1 compatibility is needed, see |
| 226 | PyLoader. |
| 227 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 228 | The methods get_code, get_source, and load_module are implemented for the |
| 229 | user. |
| 230 | |
| 231 | """ |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 232 | |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 233 | def get_filename(self, fullname): |
| 234 | """Return the source or bytecode file path.""" |
| 235 | path = self.source_path(fullname) |
| 236 | if path is not None: |
| 237 | return path |
| 238 | path = self.bytecode_path(fullname) |
| 239 | if path is not None: |
| 240 | return path |
| 241 | raise ImportError("no source or bytecode path available for " |
| 242 | "{0!r}".format(fullname)) |
| 243 | |
| 244 | def get_code(self, fullname): |
| 245 | """Get a code object from source or bytecode.""" |
| 246 | warnings.warn("importlib.abc.PyPycLoader is deprecated and slated for " |
| 247 | "removal in Python 3.4; use SourceLoader instead. " |
| 248 | "If Python 3.1 compatibility is required, see the " |
| 249 | "latest documentation for PyLoader.", |
Florent Xicluna | 6731775 | 2011-12-10 11:07:42 +0100 | [diff] [blame] | 250 | DeprecationWarning) |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 251 | source_timestamp = self.source_mtime(fullname) |
| 252 | # Try to use bytecode if it is available. |
| 253 | bytecode_path = self.bytecode_path(fullname) |
| 254 | if bytecode_path: |
| 255 | data = self.get_data(bytecode_path) |
| 256 | try: |
| 257 | magic = data[:4] |
| 258 | if len(magic) < 4: |
| 259 | raise ImportError("bad magic number in {}".format(fullname)) |
| 260 | raw_timestamp = data[4:8] |
| 261 | if len(raw_timestamp) < 4: |
| 262 | raise EOFError("bad timestamp in {}".format(fullname)) |
Brett Cannon | c264e3e | 2012-01-25 18:58:03 -0500 | [diff] [blame] | 263 | pyc_timestamp = _bootstrap._r_long(raw_timestamp) |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 264 | bytecode = data[8:] |
| 265 | # Verify that the magic number is valid. |
| 266 | if imp.get_magic() != magic: |
| 267 | raise ImportError("bad magic number in {}".format(fullname)) |
| 268 | # Verify that the bytecode is not stale (only matters when |
| 269 | # there is source to fall back on. |
| 270 | if source_timestamp: |
| 271 | if pyc_timestamp < source_timestamp: |
| 272 | raise ImportError("bytecode is stale") |
| 273 | except (ImportError, EOFError): |
| 274 | # If source is available give it a shot. |
| 275 | if source_timestamp is not None: |
| 276 | pass |
| 277 | else: |
| 278 | raise |
| 279 | else: |
| 280 | # Bytecode seems fine, so try to use it. |
| 281 | return marshal.loads(bytecode) |
| 282 | elif source_timestamp is None: |
| 283 | raise ImportError("no source or bytecode available to create code " |
| 284 | "object for {0!r}".format(fullname)) |
| 285 | # Use the source. |
| 286 | source_path = self.source_path(fullname) |
| 287 | if source_path is None: |
| 288 | message = "a source path must exist to load {0}".format(fullname) |
| 289 | raise ImportError(message) |
| 290 | source = self.get_data(source_path) |
| 291 | code_object = compile(source, source_path, 'exec', dont_inherit=True) |
| 292 | # Generate bytecode and write it out. |
| 293 | if not sys.dont_write_bytecode: |
| 294 | data = bytearray(imp.get_magic()) |
Brett Cannon | c264e3e | 2012-01-25 18:58:03 -0500 | [diff] [blame] | 295 | data.extend(_bootstrap._w_long(source_timestamp)) |
Brett Cannon | f23e374 | 2010-06-27 23:57:46 +0000 | [diff] [blame] | 296 | data.extend(marshal.dumps(code_object)) |
| 297 | self.write_bytecode(fullname, data) |
| 298 | return code_object |
| 299 | |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 300 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 301 | def source_mtime(self, fullname): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 302 | """Abstract method. Accepts a str filename and returns an int |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 303 | modification time for the source of the module.""" |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 304 | raise NotImplementedError |
| 305 | |
| 306 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 307 | def bytecode_path(self, fullname): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 308 | """Abstract method. Accepts a str filename and returns the str pathname |
| 309 | to the bytecode for the module.""" |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 310 | raise NotImplementedError |
| 311 | |
| 312 | @abc.abstractmethod |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 313 | def write_bytecode(self, fullname, bytecode): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 314 | """Abstract method. Accepts a str filename and bytes object |
| 315 | representing the bytecode for the module. Returns a boolean |
| 316 | representing whether the bytecode was written or not.""" |
Brett Cannon | 2a922ed | 2009-03-09 03:35:50 +0000 | [diff] [blame] | 317 | raise NotImplementedError |