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