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.""" |
| 485 | try: |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 486 | with _closing(_io.FileIO(path, 'wb')) as file: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 487 | file.write(data) |
| 488 | except IOError as exc: |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 489 | if exc.errno == errno.ENOENT: |
| 490 | directory, _, filename = path.rpartition(path_sep) |
| 491 | sub_directories = [] |
| 492 | while not _path_isdir(directory): |
| 493 | directory, _, sub_dir = directory.rpartition(path_sep) |
| 494 | sub_directories.append(sub_dir) |
| 495 | for part in reversed(sub_directories): |
| 496 | directory = _path_join(directory, part) |
| 497 | try: |
| 498 | _os.mkdir(directory) |
| 499 | except IOError as exc: |
| 500 | if exc.errno != errno.EACCES: |
| 501 | raise |
| 502 | else: |
| 503 | return |
| 504 | return self.set_data(path, data) |
| 505 | elif exc.errno != errno.EACCES: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 506 | raise |
| 507 | |
| 508 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 509 | class _SourcelessFileLoader(_FileLoader, _LoaderBasics): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 510 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 511 | """Loader which handles sourceless file imports.""" |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 512 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 513 | def load_module(self, fullname): |
| 514 | return self._load_module(fullname, sourceless=True) |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 515 | |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 516 | def get_code(self, fullname): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 517 | path = self.get_filename(fullname) |
| 518 | data = self.get_data(path) |
| 519 | bytes_data = self._bytes_from_bytecode(fullname, data, None) |
| 520 | found = marshal.loads(bytes_data) |
| 521 | if isinstance(found, code_type): |
| 522 | return found |
| 523 | else: |
| 524 | raise ImportError("Non-code object in {}".format(path)) |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 525 | |
Brett Cannon | d43b30b | 2009-03-10 03:29:23 +0000 | [diff] [blame] | 526 | def get_source(self, fullname): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 527 | """Return None as there is no source code.""" |
| 528 | return None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 529 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 530 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 531 | class _ExtensionFileLoader: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 532 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 533 | """Loader for extension modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 534 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 535 | The constructor is designed to work with FileFinder. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 536 | |
| 537 | """ |
| 538 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 539 | def __init__(self, name, path): |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 540 | """Initialize the loader. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 541 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 542 | If is_pkg is True then an exception is raised as extension modules |
| 543 | cannot be the __init__ module for an extension module. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 544 | |
| 545 | """ |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 546 | self._name = name |
| 547 | self._path = path |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 548 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 549 | @_check_name |
| 550 | @set_package |
| 551 | @set_loader |
| 552 | def load_module(self, fullname): |
| 553 | """Load an extension module.""" |
| 554 | is_reload = fullname in sys.modules |
| 555 | try: |
| 556 | return imp.load_dynamic(fullname, self._path) |
| 557 | except: |
| 558 | if not is_reload and fullname in sys.modules: |
| 559 | del sys.modules[fullname] |
| 560 | raise |
| 561 | |
| 562 | @_check_name |
| 563 | def is_package(self, fullname): |
| 564 | """Return False as an extension module can never be a package.""" |
| 565 | return False |
| 566 | |
| 567 | @_check_name |
| 568 | def get_code(self, fullname): |
| 569 | """Return None as an extension module cannot create a code object.""" |
| 570 | return None |
| 571 | |
| 572 | @_check_name |
| 573 | def get_source(self, fullname): |
| 574 | """Return None as extension modules have no source code.""" |
| 575 | return None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 576 | |
| 577 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 578 | # Finders ##################################################################### |
Brett Cannon | 4afab6b | 2009-02-21 03:31:35 +0000 | [diff] [blame] | 579 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 580 | class PathFinder: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 581 | |
| 582 | """Meta path finder for sys.(path|path_hooks|path_importer_cache).""" |
| 583 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 584 | @classmethod |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 585 | def _path_hooks(cls, path, hooks=None): |
| 586 | """Search sequence of hooks for a finder for 'path'. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 587 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 588 | If 'hooks' is false then use sys.path_hooks. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 589 | |
| 590 | """ |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 591 | if not hooks: |
| 592 | hooks = sys.path_hooks |
| 593 | for hook in hooks: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 594 | try: |
| 595 | return hook(path) |
| 596 | except ImportError: |
| 597 | continue |
| 598 | else: |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 599 | raise ImportError("no path hook found for {0}".format(path)) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 600 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 601 | @classmethod |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 602 | def _path_importer_cache(cls, path, default=None): |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 603 | """Get the finder for the path from sys.path_importer_cache. |
| 604 | |
| 605 | If the path is not in the cache, find the appropriate finder and cache |
| 606 | it. If None is cached, get the default finder and cache that |
| 607 | (if applicable). |
| 608 | |
| 609 | Because of NullImporter, some finder should be returned. The only |
| 610 | explicit fail case is if None is cached but the path cannot be used for |
| 611 | the default hook, for which ImportError is raised. |
| 612 | |
| 613 | """ |
| 614 | try: |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 615 | finder = sys.path_importer_cache[path] |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 616 | except KeyError: |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 617 | finder = cls._path_hooks(path) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 618 | sys.path_importer_cache[path] = finder |
| 619 | else: |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 620 | if finder is None and default: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 621 | # Raises ImportError on failure. |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 622 | finder = default(path) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 623 | sys.path_importer_cache[path] = finder |
| 624 | return finder |
| 625 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 626 | @classmethod |
| 627 | def find_module(cls, fullname, path=None): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 628 | """Find the module on sys.path or 'path' based on sys.path_hooks and |
| 629 | sys.path_importer_cache.""" |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 630 | if not path: |
| 631 | path = sys.path |
| 632 | for entry in path: |
| 633 | try: |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 634 | finder = cls._path_importer_cache(entry) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 635 | except ImportError: |
| 636 | continue |
Brett Cannon | 8593a75 | 2009-03-30 19:57:15 +0000 | [diff] [blame] | 637 | if finder: |
| 638 | loader = finder.find_module(fullname) |
| 639 | if loader: |
| 640 | return loader |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 641 | else: |
| 642 | return None |
| 643 | |
| 644 | |
Brett Cannon | f87e04d | 2009-03-12 22:47:53 +0000 | [diff] [blame] | 645 | class _FileFinder: |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 646 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 647 | """File-based finder. |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 648 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 649 | Constructor takes a list of objects detailing what file extensions their |
| 650 | loader supports along with whether it can be used for a package. |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 651 | |
| 652 | """ |
| 653 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 654 | def __init__(self, path, *details): |
| 655 | """Initialize with finder details.""" |
| 656 | packages = [] |
| 657 | modules = [] |
| 658 | for detail in details: |
| 659 | modules.extend((suffix, detail.loader) for suffix in detail.suffixes) |
| 660 | if detail.supports_packages: |
| 661 | packages.extend((suffix, detail.loader) |
| 662 | for suffix in detail.suffixes) |
| 663 | self.packages = packages |
| 664 | self.modules = modules |
| 665 | self.path = path |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 666 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 667 | def find_module(self, fullname): |
| 668 | """Try to find a loader for the specified module.""" |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 669 | tail_module = fullname.rpartition('.')[2] |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 670 | base_path = _path_join(self.path, tail_module) |
| 671 | if _path_isdir(base_path) and _case_ok(self.path, tail_module): |
| 672 | for suffix, loader in self.packages: |
| 673 | init_filename = '__init__' + suffix |
| 674 | full_path = _path_join(base_path, init_filename) |
| 675 | if (_path_isfile(full_path) and |
| 676 | _case_ok(base_path, init_filename)): |
| 677 | return loader(fullname, full_path) |
| 678 | else: |
| 679 | msg = "Not importing directory {}: missing __init__" |
| 680 | _warnings.warn(msg.format(base_path), ImportWarning) |
| 681 | for suffix, loader in self.modules: |
| 682 | mod_filename = tail_module + suffix |
| 683 | full_path = _path_join(self.path, mod_filename) |
| 684 | if _path_isfile(full_path) and _case_ok(self.path, mod_filename): |
| 685 | return loader(fullname, full_path) |
| 686 | return None |
| 687 | |
| 688 | class _SourceFinderDetails: |
| 689 | |
| 690 | loader = _SourceFileLoader |
| 691 | supports_packages = True |
| 692 | |
| 693 | def __init__(self): |
| 694 | self.suffixes = _suffix_list(imp.PY_SOURCE) |
| 695 | |
| 696 | class _SourcelessFinderDetails: |
| 697 | |
| 698 | loader = _SourcelessFileLoader |
| 699 | supports_packages = True |
| 700 | |
| 701 | def __init__(self): |
| 702 | self.suffixes = _suffix_list(imp.PY_COMPILED) |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 703 | |
| 704 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 705 | class _ExtensionFinderDetails: |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 706 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 707 | loader = _ExtensionFileLoader |
| 708 | supports_packages = False |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 709 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 710 | def __init__(self): |
| 711 | self.suffixes = _suffix_list(imp.C_EXTENSION) |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 712 | |
| 713 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 714 | # Import itself ############################################################### |
| 715 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 716 | def _file_path_hook(path): |
| 717 | """If the path is a directory, return a file-based finder.""" |
| 718 | if _path_isdir(path): |
| 719 | return _FileFinder(path, _ExtensionFinderDetails(), |
| 720 | _SourceFinderDetails(), |
| 721 | _SourcelessFinderDetails()) |
| 722 | else: |
| 723 | raise ImportError("only directories are supported") |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 724 | |
| 725 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 726 | _DEFAULT_PATH_HOOK = _file_path_hook |
Brett Cannon | 2dee597 | 2009-02-21 03:15:37 +0000 | [diff] [blame] | 727 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 728 | class _DefaultPathFinder(PathFinder): |
| 729 | |
| 730 | """Subclass of PathFinder that implements implicit semantics for |
| 731 | __import__.""" |
| 732 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 733 | @classmethod |
| 734 | def _path_hooks(cls, path): |
| 735 | """Search sys.path_hooks as well as implicit path hooks.""" |
| 736 | try: |
| 737 | return super()._path_hooks(path) |
| 738 | except ImportError: |
Brett Cannon | 2dee597 | 2009-02-21 03:15:37 +0000 | [diff] [blame] | 739 | implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter] |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 740 | return super()._path_hooks(path, implicit_hooks) |
| 741 | |
| 742 | @classmethod |
| 743 | def _path_importer_cache(cls, path): |
| 744 | """Use the default path hook when None is stored in |
| 745 | sys.path_importer_cache.""" |
Brett Cannon | 2dee597 | 2009-02-21 03:15:37 +0000 | [diff] [blame] | 746 | return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK) |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 747 | |
| 748 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 749 | class _ImportLockContext: |
| 750 | |
| 751 | """Context manager for the import lock.""" |
| 752 | |
| 753 | def __enter__(self): |
| 754 | """Acquire the import lock.""" |
| 755 | imp.acquire_lock() |
| 756 | |
| 757 | def __exit__(self, exc_type, exc_value, exc_traceback): |
| 758 | """Release the import lock regardless of any raised exceptions.""" |
| 759 | imp.release_lock() |
| 760 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 761 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 762 | _IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder] |
| 763 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 764 | def _gcd_import(name, package=None, level=0): |
| 765 | """Import and return the module based on its name, the package the call is |
| 766 | being made from, and the level adjustment. |
| 767 | |
| 768 | This function represents the greatest common denominator of functionality |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 769 | between import_module and __import__. This includes settting __package__ if |
| 770 | the loader did not. |
| 771 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 772 | """ |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 773 | if package: |
| 774 | if not hasattr(package, 'rindex'): |
| 775 | raise ValueError("__package__ not set to a string") |
| 776 | elif package not in sys.modules: |
| 777 | msg = ("Parent module {0!r} not loaded, cannot perform relative " |
| 778 | "import") |
| 779 | raise SystemError(msg.format(package)) |
| 780 | if not name and level == 0: |
| 781 | raise ValueError("Empty module name") |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 782 | if level > 0: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 783 | dot = len(package) |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 784 | for x in range(level, 1, -1): |
| 785 | try: |
| 786 | dot = package.rindex('.', 0, dot) |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 787 | except ValueError: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 788 | raise ValueError("attempted relative import beyond " |
| 789 | "top-level package") |
| 790 | if name: |
| 791 | name = "{0}.{1}".format(package[:dot], name) |
| 792 | else: |
| 793 | name = package[:dot] |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 794 | with _ImportLockContext(): |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 795 | try: |
Brett Cannon | 4d75fc1 | 2009-08-30 03:47:36 +0000 | [diff] [blame] | 796 | module = sys.modules[name] |
| 797 | if module is None: |
| 798 | message = ("import of {} halted; " |
| 799 | "None in sys.modules".format(name)) |
| 800 | raise ImportError(message) |
| 801 | return module |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 802 | except KeyError: |
| 803 | pass |
| 804 | parent = name.rpartition('.')[0] |
| 805 | path = None |
| 806 | if parent: |
| 807 | if parent not in sys.modules: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 808 | _gcd_import(parent) |
| 809 | # Backwards-compatibility; be nicer to skip the dict lookup. |
| 810 | parent_module = sys.modules[parent] |
Brett Cannon | 1c1dcbf | 2009-08-30 20:22:21 +0000 | [diff] [blame] | 811 | try: |
| 812 | path = parent_module.__path__ |
| 813 | except AttributeError: |
| 814 | raise ImportError("no module named {}; " |
| 815 | "{} is not a package".format(name, parent)) |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 816 | meta_path = sys.meta_path + _IMPLICIT_META_PATH |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 817 | for finder in meta_path: |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 818 | loader = finder.find_module(name, path) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 819 | if loader is not None: |
| 820 | loader.load_module(name) |
| 821 | break |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 822 | else: |
| 823 | raise ImportError("No module named {0}".format(name)) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 824 | # Backwards-compatibility; be nicer to skip the dict lookup. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 825 | module = sys.modules[name] |
| 826 | if parent: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 827 | # Set the module as an attribute on its parent. |
| 828 | setattr(parent_module, name.rpartition('.')[2], module) |
| 829 | # Set __package__ if the loader did not. |
| 830 | if not hasattr(module, '__package__') or module.__package__ is None: |
| 831 | # Watch out for what comes out of sys.modules to not be a module, |
| 832 | # e.g. an int. |
| 833 | try: |
| 834 | module.__package__ = module.__name__ |
| 835 | if not hasattr(module, '__path__'): |
| 836 | module.__package__ = module.__package__.rpartition('.')[0] |
| 837 | except AttributeError: |
| 838 | pass |
| 839 | return module |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 840 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 841 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 842 | def __import__(name, globals={}, locals={}, fromlist=[], level=0): |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 843 | """Import a module. |
| 844 | |
| 845 | The 'globals' argument is used to infer where the import is occuring from |
| 846 | to handle relative imports. The 'locals' argument is ignored. The |
| 847 | 'fromlist' argument specifies what should exist as attributes on the module |
| 848 | being imported (e.g. ``from module import <fromlist>``). The 'level' |
| 849 | argument represents the package location to import from in a relative |
| 850 | import (e.g. ``from ..pkg import mod`` would have a 'level' of 2). |
| 851 | |
| 852 | """ |
Brett Cannon | 6afbaef | 2009-08-30 19:08:58 +0000 | [diff] [blame] | 853 | if not hasattr(name, 'rpartition'): |
| 854 | raise TypeError("module name must be str, not {}".format(type(name))) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 855 | if level == 0: |
| 856 | module = _gcd_import(name) |
| 857 | else: |
Brett Cannon | de4ebfe | 2009-08-30 19:53:48 +0000 | [diff] [blame] | 858 | # __package__ is not guaranteed to be defined or could be set to None |
| 859 | # to represent that it's proper value is unknown |
| 860 | package = globals.get('__package__') |
| 861 | if package is None: |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 862 | package = globals['__name__'] |
| 863 | if '__path__' not in globals: |
| 864 | package = package.rpartition('.')[0] |
| 865 | module = _gcd_import(name, package, level) |
| 866 | # The hell that is fromlist ... |
| 867 | if not fromlist: |
| 868 | # Return up to the first dot in 'name'. This is complicated by the fact |
| 869 | # that 'name' may be relative. |
| 870 | if level == 0: |
| 871 | return sys.modules[name.partition('.')[0]] |
| 872 | elif not name: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 873 | return module |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 874 | else: |
| 875 | cut_off = len(name) - len(name.partition('.')[0]) |
| 876 | return sys.modules[module.__name__[:-cut_off]] |
| 877 | else: |
| 878 | # If a package was imported, try to import stuff from fromlist. |
| 879 | if hasattr(module, '__path__'): |
| 880 | if '*' in fromlist and hasattr(module, '__all__'): |
Brett Cannon | 9e0e1a6 | 2009-08-30 18:28:46 +0000 | [diff] [blame] | 881 | fromlist = list(fromlist) |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 882 | fromlist.remove('*') |
| 883 | fromlist.extend(module.__all__) |
| 884 | for x in (y for y in fromlist if not hasattr(module,y)): |
| 885 | try: |
| 886 | _gcd_import('{0}.{1}'.format(module.__name__, x)) |
| 887 | except ImportError: |
| 888 | pass |
| 889 | return module |