Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1 | """Core implementation of import. |
| 2 | |
| 3 | This module is NOT meant to be directly imported! It has been designed such |
| 4 | that it can be bootstrapped into Python as the implementation of import. As |
| 5 | such it requires the injection of specific modules and attributes in order to |
| 6 | work. One should use importlib as the public-facing version of this module. |
| 7 | |
| 8 | """ |
| 9 | |
Brett Cannon | 7c9875c | 2009-03-04 01:10:09 +0000 | [diff] [blame] | 10 | # Injected modules are '_warnings', 'imp', 'sys', 'marshal', 'errno', '_io', |
| 11 | # and '_os' (a.k.a. 'posix', 'nt' or 'os2'). |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 12 | # Injected attribute is path_sep. |
| 13 | # |
| 14 | # When editing this code be aware that code executed at import time CANNOT |
| 15 | # reference any injected objects! This includes not only global code but also |
| 16 | # anything specified at the class level. |
| 17 | |
| 18 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 19 | # Bootstrap-related code ###################################################### |
| 20 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 21 | # XXX Could also expose Modules/getpath.c:joinpath() |
| 22 | def _path_join(*args): |
| 23 | """Replacement for os.path.join.""" |
| 24 | return path_sep.join(x[:-len(path_sep)] if x.endswith(path_sep) else x |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 25 | for x in args if x) |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 26 | |
| 27 | |
| 28 | def _path_exists(path): |
| 29 | """Replacement for os.path.exists.""" |
| 30 | try: |
| 31 | _os.stat(path) |
| 32 | except OSError: |
| 33 | return False |
| 34 | else: |
| 35 | return True |
| 36 | |
| 37 | |
| 38 | def _path_is_mode_type(path, mode): |
| 39 | """Test whether the path is the specified mode type.""" |
| 40 | try: |
| 41 | stat_info = _os.stat(path) |
| 42 | except OSError: |
| 43 | return False |
| 44 | return (stat_info.st_mode & 0o170000) == mode |
| 45 | |
| 46 | |
| 47 | # XXX Could also expose Modules/getpath.c:isfile() |
| 48 | def _path_isfile(path): |
| 49 | """Replacement for os.path.isfile.""" |
| 50 | return _path_is_mode_type(path, 0o100000) |
| 51 | |
| 52 | |
| 53 | # XXX Could also expose Modules/getpath.c:isdir() |
| 54 | def _path_isdir(path): |
| 55 | """Replacement for os.path.isdir.""" |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 56 | if not path: |
| 57 | path = _os.getcwd() |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 58 | return _path_is_mode_type(path, 0o040000) |
| 59 | |
| 60 | |
| 61 | def _path_without_ext(path, ext_type): |
| 62 | """Replacement for os.path.splitext()[0].""" |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 63 | for suffix in _suffix_list(ext_type): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 64 | if path.endswith(suffix): |
| 65 | return path[:-len(suffix)] |
| 66 | else: |
| 67 | raise ValueError("path is not of the specified type") |
| 68 | |
| 69 | |
| 70 | def _path_absolute(path): |
| 71 | """Replacement for os.path.abspath.""" |
| 72 | if not path: |
| 73 | path = _os.getcwd() |
| 74 | try: |
| 75 | return _os._getfullpathname(path) |
| 76 | except AttributeError: |
| 77 | if path.startswith('/'): |
| 78 | return path |
| 79 | else: |
| 80 | return _path_join(_os.getcwd(), path) |
| 81 | |
| 82 | |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 83 | class _closing: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 84 | |
| 85 | """Simple replacement for contextlib.closing.""" |
| 86 | |
| 87 | def __init__(self, obj): |
| 88 | self.obj = obj |
| 89 | |
| 90 | def __enter__(self): |
| 91 | return self.obj |
| 92 | |
| 93 | def __exit__(self, *args): |
| 94 | self.obj.close() |
| 95 | |
| 96 | |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 97 | def _wrap(new, old): |
Brett Cannon | 51d8bfc | 2009-02-07 02:13:28 +0000 | [diff] [blame] | 98 | """Simple substitute for functools.wraps.""" |
| 99 | for replace in ['__module__', '__name__', '__doc__']: |
| 100 | setattr(new, replace, getattr(old, replace)) |
| 101 | new.__dict__.update(old.__dict__) |
| 102 | |
| 103 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 104 | code_type = type(_wrap.__code__) |
| 105 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 106 | # Finder/loader utility code ################################################## |
| 107 | |
Brett Cannon | 435aad8 | 2009-03-04 16:07:00 +0000 | [diff] [blame] | 108 | def set_package(fxn): |
Brett Cannon | 06c9d96 | 2009-02-07 01:52:25 +0000 | [diff] [blame] | 109 | """Set __package__ on the returned module.""" |
| 110 | def wrapper(*args, **kwargs): |
| 111 | module = fxn(*args, **kwargs) |
| 112 | if not hasattr(module, '__package__') or module.__package__ is None: |
| 113 | module.__package__ = module.__name__ |
| 114 | if not hasattr(module, '__path__'): |
| 115 | module.__package__ = module.__package__.rpartition('.')[0] |
| 116 | return module |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 117 | _wrap(wrapper, fxn) |
Brett Cannon | 06c9d96 | 2009-02-07 01:52:25 +0000 | [diff] [blame] | 118 | return wrapper |
| 119 | |
| 120 | |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 121 | def set_loader(fxn): |
| 122 | """Set __loader__ on the returned module.""" |
| 123 | def wrapper(self, *args, **kwargs): |
| 124 | module = fxn(self, *args, **kwargs) |
| 125 | if not hasattr(module, '__loader__'): |
| 126 | module.__loader__ = self |
| 127 | return module |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 128 | _wrap(wrapper, fxn) |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 129 | return wrapper |
| 130 | |
| 131 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 132 | def module_for_loader(fxn): |
| 133 | """Decorator to handle selecting the proper module for loaders. |
| 134 | |
Brett Cannon | 0e0d8a6 | 2009-03-15 00:00:19 +0000 | [diff] [blame] | 135 | The decorated function is passed the module to use instead of the module |
| 136 | name. The module passed in to the function is either from sys.modules if |
| 137 | it already exists or is a new module which has __name__ set and is inserted |
| 138 | into sys.modules. If an exception is raised and the decorator created the |
| 139 | module it is subsequently removed from sys.modules. |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 140 | |
Brett Cannon | 0e0d8a6 | 2009-03-15 00:00:19 +0000 | [diff] [blame] | 141 | The decorator assumes that the decorated function takes the module name as |
| 142 | the second argument. |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 143 | |
| 144 | """ |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 145 | def decorated(self, fullname, *args, **kwargs): |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 146 | module = sys.modules.get(fullname) |
| 147 | is_reload = bool(module) |
| 148 | if not is_reload: |
| 149 | # This must be done before open() is called as the 'io' module |
| 150 | # implicitly imports 'locale' and would otherwise trigger an |
| 151 | # infinite loop. |
| 152 | module = imp.new_module(fullname) |
| 153 | sys.modules[fullname] = module |
| 154 | try: |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 155 | return fxn(self, module, *args, **kwargs) |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 156 | except: |
| 157 | if not is_reload: |
| 158 | del sys.modules[fullname] |
| 159 | raise |
| 160 | _wrap(decorated, fxn) |
| 161 | return decorated |
| 162 | |
| 163 | |
| 164 | def _check_name(method): |
| 165 | """Decorator to verify that the module being requested matches the one the |
| 166 | loader can handle. |
| 167 | |
| 168 | The first argument (self) must define _name which the second argument is |
| 169 | comapred against. If the comparison fails then ImportError is raised. |
| 170 | |
| 171 | """ |
| 172 | def inner(self, name, *args, **kwargs): |
| 173 | if self._name != name: |
| 174 | raise ImportError("loader cannot handle %s" % name) |
| 175 | return method(self, name, *args, **kwargs) |
| 176 | _wrap(inner, method) |
| 177 | return inner |
| 178 | |
| 179 | |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 180 | def _requires_builtin(fxn): |
| 181 | """Decorator to verify the named module is built-in.""" |
| 182 | def wrapper(self, fullname): |
| 183 | if fullname not in sys.builtin_module_names: |
| 184 | raise ImportError("{0} is not a built-in module".format(fullname)) |
| 185 | return fxn(self, fullname) |
| 186 | _wrap(wrapper, fxn) |
| 187 | return wrapper |
| 188 | |
| 189 | |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 190 | def _requires_frozen(fxn): |
| 191 | """Decorator to verify the named module is frozen.""" |
| 192 | def wrapper(self, fullname): |
| 193 | if not imp.is_frozen(fullname): |
| 194 | raise ImportError("{0} is not a frozen module".format(fullname)) |
| 195 | return fxn(self, fullname) |
| 196 | _wrap(wrapper, fxn) |
| 197 | return wrapper |
| 198 | |
| 199 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 200 | def _suffix_list(suffix_type): |
| 201 | """Return a list of file suffixes based on the imp file type.""" |
| 202 | return [suffix[0] for suffix in imp.get_suffixes() |
| 203 | if suffix[2] == suffix_type] |
| 204 | |
| 205 | |
| 206 | # Loaders ##################################################################### |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 207 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 208 | class BuiltinImporter: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 209 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 210 | """Meta path import for built-in modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 211 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 212 | All methods are either class or static methods to avoid the need to |
| 213 | instantiate the class. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 214 | |
| 215 | """ |
| 216 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 217 | @classmethod |
| 218 | def find_module(cls, fullname, path=None): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 219 | """Find the built-in module. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 220 | |
| 221 | If 'path' is ever specified then the search is considered a failure. |
| 222 | |
| 223 | """ |
| 224 | if path is not None: |
| 225 | return None |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 226 | return cls if imp.is_builtin(fullname) else None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 227 | |
Brett Cannon | 78246b6 | 2009-01-25 04:56:30 +0000 | [diff] [blame] | 228 | @classmethod |
Brett Cannon | 435aad8 | 2009-03-04 16:07:00 +0000 | [diff] [blame] | 229 | @set_package |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 230 | @set_loader |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 231 | @_requires_builtin |
Brett Cannon | 78246b6 | 2009-01-25 04:56:30 +0000 | [diff] [blame] | 232 | def load_module(cls, fullname): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 233 | """Load a built-in module.""" |
Brett Cannon | d2e7b33 | 2009-02-17 02:45:03 +0000 | [diff] [blame] | 234 | is_reload = fullname in sys.modules |
| 235 | try: |
| 236 | return imp.init_builtin(fullname) |
| 237 | except: |
| 238 | if not is_reload and fullname in sys.modules: |
| 239 | del sys.modules[fullname] |
| 240 | raise |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 241 | |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 242 | @classmethod |
| 243 | @_requires_builtin |
| 244 | def get_code(cls, fullname): |
| 245 | """Return None as built-in modules do not have code objects.""" |
| 246 | return None |
| 247 | |
| 248 | @classmethod |
| 249 | @_requires_builtin |
| 250 | def get_source(cls, fullname): |
| 251 | """Return None as built-in modules do not have source code.""" |
| 252 | return None |
| 253 | |
| 254 | @classmethod |
| 255 | @_requires_builtin |
| 256 | def is_package(cls, fullname): |
| 257 | """Return None as built-in module are never packages.""" |
| 258 | return False |
| 259 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 260 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 261 | class FrozenImporter: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 262 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 263 | """Meta path import for frozen modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 264 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 265 | All methods are either class or static methods to avoid the need to |
| 266 | instantiate the class. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 267 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 268 | """ |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 269 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 270 | @classmethod |
| 271 | def find_module(cls, fullname, path=None): |
| 272 | """Find a frozen module.""" |
| 273 | return cls if imp.is_frozen(fullname) else None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 274 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 275 | @classmethod |
Brett Cannon | 435aad8 | 2009-03-04 16:07:00 +0000 | [diff] [blame] | 276 | @set_package |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 277 | @set_loader |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 278 | @_requires_frozen |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 279 | def load_module(cls, fullname): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 280 | """Load a frozen module.""" |
Brett Cannon | d2e7b33 | 2009-02-17 02:45:03 +0000 | [diff] [blame] | 281 | is_reload = fullname in sys.modules |
| 282 | try: |
| 283 | return imp.init_frozen(fullname) |
| 284 | except: |
| 285 | if not is_reload and fullname in sys.modules: |
| 286 | del sys.modules[fullname] |
| 287 | raise |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 288 | |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 289 | @classmethod |
| 290 | @_requires_frozen |
| 291 | def get_code(cls, fullname): |
| 292 | """Return the code object for the frozen module.""" |
| 293 | return imp.get_frozen_object(fullname) |
| 294 | |
| 295 | @classmethod |
| 296 | @_requires_frozen |
| 297 | def get_source(cls, fullname): |
| 298 | """Return None as frozen modules do not have source code.""" |
| 299 | return None |
| 300 | |
| 301 | @classmethod |
| 302 | @_requires_frozen |
| 303 | def is_package(cls, fullname): |
| 304 | """Return if the frozen module is a package.""" |
| 305 | return imp.is_frozen_package(fullname) |
| 306 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 307 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 308 | class _LoaderBasics: |
| 309 | |
| 310 | """Base class of common code needed by both SourceLoader and |
| 311 | _SourcelessFileLoader.""" |
| 312 | |
| 313 | def is_package(self, fullname): |
| 314 | """Concrete implementation of InspectLoader.is_package by checking if |
| 315 | the path returned by get_filename has a filename of '__init__.py'.""" |
| 316 | filename = self.get_filename(fullname).rpartition(path_sep)[2] |
| 317 | return filename.rsplit('.', 1)[0] == '__init__' |
| 318 | |
| 319 | def _bytes_from_bytecode(self, fullname, data, source_mtime): |
| 320 | """Return the marshalled bytes from bytecode, verifying the magic |
| 321 | number and timestamp alon the way. |
| 322 | |
| 323 | If source_mtime is None then skip the timestamp check. |
| 324 | |
| 325 | """ |
| 326 | magic = data[:4] |
| 327 | raw_timestamp = data[4:8] |
| 328 | if len(magic) != 4 or magic != imp.get_magic(): |
| 329 | raise ImportError("bad magic number in {}".format(fullname)) |
| 330 | elif len(raw_timestamp) != 4: |
| 331 | raise EOFError("bad timestamp in {}".format(fullname)) |
| 332 | elif source_mtime is not None: |
| 333 | if marshal._r_long(raw_timestamp) != source_mtime: |
| 334 | raise ImportError("bytecode is stale for {}".format(fullname)) |
| 335 | # Can't return the code object as errors from marshal loading need to |
| 336 | # propagate even when source is available. |
| 337 | return data[8:] |
| 338 | |
| 339 | @module_for_loader |
| 340 | def _load_module(self, module, *, sourceless=False): |
| 341 | """Helper for load_module able to handle either source or sourceless |
| 342 | loading.""" |
| 343 | name = module.__name__ |
| 344 | code_object = self.get_code(name) |
| 345 | module.__file__ = self.get_filename(name) |
| 346 | if not sourceless: |
| 347 | module.__cached__ = imp.cache_from_source(module.__file__) |
| 348 | else: |
| 349 | module.__cached__ = module.__file__ |
| 350 | module.__package__ = name |
| 351 | if self.is_package(name): |
| 352 | module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]] |
| 353 | else: |
| 354 | module.__package__ = module.__package__.rpartition('.')[0] |
| 355 | module.__loader__ = self |
| 356 | exec(code_object, module.__dict__) |
| 357 | return module |
| 358 | |
| 359 | |
| 360 | class SourceLoader(_LoaderBasics): |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 361 | |
| 362 | def path_mtime(self, path:str) -> int: |
| 363 | """Optional method that returns the modification time for the specified |
| 364 | path. |
| 365 | |
| 366 | Implementing this method allows the loader to read bytecode files. |
| 367 | |
| 368 | """ |
| 369 | raise NotImplementedError |
| 370 | |
| 371 | def set_data(self, path:str, data:bytes) -> None: |
| 372 | """Optional method which writes data to a file path. |
| 373 | |
| 374 | Implementing this method allows for the writing of bytecode files. |
| 375 | |
| 376 | """ |
| 377 | raise NotImplementedError |
| 378 | |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 379 | |
| 380 | def get_source(self, fullname): |
| 381 | """Concrete implementation of InspectLoader.get_source.""" |
| 382 | import tokenize |
| 383 | path = self.get_filename(fullname) |
| 384 | try: |
| 385 | source_bytes = self.get_data(path) |
| 386 | except IOError: |
| 387 | raise ImportError("source not available through get_data()") |
| 388 | encoding = tokenize.detect_encoding(_io.BytesIO(source_bytes).readline) |
Brett Cannon | 418182e | 2010-07-03 22:32:41 +0000 | [diff] [blame] | 389 | newline_decoder = _io.IncrementalNewlineDecoder(None, True) |
| 390 | return newline_decoder.decode(source_bytes.decode(encoding[0])) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 391 | |
| 392 | def get_code(self, fullname): |
| 393 | """Concrete implementation of InspectLoader.get_code. |
| 394 | |
| 395 | Reading of bytecode requires path_mtime to be implemented. To write |
| 396 | bytecode, set_data must also be implemented. |
| 397 | |
| 398 | """ |
| 399 | source_path = self.get_filename(fullname) |
| 400 | bytecode_path = imp.cache_from_source(source_path) |
| 401 | source_mtime = None |
| 402 | if bytecode_path is not None: |
| 403 | try: |
| 404 | source_mtime = self.path_mtime(source_path) |
| 405 | except NotImplementedError: |
| 406 | pass |
| 407 | else: |
| 408 | try: |
| 409 | data = self.get_data(bytecode_path) |
| 410 | except IOError: |
| 411 | pass |
| 412 | else: |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 413 | try: |
| 414 | bytes_data = self._bytes_from_bytecode(fullname, data, |
| 415 | source_mtime) |
| 416 | except (ImportError, EOFError): |
| 417 | pass |
| 418 | else: |
| 419 | found = marshal.loads(bytes_data) |
| 420 | if isinstance(found, code_type): |
| 421 | return found |
| 422 | else: |
| 423 | msg = "Non-code object in {}" |
| 424 | raise ImportError(msg.format(bytecode_path)) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 425 | source_bytes = self.get_data(source_path) |
| 426 | code_object = compile(source_bytes, source_path, 'exec', |
| 427 | dont_inherit=True) |
| 428 | if (not sys.dont_write_bytecode and bytecode_path is not None and |
| 429 | source_mtime is not None): |
| 430 | # If e.g. Jython ever implements imp.cache_from_source to have |
| 431 | # their own cached file format, this block of code will most likely |
| 432 | # throw an exception. |
| 433 | data = bytearray(imp.get_magic()) |
| 434 | data.extend(marshal._w_long(source_mtime)) |
| 435 | data.extend(marshal.dumps(code_object)) |
| 436 | try: |
| 437 | self.set_data(bytecode_path, data) |
| 438 | except NotImplementedError: |
| 439 | pass |
| 440 | return code_object |
| 441 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 442 | def load_module(self, fullname): |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 443 | """Concrete implementation of Loader.load_module. |
| 444 | |
| 445 | Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be |
| 446 | implemented to load source code. Use of bytecode is dictated by whether |
| 447 | get_code uses/writes bytecode. |
| 448 | |
| 449 | """ |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 450 | return self._load_module(fullname) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 451 | |
| 452 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 453 | class _FileLoader: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 454 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 455 | """Base file loader class which implements the loader protocol methods that |
| 456 | require file system usage.""" |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 457 | |
| 458 | def __init__(self, fullname, path): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 459 | """Cache the module name and the path to the file found by the |
| 460 | finder.""" |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 461 | self._name = fullname |
| 462 | self._path = path |
| 463 | |
| 464 | @_check_name |
| 465 | def get_filename(self, fullname): |
| 466 | """Return the path to the source file as found by the finder.""" |
| 467 | return self._path |
| 468 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 469 | def get_data(self, path): |
| 470 | """Return the data from path as raw bytes.""" |
| 471 | with _closing(_io.FileIO(path, 'r')) as file: |
| 472 | return file.read() |
| 473 | |
| 474 | |
| 475 | class _SourceFileLoader(_FileLoader, SourceLoader): |
| 476 | |
| 477 | """Concrete implementation of SourceLoader using the file system.""" |
| 478 | |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 479 | def path_mtime(self, path): |
| 480 | """Return the modification time for the path.""" |
| 481 | return int(_os.stat(path).st_mtime) |
| 482 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 483 | def set_data(self, path, data): |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 484 | """Write bytes data to a file.""" |
Brett Cannon | ee6d647 | 2010-08-22 22:19:11 +0000 | [diff] [blame^] | 485 | parent, _, filename = path.rpartition(path_sep) |
| 486 | path_parts = [] |
| 487 | # Figure out what directories are missing. |
| 488 | while parent and not _path_isdir(parent): |
| 489 | parent, _, part = parent.rpartition(path_sep) |
| 490 | path_parts.append(part) |
| 491 | # Create needed directories. |
| 492 | for part in reversed(path_parts): |
| 493 | parent = _path_join(parent, part) |
| 494 | try: |
| 495 | _os.mkdir(parent) |
| 496 | except IOError as exc: |
| 497 | # Probably another Python process already created the dir. |
| 498 | if exc.errno == errno.EEXIST: |
| 499 | continue |
| 500 | # If can't get proper access, then just forget about writing |
| 501 | # the data. |
| 502 | elif errno == errno.EACCES: |
| 503 | return |
| 504 | else: |
| 505 | raise |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 506 | try: |
Brett Cannon | ee6d647 | 2010-08-22 22:19:11 +0000 | [diff] [blame^] | 507 | with _io.FileIO(path, 'wb') as file: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 508 | file.write(data) |
| 509 | except IOError as exc: |
Brett Cannon | ee6d647 | 2010-08-22 22:19:11 +0000 | [diff] [blame^] | 510 | # Don't worry if you can't write bytecode. |
| 511 | if exc.errno == errno.EACCES: |
| 512 | return |
| 513 | else: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 514 | raise |
| 515 | |
| 516 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 517 | class _SourcelessFileLoader(_FileLoader, _LoaderBasics): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 518 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 519 | """Loader which handles sourceless file imports.""" |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 520 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 521 | def load_module(self, fullname): |
| 522 | return self._load_module(fullname, sourceless=True) |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 523 | |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 524 | def get_code(self, fullname): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 525 | path = self.get_filename(fullname) |
| 526 | data = self.get_data(path) |
| 527 | bytes_data = self._bytes_from_bytecode(fullname, data, None) |
| 528 | found = marshal.loads(bytes_data) |
| 529 | if isinstance(found, code_type): |
| 530 | return found |
| 531 | else: |
| 532 | raise ImportError("Non-code object in {}".format(path)) |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 533 | |
Brett Cannon | d43b30b | 2009-03-10 03:29:23 +0000 | [diff] [blame] | 534 | def get_source(self, fullname): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 535 | """Return None as there is no source code.""" |
| 536 | return None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 537 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 538 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 539 | class _ExtensionFileLoader: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 540 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 541 | """Loader for extension modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 542 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 543 | The constructor is designed to work with FileFinder. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 544 | |
| 545 | """ |
| 546 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 547 | def __init__(self, name, path): |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 548 | """Initialize the loader. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 549 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 550 | If is_pkg is True then an exception is raised as extension modules |
| 551 | cannot be the __init__ module for an extension module. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 552 | |
| 553 | """ |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 554 | self._name = name |
| 555 | self._path = path |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 556 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 557 | @_check_name |
| 558 | @set_package |
| 559 | @set_loader |
| 560 | def load_module(self, fullname): |
| 561 | """Load an extension module.""" |
| 562 | is_reload = fullname in sys.modules |
| 563 | try: |
| 564 | return imp.load_dynamic(fullname, self._path) |
| 565 | except: |
| 566 | if not is_reload and fullname in sys.modules: |
| 567 | del sys.modules[fullname] |
| 568 | raise |
| 569 | |
| 570 | @_check_name |
| 571 | def is_package(self, fullname): |
| 572 | """Return False as an extension module can never be a package.""" |
| 573 | return False |
| 574 | |
| 575 | @_check_name |
| 576 | def get_code(self, fullname): |
| 577 | """Return None as an extension module cannot create a code object.""" |
| 578 | return None |
| 579 | |
| 580 | @_check_name |
| 581 | def get_source(self, fullname): |
| 582 | """Return None as extension modules have no source code.""" |
| 583 | return None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 584 | |
| 585 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 586 | # Finders ##################################################################### |
Brett Cannon | 4afab6b | 2009-02-21 03:31:35 +0000 | [diff] [blame] | 587 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 588 | class PathFinder: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 589 | |
| 590 | """Meta path finder for sys.(path|path_hooks|path_importer_cache).""" |
| 591 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 592 | @classmethod |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 593 | def _path_hooks(cls, path, hooks=None): |
| 594 | """Search sequence of hooks for a finder for 'path'. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 595 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 596 | If 'hooks' is false then use sys.path_hooks. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 597 | |
| 598 | """ |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 599 | if not hooks: |
| 600 | hooks = sys.path_hooks |
| 601 | for hook in hooks: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 602 | try: |
| 603 | return hook(path) |
| 604 | except ImportError: |
| 605 | continue |
| 606 | else: |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 607 | raise ImportError("no path hook found for {0}".format(path)) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 608 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 609 | @classmethod |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 610 | def _path_importer_cache(cls, path, default=None): |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 611 | """Get the finder for the path from sys.path_importer_cache. |
| 612 | |
| 613 | If the path is not in the cache, find the appropriate finder and cache |
| 614 | it. If None is cached, get the default finder and cache that |
| 615 | (if applicable). |
| 616 | |
| 617 | Because of NullImporter, some finder should be returned. The only |
| 618 | explicit fail case is if None is cached but the path cannot be used for |
| 619 | the default hook, for which ImportError is raised. |
| 620 | |
| 621 | """ |
| 622 | try: |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 623 | finder = sys.path_importer_cache[path] |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 624 | except KeyError: |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 625 | finder = cls._path_hooks(path) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 626 | sys.path_importer_cache[path] = finder |
| 627 | else: |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 628 | if finder is None and default: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 629 | # Raises ImportError on failure. |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 630 | finder = default(path) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 631 | sys.path_importer_cache[path] = finder |
| 632 | return finder |
| 633 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 634 | @classmethod |
| 635 | def find_module(cls, fullname, path=None): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 636 | """Find the module on sys.path or 'path' based on sys.path_hooks and |
| 637 | sys.path_importer_cache.""" |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 638 | if not path: |
| 639 | path = sys.path |
| 640 | for entry in path: |
| 641 | try: |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 642 | finder = cls._path_importer_cache(entry) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 643 | except ImportError: |
| 644 | continue |
Brett Cannon | 8593a75 | 2009-03-30 19:57:15 +0000 | [diff] [blame] | 645 | if finder: |
| 646 | loader = finder.find_module(fullname) |
| 647 | if loader: |
| 648 | return loader |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 649 | else: |
| 650 | return None |
| 651 | |
| 652 | |
Brett Cannon | f87e04d | 2009-03-12 22:47:53 +0000 | [diff] [blame] | 653 | class _FileFinder: |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 654 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 655 | """File-based finder. |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 656 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 657 | Constructor takes a list of objects detailing what file extensions their |
| 658 | loader supports along with whether it can be used for a package. |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 659 | |
| 660 | """ |
| 661 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 662 | def __init__(self, path, *details): |
| 663 | """Initialize with finder details.""" |
| 664 | packages = [] |
| 665 | modules = [] |
| 666 | for detail in details: |
| 667 | modules.extend((suffix, detail.loader) for suffix in detail.suffixes) |
| 668 | if detail.supports_packages: |
| 669 | packages.extend((suffix, detail.loader) |
| 670 | for suffix in detail.suffixes) |
| 671 | self.packages = packages |
| 672 | self.modules = modules |
| 673 | self.path = path |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 674 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 675 | def find_module(self, fullname): |
| 676 | """Try to find a loader for the specified module.""" |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 677 | tail_module = fullname.rpartition('.')[2] |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 678 | base_path = _path_join(self.path, tail_module) |
| 679 | if _path_isdir(base_path) and _case_ok(self.path, tail_module): |
| 680 | for suffix, loader in self.packages: |
| 681 | init_filename = '__init__' + suffix |
| 682 | full_path = _path_join(base_path, init_filename) |
| 683 | if (_path_isfile(full_path) and |
| 684 | _case_ok(base_path, init_filename)): |
| 685 | return loader(fullname, full_path) |
| 686 | else: |
| 687 | msg = "Not importing directory {}: missing __init__" |
| 688 | _warnings.warn(msg.format(base_path), ImportWarning) |
| 689 | for suffix, loader in self.modules: |
| 690 | mod_filename = tail_module + suffix |
| 691 | full_path = _path_join(self.path, mod_filename) |
| 692 | if _path_isfile(full_path) and _case_ok(self.path, mod_filename): |
| 693 | return loader(fullname, full_path) |
| 694 | return None |
| 695 | |
| 696 | class _SourceFinderDetails: |
| 697 | |
| 698 | loader = _SourceFileLoader |
| 699 | supports_packages = True |
| 700 | |
| 701 | def __init__(self): |
| 702 | self.suffixes = _suffix_list(imp.PY_SOURCE) |
| 703 | |
| 704 | class _SourcelessFinderDetails: |
| 705 | |
| 706 | loader = _SourcelessFileLoader |
| 707 | supports_packages = True |
| 708 | |
| 709 | def __init__(self): |
| 710 | self.suffixes = _suffix_list(imp.PY_COMPILED) |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 711 | |
| 712 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 713 | class _ExtensionFinderDetails: |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 714 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 715 | loader = _ExtensionFileLoader |
| 716 | supports_packages = False |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 717 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 718 | def __init__(self): |
| 719 | self.suffixes = _suffix_list(imp.C_EXTENSION) |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 720 | |
| 721 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 722 | # Import itself ############################################################### |
| 723 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 724 | def _file_path_hook(path): |
| 725 | """If the path is a directory, return a file-based finder.""" |
| 726 | if _path_isdir(path): |
| 727 | return _FileFinder(path, _ExtensionFinderDetails(), |
| 728 | _SourceFinderDetails(), |
| 729 | _SourcelessFinderDetails()) |
| 730 | else: |
| 731 | raise ImportError("only directories are supported") |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 732 | |
| 733 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 734 | _DEFAULT_PATH_HOOK = _file_path_hook |
Brett Cannon | 2dee597 | 2009-02-21 03:15:37 +0000 | [diff] [blame] | 735 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 736 | class _DefaultPathFinder(PathFinder): |
| 737 | |
| 738 | """Subclass of PathFinder that implements implicit semantics for |
| 739 | __import__.""" |
| 740 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 741 | @classmethod |
| 742 | def _path_hooks(cls, path): |
| 743 | """Search sys.path_hooks as well as implicit path hooks.""" |
| 744 | try: |
| 745 | return super()._path_hooks(path) |
| 746 | except ImportError: |
Brett Cannon | 2dee597 | 2009-02-21 03:15:37 +0000 | [diff] [blame] | 747 | implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter] |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 748 | return super()._path_hooks(path, implicit_hooks) |
| 749 | |
| 750 | @classmethod |
| 751 | def _path_importer_cache(cls, path): |
| 752 | """Use the default path hook when None is stored in |
| 753 | sys.path_importer_cache.""" |
Brett Cannon | 2dee597 | 2009-02-21 03:15:37 +0000 | [diff] [blame] | 754 | return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK) |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 755 | |
| 756 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 757 | class _ImportLockContext: |
| 758 | |
| 759 | """Context manager for the import lock.""" |
| 760 | |
| 761 | def __enter__(self): |
| 762 | """Acquire the import lock.""" |
| 763 | imp.acquire_lock() |
| 764 | |
| 765 | def __exit__(self, exc_type, exc_value, exc_traceback): |
| 766 | """Release the import lock regardless of any raised exceptions.""" |
| 767 | imp.release_lock() |
| 768 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 769 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 770 | _IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder] |
| 771 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 772 | def _gcd_import(name, package=None, level=0): |
| 773 | """Import and return the module based on its name, the package the call is |
| 774 | being made from, and the level adjustment. |
| 775 | |
| 776 | This function represents the greatest common denominator of functionality |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 777 | between import_module and __import__. This includes settting __package__ if |
| 778 | the loader did not. |
| 779 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 780 | """ |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 781 | if package: |
| 782 | if not hasattr(package, 'rindex'): |
| 783 | raise ValueError("__package__ not set to a string") |
| 784 | elif package not in sys.modules: |
| 785 | msg = ("Parent module {0!r} not loaded, cannot perform relative " |
| 786 | "import") |
| 787 | raise SystemError(msg.format(package)) |
| 788 | if not name and level == 0: |
| 789 | raise ValueError("Empty module name") |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 790 | if level > 0: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 791 | dot = len(package) |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 792 | for x in range(level, 1, -1): |
| 793 | try: |
| 794 | dot = package.rindex('.', 0, dot) |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 795 | except ValueError: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 796 | raise ValueError("attempted relative import beyond " |
| 797 | "top-level package") |
| 798 | if name: |
| 799 | name = "{0}.{1}".format(package[:dot], name) |
| 800 | else: |
| 801 | name = package[:dot] |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 802 | with _ImportLockContext(): |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 803 | try: |
Brett Cannon | 4d75fc1 | 2009-08-30 03:47:36 +0000 | [diff] [blame] | 804 | module = sys.modules[name] |
| 805 | if module is None: |
| 806 | message = ("import of {} halted; " |
| 807 | "None in sys.modules".format(name)) |
| 808 | raise ImportError(message) |
| 809 | return module |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 810 | except KeyError: |
| 811 | pass |
| 812 | parent = name.rpartition('.')[0] |
| 813 | path = None |
| 814 | if parent: |
| 815 | if parent not in sys.modules: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 816 | _gcd_import(parent) |
| 817 | # Backwards-compatibility; be nicer to skip the dict lookup. |
| 818 | parent_module = sys.modules[parent] |
Brett Cannon | 1c1dcbf | 2009-08-30 20:22:21 +0000 | [diff] [blame] | 819 | try: |
| 820 | path = parent_module.__path__ |
| 821 | except AttributeError: |
| 822 | raise ImportError("no module named {}; " |
| 823 | "{} is not a package".format(name, parent)) |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 824 | meta_path = sys.meta_path + _IMPLICIT_META_PATH |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 825 | for finder in meta_path: |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 826 | loader = finder.find_module(name, path) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 827 | if loader is not None: |
| 828 | loader.load_module(name) |
| 829 | break |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 830 | else: |
| 831 | raise ImportError("No module named {0}".format(name)) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 832 | # Backwards-compatibility; be nicer to skip the dict lookup. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 833 | module = sys.modules[name] |
| 834 | if parent: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 835 | # Set the module as an attribute on its parent. |
| 836 | setattr(parent_module, name.rpartition('.')[2], module) |
| 837 | # Set __package__ if the loader did not. |
| 838 | if not hasattr(module, '__package__') or module.__package__ is None: |
| 839 | # Watch out for what comes out of sys.modules to not be a module, |
| 840 | # e.g. an int. |
| 841 | try: |
| 842 | module.__package__ = module.__name__ |
| 843 | if not hasattr(module, '__path__'): |
| 844 | module.__package__ = module.__package__.rpartition('.')[0] |
| 845 | except AttributeError: |
| 846 | pass |
| 847 | return module |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 848 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 849 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 850 | def __import__(name, globals={}, locals={}, fromlist=[], level=0): |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 851 | """Import a module. |
| 852 | |
| 853 | The 'globals' argument is used to infer where the import is occuring from |
| 854 | to handle relative imports. The 'locals' argument is ignored. The |
| 855 | 'fromlist' argument specifies what should exist as attributes on the module |
| 856 | being imported (e.g. ``from module import <fromlist>``). The 'level' |
| 857 | argument represents the package location to import from in a relative |
| 858 | import (e.g. ``from ..pkg import mod`` would have a 'level' of 2). |
| 859 | |
| 860 | """ |
Brett Cannon | 6afbaef | 2009-08-30 19:08:58 +0000 | [diff] [blame] | 861 | if not hasattr(name, 'rpartition'): |
| 862 | raise TypeError("module name must be str, not {}".format(type(name))) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 863 | if level == 0: |
| 864 | module = _gcd_import(name) |
| 865 | else: |
Brett Cannon | de4ebfe | 2009-08-30 19:53:48 +0000 | [diff] [blame] | 866 | # __package__ is not guaranteed to be defined or could be set to None |
| 867 | # to represent that it's proper value is unknown |
| 868 | package = globals.get('__package__') |
| 869 | if package is None: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 870 | package = globals['__name__'] |
| 871 | if '__path__' not in globals: |
| 872 | package = package.rpartition('.')[0] |
| 873 | module = _gcd_import(name, package, level) |
| 874 | # The hell that is fromlist ... |
| 875 | if not fromlist: |
| 876 | # Return up to the first dot in 'name'. This is complicated by the fact |
| 877 | # that 'name' may be relative. |
| 878 | if level == 0: |
| 879 | return sys.modules[name.partition('.')[0]] |
| 880 | elif not name: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 881 | return module |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 882 | else: |
| 883 | cut_off = len(name) - len(name.partition('.')[0]) |
| 884 | return sys.modules[module.__name__[:-cut_off]] |
| 885 | else: |
| 886 | # If a package was imported, try to import stuff from fromlist. |
| 887 | if hasattr(module, '__path__'): |
| 888 | if '*' in fromlist and hasattr(module, '__all__'): |
Brett Cannon | 9e0e1a6 | 2009-08-30 18:28:46 +0000 | [diff] [blame] | 889 | fromlist = list(fromlist) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 890 | fromlist.remove('*') |
| 891 | fromlist.extend(module.__all__) |
| 892 | for x in (y for y in fromlist if not hasattr(module,y)): |
| 893 | try: |
| 894 | _gcd_import('{0}.{1}'.format(module.__name__, x)) |
| 895 | except ImportError: |
| 896 | pass |
| 897 | return module |