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