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 | """ |
Marc-Andre Lemburg | 7541c8e | 2012-04-25 10:54:48 +0200 | [diff] [blame] | 9 | # |
| 10 | # IMPORTANT: Whenever making changes to this module, be sure to run |
| 11 | # a top-level make in order to get the frozen version of the module |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 12 | # updated. Not doing so will result in the Makefile to fail for |
Marc-Andre Lemburg | 7541c8e | 2012-04-25 10:54:48 +0200 | [diff] [blame] | 13 | # all others who don't have a ./python around to freeze the module |
| 14 | # in the early stages of compilation. |
| 15 | # |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 16 | |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 17 | # See importlib._setup() for what is injected into the global namespace. |
| 18 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 19 | # When editing this code be aware that code executed at import time CANNOT |
| 20 | # reference any injected objects! This includes not only global code but also |
| 21 | # anything specified at the class level. |
| 22 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 23 | # Bootstrap-related code ###################################################### |
| 24 | |
Eric Snow | 183a941 | 2015-05-15 21:54:59 -0600 | [diff] [blame] | 25 | _bootstrap_external = None |
| 26 | |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 27 | def _wrap(new, old): |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 28 | """Simple substitute for functools.update_wrapper.""" |
Meador Inge | 96ff084 | 2011-12-14 22:53:13 -0600 | [diff] [blame] | 29 | for replace in ['__module__', '__name__', '__qualname__', '__doc__']: |
Brett Cannon | 8490fab | 2012-02-08 18:44:14 -0500 | [diff] [blame] | 30 | if hasattr(old, replace): |
| 31 | setattr(new, replace, getattr(old, replace)) |
Brett Cannon | 51d8bfc | 2009-02-07 02:13:28 +0000 | [diff] [blame] | 32 | new.__dict__.update(old.__dict__) |
| 33 | |
| 34 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 35 | def _new_module(name): |
| 36 | return type(sys)(name) |
| 37 | |
| 38 | |
Brett Cannon | d2476c6 | 2013-11-29 11:00:11 -0500 | [diff] [blame] | 39 | class _ManageReload: |
| 40 | |
| 41 | """Manages the possible clean-up of sys.modules for load_module().""" |
| 42 | |
| 43 | def __init__(self, name): |
| 44 | self._name = name |
| 45 | |
| 46 | def __enter__(self): |
| 47 | self._is_reload = self._name in sys.modules |
| 48 | |
| 49 | def __exit__(self, *args): |
| 50 | if any(arg is not None for arg in args) and not self._is_reload: |
| 51 | try: |
| 52 | del sys.modules[self._name] |
| 53 | except KeyError: |
| 54 | pass |
| 55 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 56 | # Module-level locking ######################################################## |
| 57 | |
| 58 | # A dict mapping module names to weakrefs of _ModuleLock instances |
| 59 | _module_locks = {} |
| 60 | # A dict mapping thread ids to _ModuleLock instances |
| 61 | _blocking_on = {} |
| 62 | |
| 63 | |
| 64 | class _DeadlockError(RuntimeError): |
| 65 | pass |
| 66 | |
| 67 | |
| 68 | class _ModuleLock: |
| 69 | """A recursive lock implementation which is able to detect deadlocks |
| 70 | (e.g. thread 1 trying to take locks A then B, and thread 2 trying to |
| 71 | take locks B then A). |
| 72 | """ |
| 73 | |
| 74 | def __init__(self, name): |
| 75 | self.lock = _thread.allocate_lock() |
| 76 | self.wakeup = _thread.allocate_lock() |
| 77 | self.name = name |
| 78 | self.owner = None |
| 79 | self.count = 0 |
| 80 | self.waiters = 0 |
| 81 | |
| 82 | def has_deadlock(self): |
| 83 | # Deadlock avoidance for concurrent circular imports. |
| 84 | me = _thread.get_ident() |
| 85 | tid = self.owner |
| 86 | while True: |
| 87 | lock = _blocking_on.get(tid) |
| 88 | if lock is None: |
| 89 | return False |
| 90 | tid = lock.owner |
| 91 | if tid == me: |
| 92 | return True |
| 93 | |
| 94 | def acquire(self): |
| 95 | """ |
| 96 | Acquire the module lock. If a potential deadlock is detected, |
| 97 | a _DeadlockError is raised. |
| 98 | Otherwise, the lock is always acquired and True is returned. |
| 99 | """ |
| 100 | tid = _thread.get_ident() |
| 101 | _blocking_on[tid] = self |
| 102 | try: |
| 103 | while True: |
| 104 | with self.lock: |
| 105 | if self.count == 0 or self.owner == tid: |
| 106 | self.owner = tid |
| 107 | self.count += 1 |
| 108 | return True |
| 109 | if self.has_deadlock(): |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 110 | raise _DeadlockError('deadlock detected by %r' % self) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 111 | if self.wakeup.acquire(False): |
| 112 | self.waiters += 1 |
| 113 | # Wait for a release() call |
| 114 | self.wakeup.acquire() |
| 115 | self.wakeup.release() |
| 116 | finally: |
| 117 | del _blocking_on[tid] |
| 118 | |
| 119 | def release(self): |
| 120 | tid = _thread.get_ident() |
| 121 | with self.lock: |
| 122 | if self.owner != tid: |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 123 | raise RuntimeError('cannot release un-acquired lock') |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 124 | assert self.count > 0 |
| 125 | self.count -= 1 |
| 126 | if self.count == 0: |
| 127 | self.owner = None |
| 128 | if self.waiters: |
| 129 | self.waiters -= 1 |
| 130 | self.wakeup.release() |
| 131 | |
| 132 | def __repr__(self): |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 133 | return '_ModuleLock({!r}) at {}'.format(self.name, id(self)) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 134 | |
| 135 | |
| 136 | class _DummyModuleLock: |
| 137 | """A simple _ModuleLock equivalent for Python builds without |
| 138 | multi-threading support.""" |
| 139 | |
| 140 | def __init__(self, name): |
| 141 | self.name = name |
| 142 | self.count = 0 |
| 143 | |
| 144 | def acquire(self): |
| 145 | self.count += 1 |
| 146 | return True |
| 147 | |
| 148 | def release(self): |
| 149 | if self.count == 0: |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 150 | raise RuntimeError('cannot release un-acquired lock') |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 151 | self.count -= 1 |
| 152 | |
| 153 | def __repr__(self): |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 154 | return '_DummyModuleLock({!r}) at {}'.format(self.name, id(self)) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 155 | |
| 156 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 157 | class _ModuleLockManager: |
| 158 | |
| 159 | def __init__(self, name): |
| 160 | self._name = name |
| 161 | self._lock = None |
| 162 | |
| 163 | def __enter__(self): |
| 164 | try: |
| 165 | self._lock = _get_module_lock(self._name) |
| 166 | finally: |
| 167 | _imp.release_lock() |
| 168 | self._lock.acquire() |
| 169 | |
| 170 | def __exit__(self, *args, **kwargs): |
| 171 | self._lock.release() |
| 172 | |
| 173 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 174 | # The following two functions are for consumption by Python/import.c. |
| 175 | |
| 176 | def _get_module_lock(name): |
| 177 | """Get or create the module lock for a given module name. |
| 178 | |
| 179 | Should only be called with the import lock taken.""" |
| 180 | lock = None |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 181 | try: |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 182 | lock = _module_locks[name]() |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 183 | except KeyError: |
| 184 | pass |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 185 | if lock is None: |
| 186 | if _thread is None: |
| 187 | lock = _DummyModuleLock(name) |
| 188 | else: |
| 189 | lock = _ModuleLock(name) |
| 190 | def cb(_): |
| 191 | del _module_locks[name] |
| 192 | _module_locks[name] = _weakref.ref(lock, cb) |
| 193 | return lock |
| 194 | |
| 195 | def _lock_unlock_module(name): |
| 196 | """Release the global import lock, and acquires then release the |
| 197 | module lock for a given module name. |
| 198 | This is used to ensure a module is completely initialized, in the |
| 199 | event it is being imported by another thread. |
| 200 | |
| 201 | Should only be called with the import lock taken.""" |
| 202 | lock = _get_module_lock(name) |
| 203 | _imp.release_lock() |
| 204 | try: |
| 205 | lock.acquire() |
| 206 | except _DeadlockError: |
| 207 | # Concurrent circular import, we'll accept a partially initialized |
| 208 | # module object. |
| 209 | pass |
| 210 | else: |
| 211 | lock.release() |
| 212 | |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 213 | # Frame stripping magic ############################################### |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 214 | def _call_with_frames_removed(f, *args, **kwds): |
| 215 | """remove_importlib_frames in import.c will always remove sequences |
| 216 | of importlib frames that end with a call to this function |
| 217 | |
| 218 | Use it instead of a normal call in places where including the importlib |
| 219 | frames introduces unwanted noise into the traceback (e.g. when executing |
| 220 | module code) |
| 221 | """ |
| 222 | return f(*args, **kwds) |
| 223 | |
| 224 | |
Brett Cannon | f8ffec0 | 2013-04-01 13:10:51 -0400 | [diff] [blame] | 225 | def _verbose_message(message, *args, verbosity=1): |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 226 | """Print the message to stderr if -v/PYTHONVERBOSE is turned on.""" |
Brett Cannon | f8ffec0 | 2013-04-01 13:10:51 -0400 | [diff] [blame] | 227 | if sys.flags.verbose >= verbosity: |
Philip Jenvey | f8f3190 | 2012-04-15 12:21:32 -0700 | [diff] [blame] | 228 | if not message.startswith(('#', 'import ')): |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 229 | message = '# ' + message |
| 230 | print(message.format(*args), file=sys.stderr) |
| 231 | |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 232 | |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 233 | def _requires_builtin(fxn): |
| 234 | """Decorator to verify the named module is built-in.""" |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 235 | def _requires_builtin_wrapper(self, fullname): |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 236 | if fullname not in sys.builtin_module_names: |
Brett Cannon | 224b261 | 2013-11-22 14:52:36 -0500 | [diff] [blame] | 237 | raise ImportError('{!r} is not a built-in module'.format(fullname), |
Brett Cannon | bbb6680 | 2012-04-12 21:09:01 -0400 | [diff] [blame] | 238 | name=fullname) |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 239 | return fxn(self, fullname) |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 240 | _wrap(_requires_builtin_wrapper, fxn) |
| 241 | return _requires_builtin_wrapper |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 242 | |
| 243 | |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 244 | def _requires_frozen(fxn): |
| 245 | """Decorator to verify the named module is frozen.""" |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 246 | def _requires_frozen_wrapper(self, fullname): |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 247 | if not _imp.is_frozen(fullname): |
Brett Cannon | 224b261 | 2013-11-22 14:52:36 -0500 | [diff] [blame] | 248 | raise ImportError('{!r} is not a frozen module'.format(fullname), |
Brett Cannon | bbb6680 | 2012-04-12 21:09:01 -0400 | [diff] [blame] | 249 | name=fullname) |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 250 | return fxn(self, fullname) |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 251 | _wrap(_requires_frozen_wrapper, fxn) |
| 252 | return _requires_frozen_wrapper |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 253 | |
| 254 | |
Brett Cannon | 42535f0 | 2014-05-30 16:28:00 -0400 | [diff] [blame] | 255 | # Typically used by loader classes as a method replacement. |
| 256 | def _load_module_shim(self, fullname): |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 257 | """Load the specified module into sys.modules and return it. |
| 258 | |
| 259 | This method is deprecated. Use loader.exec_module instead. |
| 260 | |
| 261 | """ |
Brett Cannon | 42535f0 | 2014-05-30 16:28:00 -0400 | [diff] [blame] | 262 | spec = spec_from_loader(fullname, self) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 263 | if fullname in sys.modules: |
| 264 | module = sys.modules[fullname] |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 265 | _exec(spec, module) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 266 | return sys.modules[fullname] |
| 267 | else: |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 268 | return _load(spec) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 269 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 270 | # Module specifications ####################################################### |
| 271 | |
| 272 | def _module_repr(module): |
| 273 | # The implementation of ModuleType__repr__(). |
| 274 | loader = getattr(module, '__loader__', None) |
| 275 | if hasattr(loader, 'module_repr'): |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 276 | # As soon as BuiltinImporter, FrozenImporter, and NamespaceLoader |
| 277 | # drop their implementations for module_repr. we can add a |
| 278 | # deprecation warning here. |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 279 | try: |
| 280 | return loader.module_repr(module) |
| 281 | except Exception: |
| 282 | pass |
| 283 | try: |
| 284 | spec = module.__spec__ |
| 285 | except AttributeError: |
| 286 | pass |
| 287 | else: |
| 288 | if spec is not None: |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 289 | return _module_repr_from_spec(spec) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 290 | |
| 291 | # We could use module.__class__.__name__ instead of 'module' in the |
| 292 | # various repr permutations. |
| 293 | try: |
| 294 | name = module.__name__ |
| 295 | except AttributeError: |
| 296 | name = '?' |
| 297 | try: |
| 298 | filename = module.__file__ |
| 299 | except AttributeError: |
| 300 | if loader is None: |
| 301 | return '<module {!r}>'.format(name) |
| 302 | else: |
| 303 | return '<module {!r} ({!r})>'.format(name, loader) |
| 304 | else: |
| 305 | return '<module {!r} from {!r}>'.format(name, filename) |
| 306 | |
| 307 | |
| 308 | class _installed_safely: |
| 309 | |
| 310 | def __init__(self, module): |
| 311 | self._module = module |
| 312 | self._spec = module.__spec__ |
| 313 | |
| 314 | def __enter__(self): |
| 315 | # This must be done before putting the module in sys.modules |
| 316 | # (otherwise an optimization shortcut in import.c becomes |
| 317 | # wrong) |
| 318 | self._spec._initializing = True |
| 319 | sys.modules[self._spec.name] = self._module |
| 320 | |
| 321 | def __exit__(self, *args): |
| 322 | try: |
| 323 | spec = self._spec |
| 324 | if any(arg is not None for arg in args): |
| 325 | try: |
| 326 | del sys.modules[spec.name] |
| 327 | except KeyError: |
| 328 | pass |
| 329 | else: |
| 330 | _verbose_message('import {!r} # {!r}', spec.name, spec.loader) |
| 331 | finally: |
| 332 | self._spec._initializing = False |
| 333 | |
| 334 | |
| 335 | class ModuleSpec: |
| 336 | """The specification for a module, used for loading. |
| 337 | |
| 338 | A module's spec is the source for information about the module. For |
| 339 | data associated with the module, including source, use the spec's |
| 340 | loader. |
| 341 | |
| 342 | `name` is the absolute name of the module. `loader` is the loader |
| 343 | to use when loading the module. `parent` is the name of the |
| 344 | package the module is in. The parent is derived from the name. |
| 345 | |
| 346 | `is_package` determines if the module is considered a package or |
| 347 | not. On modules this is reflected by the `__path__` attribute. |
| 348 | |
| 349 | `origin` is the specific location used by the loader from which to |
| 350 | load the module, if that information is available. When filename is |
| 351 | set, origin will match. |
| 352 | |
| 353 | `has_location` indicates that a spec's "origin" reflects a location. |
| 354 | When this is True, `__file__` attribute of the module is set. |
| 355 | |
| 356 | `cached` is the location of the cached bytecode file, if any. It |
| 357 | corresponds to the `__cached__` attribute. |
| 358 | |
| 359 | `submodule_search_locations` is the sequence of path entries to |
| 360 | search when importing submodules. If set, is_package should be |
| 361 | True--and False otherwise. |
| 362 | |
| 363 | Packages are simply modules that (may) have submodules. If a spec |
| 364 | has a non-None value in `submodule_search_locations`, the import |
| 365 | system will consider modules loaded from the spec as packages. |
| 366 | |
| 367 | Only finders (see importlib.abc.MetaPathFinder and |
| 368 | importlib.abc.PathEntryFinder) should modify ModuleSpec instances. |
| 369 | |
| 370 | """ |
| 371 | |
| 372 | def __init__(self, name, loader, *, origin=None, loader_state=None, |
| 373 | is_package=None): |
| 374 | self.name = name |
| 375 | self.loader = loader |
| 376 | self.origin = origin |
| 377 | self.loader_state = loader_state |
| 378 | self.submodule_search_locations = [] if is_package else None |
| 379 | |
| 380 | # file-location attributes |
| 381 | self._set_fileattr = False |
| 382 | self._cached = None |
| 383 | |
| 384 | def __repr__(self): |
| 385 | args = ['name={!r}'.format(self.name), |
| 386 | 'loader={!r}'.format(self.loader)] |
| 387 | if self.origin is not None: |
| 388 | args.append('origin={!r}'.format(self.origin)) |
| 389 | if self.submodule_search_locations is not None: |
| 390 | args.append('submodule_search_locations={}' |
| 391 | .format(self.submodule_search_locations)) |
| 392 | return '{}({})'.format(self.__class__.__name__, ', '.join(args)) |
| 393 | |
| 394 | def __eq__(self, other): |
| 395 | smsl = self.submodule_search_locations |
| 396 | try: |
| 397 | return (self.name == other.name and |
| 398 | self.loader == other.loader and |
| 399 | self.origin == other.origin and |
| 400 | smsl == other.submodule_search_locations and |
| 401 | self.cached == other.cached and |
| 402 | self.has_location == other.has_location) |
| 403 | except AttributeError: |
| 404 | return False |
| 405 | |
| 406 | @property |
| 407 | def cached(self): |
| 408 | if self._cached is None: |
| 409 | if self.origin is not None and self._set_fileattr: |
Eric Snow | 183a941 | 2015-05-15 21:54:59 -0600 | [diff] [blame] | 410 | if _bootstrap_external is None: |
| 411 | raise NotImplementedError |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 412 | self._cached = _bootstrap_external._get_cached(self.origin) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 413 | return self._cached |
| 414 | |
| 415 | @cached.setter |
| 416 | def cached(self, cached): |
| 417 | self._cached = cached |
| 418 | |
| 419 | @property |
| 420 | def parent(self): |
| 421 | """The name of the module's parent.""" |
| 422 | if self.submodule_search_locations is None: |
| 423 | return self.name.rpartition('.')[0] |
| 424 | else: |
| 425 | return self.name |
| 426 | |
| 427 | @property |
| 428 | def has_location(self): |
| 429 | return self._set_fileattr |
| 430 | |
Eric Snow | b282b3d | 2013-12-10 22:16:41 -0700 | [diff] [blame] | 431 | @has_location.setter |
| 432 | def has_location(self, value): |
| 433 | self._set_fileattr = bool(value) |
| 434 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 435 | |
| 436 | def spec_from_loader(name, loader, *, origin=None, is_package=None): |
| 437 | """Return a module spec based on various loader methods.""" |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 438 | if hasattr(loader, 'get_filename'): |
Eric Snow | 183a941 | 2015-05-15 21:54:59 -0600 | [diff] [blame] | 439 | if _bootstrap_external is None: |
| 440 | raise NotImplementedError |
| 441 | spec_from_file_location = _bootstrap_external.spec_from_file_location |
| 442 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 443 | if is_package is None: |
| 444 | return spec_from_file_location(name, loader=loader) |
| 445 | search = [] if is_package else None |
| 446 | return spec_from_file_location(name, loader=loader, |
| 447 | submodule_search_locations=search) |
| 448 | |
| 449 | if is_package is None: |
| 450 | if hasattr(loader, 'is_package'): |
| 451 | try: |
| 452 | is_package = loader.is_package(name) |
| 453 | except ImportError: |
| 454 | is_package = None # aka, undefined |
| 455 | else: |
| 456 | # the default |
| 457 | is_package = False |
| 458 | |
| 459 | return ModuleSpec(name, loader, origin=origin, is_package=is_package) |
| 460 | |
| 461 | |
| 462 | _POPULATE = object() |
| 463 | |
| 464 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 465 | def _spec_from_module(module, loader=None, origin=None): |
| 466 | # This function is meant for use in _setup(). |
| 467 | try: |
| 468 | spec = module.__spec__ |
| 469 | except AttributeError: |
| 470 | pass |
| 471 | else: |
| 472 | if spec is not None: |
| 473 | return spec |
| 474 | |
| 475 | name = module.__name__ |
| 476 | if loader is None: |
| 477 | try: |
| 478 | loader = module.__loader__ |
| 479 | except AttributeError: |
| 480 | # loader will stay None. |
| 481 | pass |
| 482 | try: |
| 483 | location = module.__file__ |
| 484 | except AttributeError: |
| 485 | location = None |
| 486 | if origin is None: |
| 487 | if location is None: |
| 488 | try: |
| 489 | origin = loader._ORIGIN |
| 490 | except AttributeError: |
| 491 | origin = None |
| 492 | else: |
| 493 | origin = location |
| 494 | try: |
| 495 | cached = module.__cached__ |
| 496 | except AttributeError: |
| 497 | cached = None |
| 498 | try: |
| 499 | submodule_search_locations = list(module.__path__) |
| 500 | except AttributeError: |
| 501 | submodule_search_locations = None |
| 502 | |
| 503 | spec = ModuleSpec(name, loader, origin=origin) |
| 504 | spec._set_fileattr = False if location is None else True |
| 505 | spec.cached = cached |
| 506 | spec.submodule_search_locations = submodule_search_locations |
| 507 | return spec |
| 508 | |
| 509 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 510 | def _init_module_attrs(spec, module, *, override=False): |
| 511 | # The passed-in module may be not support attribute assignment, |
| 512 | # in which case we simply don't set the attributes. |
| 513 | # __name__ |
| 514 | if (override or getattr(module, '__name__', None) is None): |
| 515 | try: |
| 516 | module.__name__ = spec.name |
| 517 | except AttributeError: |
| 518 | pass |
| 519 | # __loader__ |
| 520 | if override or getattr(module, '__loader__', None) is None: |
| 521 | loader = spec.loader |
| 522 | if loader is None: |
| 523 | # A backward compatibility hack. |
| 524 | if spec.submodule_search_locations is not None: |
Eric Snow | 183a941 | 2015-05-15 21:54:59 -0600 | [diff] [blame] | 525 | if _bootstrap_external is None: |
| 526 | raise NotImplementedError |
| 527 | _NamespaceLoader = _bootstrap_external._NamespaceLoader |
| 528 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 529 | loader = _NamespaceLoader.__new__(_NamespaceLoader) |
| 530 | loader._path = spec.submodule_search_locations |
| 531 | try: |
| 532 | module.__loader__ = loader |
| 533 | except AttributeError: |
| 534 | pass |
| 535 | # __package__ |
| 536 | if override or getattr(module, '__package__', None) is None: |
| 537 | try: |
| 538 | module.__package__ = spec.parent |
| 539 | except AttributeError: |
| 540 | pass |
| 541 | # __spec__ |
| 542 | try: |
| 543 | module.__spec__ = spec |
| 544 | except AttributeError: |
| 545 | pass |
| 546 | # __path__ |
| 547 | if override or getattr(module, '__path__', None) is None: |
| 548 | if spec.submodule_search_locations is not None: |
| 549 | try: |
| 550 | module.__path__ = spec.submodule_search_locations |
| 551 | except AttributeError: |
| 552 | pass |
| 553 | # __file__/__cached__ |
| 554 | if spec.has_location: |
| 555 | if override or getattr(module, '__file__', None) is None: |
| 556 | try: |
| 557 | module.__file__ = spec.origin |
| 558 | except AttributeError: |
| 559 | pass |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 560 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 561 | if override or getattr(module, '__cached__', None) is None: |
| 562 | if spec.cached is not None: |
| 563 | try: |
| 564 | module.__cached__ = spec.cached |
| 565 | except AttributeError: |
| 566 | pass |
| 567 | return module |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 568 | |
Eric Snow | e4314e0 | 2014-01-07 23:29:19 -0700 | [diff] [blame] | 569 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 570 | def module_from_spec(spec): |
| 571 | """Create a module based on the provided spec.""" |
| 572 | # Typically loaders will not implement create_module(). |
| 573 | module = None |
| 574 | if hasattr(spec.loader, 'create_module'): |
| 575 | # If create_module() returns `None` then it means default |
| 576 | # module creation should be used. |
| 577 | module = spec.loader.create_module(spec) |
Brett Cannon | 02d8454 | 2015-01-09 11:39:21 -0500 | [diff] [blame] | 578 | elif hasattr(spec.loader, 'exec_module'): |
| 579 | _warnings.warn('starting in Python 3.6, loaders defining exec_module() ' |
| 580 | 'must also define create_module()', |
| 581 | DeprecationWarning, stacklevel=2) |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 582 | if module is None: |
| 583 | module = _new_module(spec.name) |
| 584 | _init_module_attrs(spec, module) |
| 585 | return module |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 586 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 587 | |
| 588 | def _module_repr_from_spec(spec): |
| 589 | """Return the repr to use for the module.""" |
| 590 | # We mostly replicate _module_repr() using the spec attributes. |
| 591 | name = '?' if spec.name is None else spec.name |
| 592 | if spec.origin is None: |
| 593 | if spec.loader is None: |
| 594 | return '<module {!r}>'.format(name) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 595 | else: |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 596 | return '<module {!r} ({!r})>'.format(name, spec.loader) |
| 597 | else: |
| 598 | if spec.has_location: |
| 599 | return '<module {!r} from {!r}>'.format(name, spec.origin) |
| 600 | else: |
| 601 | return '<module {!r} ({})>'.format(spec.name, spec.origin) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 602 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 603 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 604 | # Used by importlib.reload() and _load_module_shim(). |
| 605 | def _exec(spec, module): |
| 606 | """Execute the spec in an existing module's namespace.""" |
| 607 | name = spec.name |
| 608 | _imp.acquire_lock() |
| 609 | with _ModuleLockManager(name): |
| 610 | if sys.modules.get(name) is not module: |
| 611 | msg = 'module {!r} not in sys.modules'.format(name) |
| 612 | raise ImportError(msg, name=name) |
| 613 | if spec.loader is None: |
| 614 | if spec.submodule_search_locations is None: |
| 615 | raise ImportError('missing loader', name=spec.name) |
| 616 | # namespace package |
| 617 | _init_module_attrs(spec, module, override=True) |
| 618 | return module |
| 619 | _init_module_attrs(spec, module, override=True) |
| 620 | if not hasattr(spec.loader, 'exec_module'): |
| 621 | # (issue19713) Once BuiltinImporter and ExtensionFileLoader |
| 622 | # have exec_module() implemented, we can add a deprecation |
| 623 | # warning here. |
| 624 | spec.loader.load_module(name) |
| 625 | else: |
| 626 | spec.loader.exec_module(module) |
| 627 | return sys.modules[name] |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 628 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 629 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 630 | def _load_backward_compatible(spec): |
| 631 | # (issue19713) Once BuiltinImporter and ExtensionFileLoader |
| 632 | # have exec_module() implemented, we can add a deprecation |
| 633 | # warning here. |
| 634 | spec.loader.load_module(spec.name) |
| 635 | # The module must be in sys.modules at this point! |
| 636 | module = sys.modules[spec.name] |
| 637 | if getattr(module, '__loader__', None) is None: |
| 638 | try: |
| 639 | module.__loader__ = spec.loader |
| 640 | except AttributeError: |
| 641 | pass |
| 642 | if getattr(module, '__package__', None) is None: |
| 643 | try: |
| 644 | # Since module.__path__ may not line up with |
| 645 | # spec.submodule_search_paths, we can't necessarily rely |
| 646 | # on spec.parent here. |
| 647 | module.__package__ = module.__name__ |
| 648 | if not hasattr(module, '__path__'): |
| 649 | module.__package__ = spec.name.rpartition('.')[0] |
| 650 | except AttributeError: |
| 651 | pass |
| 652 | if getattr(module, '__spec__', None) is None: |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 653 | try: |
| 654 | module.__spec__ = spec |
| 655 | except AttributeError: |
| 656 | pass |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 657 | return module |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 658 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 659 | def _load_unlocked(spec): |
| 660 | # A helper for direct use by the import system. |
| 661 | if spec.loader is not None: |
| 662 | # not a namespace package |
| 663 | if not hasattr(spec.loader, 'exec_module'): |
| 664 | return _load_backward_compatible(spec) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 665 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 666 | module = module_from_spec(spec) |
| 667 | with _installed_safely(module): |
| 668 | if spec.loader is None: |
| 669 | if spec.submodule_search_locations is None: |
| 670 | raise ImportError('missing loader', name=spec.name) |
| 671 | # A namespace package so do nothing. |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 672 | else: |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 673 | spec.loader.exec_module(module) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 674 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 675 | # We don't ensure that the import-related module attributes get |
| 676 | # set in the sys.modules replacement case. Such modules are on |
| 677 | # their own. |
| 678 | return sys.modules[spec.name] |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 679 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 680 | # A method used during testing of _load_unlocked() and by |
| 681 | # _load_module_shim(). |
| 682 | def _load(spec): |
| 683 | """Return a new module object, loaded by the spec's loader. |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 684 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 685 | The module is not added to its parent. |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 686 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 687 | If a module is already in sys.modules, that existing module gets |
| 688 | clobbered. |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 689 | |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 690 | """ |
| 691 | _imp.acquire_lock() |
| 692 | with _ModuleLockManager(spec.name): |
| 693 | return _load_unlocked(spec) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 694 | |
| 695 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 696 | # Loaders ##################################################################### |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 697 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 698 | class BuiltinImporter: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 699 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 700 | """Meta path import for built-in modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 701 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 702 | All methods are either class or static methods to avoid the need to |
| 703 | instantiate the class. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 704 | |
| 705 | """ |
| 706 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 707 | @staticmethod |
| 708 | def module_repr(module): |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 709 | """Return repr for the module. |
| 710 | |
| 711 | The method is deprecated. The import machinery does the job itself. |
| 712 | |
| 713 | """ |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 714 | return '<module {!r} (built-in)>'.format(module.__name__) |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 715 | |
| 716 | @classmethod |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 717 | def find_spec(cls, fullname, path=None, target=None): |
| 718 | if path is not None: |
| 719 | return None |
| 720 | if _imp.is_builtin(fullname): |
| 721 | return spec_from_loader(fullname, cls, origin='built-in') |
| 722 | else: |
| 723 | return None |
| 724 | |
| 725 | @classmethod |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 726 | def find_module(cls, fullname, path=None): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 727 | """Find the built-in module. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 728 | |
| 729 | If 'path' is ever specified then the search is considered a failure. |
| 730 | |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 731 | This method is deprecated. Use find_spec() instead. |
| 732 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 733 | """ |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 734 | spec = cls.find_spec(fullname, path) |
| 735 | return spec.loader if spec is not None else None |
| 736 | |
Brett Cannon | 78246b6 | 2009-01-25 04:56:30 +0000 | [diff] [blame] | 737 | @classmethod |
Nick Coghlan | d5cacbb | 2015-05-23 22:24:10 +1000 | [diff] [blame] | 738 | def create_module(self, spec): |
| 739 | """Create a built-in module""" |
| 740 | if spec.name not in sys.builtin_module_names: |
| 741 | raise ImportError('{!r} is not a built-in module'.format(spec.name), |
| 742 | name=spec.name) |
| 743 | return _call_with_frames_removed(_imp.create_builtin, spec) |
| 744 | |
| 745 | @classmethod |
| 746 | def exec_module(self, module): |
| 747 | """Exec a built-in module""" |
| 748 | _call_with_frames_removed(_imp.exec_dynamic, module) |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 749 | |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 750 | @classmethod |
| 751 | @_requires_builtin |
| 752 | def get_code(cls, fullname): |
| 753 | """Return None as built-in modules do not have code objects.""" |
| 754 | return None |
| 755 | |
| 756 | @classmethod |
| 757 | @_requires_builtin |
| 758 | def get_source(cls, fullname): |
| 759 | """Return None as built-in modules do not have source code.""" |
| 760 | return None |
| 761 | |
| 762 | @classmethod |
| 763 | @_requires_builtin |
| 764 | def is_package(cls, fullname): |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 765 | """Return False as built-in modules are never packages.""" |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 766 | return False |
| 767 | |
Nick Coghlan | d5cacbb | 2015-05-23 22:24:10 +1000 | [diff] [blame] | 768 | load_module = classmethod(_load_module_shim) |
| 769 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 770 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 771 | class FrozenImporter: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 772 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 773 | """Meta path import for frozen modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 774 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 775 | All methods are either class or static methods to avoid the need to |
| 776 | instantiate the class. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 777 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 778 | """ |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 779 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 780 | @staticmethod |
| 781 | def module_repr(m): |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 782 | """Return repr for the module. |
| 783 | |
| 784 | The method is deprecated. The import machinery does the job itself. |
| 785 | |
| 786 | """ |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 787 | return '<module {!r} (frozen)>'.format(m.__name__) |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 788 | |
| 789 | @classmethod |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 790 | def find_spec(cls, fullname, path=None, target=None): |
| 791 | if _imp.is_frozen(fullname): |
| 792 | return spec_from_loader(fullname, cls, origin='frozen') |
| 793 | else: |
| 794 | return None |
| 795 | |
| 796 | @classmethod |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 797 | def find_module(cls, fullname, path=None): |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 798 | """Find a frozen module. |
| 799 | |
| 800 | This method is deprecated. Use find_spec() instead. |
| 801 | |
| 802 | """ |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 803 | return cls if _imp.is_frozen(fullname) else None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 804 | |
Brett Cannon | 02d8454 | 2015-01-09 11:39:21 -0500 | [diff] [blame] | 805 | @classmethod |
| 806 | def create_module(cls, spec): |
| 807 | """Use default semantics for module creation.""" |
| 808 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 809 | @staticmethod |
| 810 | def exec_module(module): |
| 811 | name = module.__spec__.name |
| 812 | if not _imp.is_frozen(name): |
Brett Cannon | 224b261 | 2013-11-22 14:52:36 -0500 | [diff] [blame] | 813 | raise ImportError('{!r} is not a frozen module'.format(name), |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 814 | name=name) |
| 815 | code = _call_with_frames_removed(_imp.get_frozen_object, name) |
| 816 | exec(code, module.__dict__) |
| 817 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 818 | @classmethod |
| 819 | def load_module(cls, fullname): |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 820 | """Load a frozen module. |
| 821 | |
| 822 | This method is deprecated. Use exec_module() instead. |
| 823 | |
| 824 | """ |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 825 | return _load_module_shim(cls, fullname) |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 826 | |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 827 | @classmethod |
| 828 | @_requires_frozen |
| 829 | def get_code(cls, fullname): |
| 830 | """Return the code object for the frozen module.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 831 | return _imp.get_frozen_object(fullname) |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 832 | |
| 833 | @classmethod |
| 834 | @_requires_frozen |
| 835 | def get_source(cls, fullname): |
| 836 | """Return None as frozen modules do not have source code.""" |
| 837 | return None |
| 838 | |
| 839 | @classmethod |
| 840 | @_requires_frozen |
| 841 | def is_package(cls, fullname): |
Philip Jenvey | 688a551 | 2012-08-10 16:21:35 -0700 | [diff] [blame] | 842 | """Return True if the frozen module is a package.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 843 | return _imp.is_frozen_package(fullname) |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 844 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 845 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 846 | # Import itself ############################################################### |
| 847 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 848 | class _ImportLockContext: |
| 849 | |
| 850 | """Context manager for the import lock.""" |
| 851 | |
| 852 | def __enter__(self): |
| 853 | """Acquire the import lock.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 854 | _imp.acquire_lock() |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 855 | |
| 856 | def __exit__(self, exc_type, exc_value, exc_traceback): |
| 857 | """Release the import lock regardless of any raised exceptions.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 858 | _imp.release_lock() |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 859 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 860 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 861 | def _resolve_name(name, package, level): |
| 862 | """Resolve a relative module name to an absolute one.""" |
Philip Jenvey | 4b42ff6 | 2012-02-24 21:48:17 -0800 | [diff] [blame] | 863 | bits = package.rsplit('.', level - 1) |
Brett Cannon | 625cd23 | 2012-02-24 11:20:54 -0500 | [diff] [blame] | 864 | if len(bits) < level: |
| 865 | raise ValueError('attempted relative import beyond top-level package') |
| 866 | base = bits[0] |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 867 | return '{}.{}'.format(base, name) if name else base |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 868 | |
| 869 | |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 870 | def _find_spec_legacy(finder, name, path): |
| 871 | # This would be a good place for a DeprecationWarning if |
| 872 | # we ended up going that route. |
| 873 | loader = finder.find_module(name, path) |
| 874 | if loader is None: |
| 875 | return None |
| 876 | return spec_from_loader(name, loader) |
| 877 | |
| 878 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 879 | def _find_spec(name, path, target=None): |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 880 | """Find a module's loader.""" |
Brett Cannon | 5e8b04e | 2014-10-10 10:54:28 -0400 | [diff] [blame] | 881 | if sys.meta_path is not None and not sys.meta_path: |
Brett Cannon | ce418b4 | 2012-04-27 14:01:58 -0400 | [diff] [blame] | 882 | _warnings.warn('sys.meta_path is empty', ImportWarning) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 883 | # We check sys.modules here for the reload case. While a passed-in |
| 884 | # target will usually indicate a reload there is no guarantee, whereas |
| 885 | # sys.modules provides one. |
Eric Snow | cdf6012 | 2013-10-31 22:22:15 -0600 | [diff] [blame] | 886 | is_reload = name in sys.modules |
Brett Cannon | ce418b4 | 2012-04-27 14:01:58 -0400 | [diff] [blame] | 887 | for finder in sys.meta_path: |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 888 | with _ImportLockContext(): |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 889 | try: |
| 890 | find_spec = finder.find_spec |
| 891 | except AttributeError: |
Eric Snow | 1500d49 | 2014-01-06 20:49:04 -0700 | [diff] [blame] | 892 | spec = _find_spec_legacy(finder, name, path) |
| 893 | if spec is None: |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 894 | continue |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 895 | else: |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 896 | spec = find_spec(name, path, target) |
| 897 | if spec is not None: |
| 898 | # The parent import may have already imported this module. |
| 899 | if not is_reload and name in sys.modules: |
| 900 | module = sys.modules[name] |
Eric Snow | cdf6012 | 2013-10-31 22:22:15 -0600 | [diff] [blame] | 901 | try: |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 902 | __spec__ = module.__spec__ |
Eric Snow | cdf6012 | 2013-10-31 22:22:15 -0600 | [diff] [blame] | 903 | except AttributeError: |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 904 | # We use the found spec since that is the one that |
| 905 | # we would have used if the parent module hadn't |
| 906 | # beaten us to the punch. |
| 907 | return spec |
| 908 | else: |
| 909 | if __spec__ is None: |
| 910 | return spec |
| 911 | else: |
| 912 | return __spec__ |
| 913 | else: |
| 914 | return spec |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 915 | else: |
| 916 | return None |
| 917 | |
| 918 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 919 | def _sanity_check(name, package, level): |
| 920 | """Verify arguments are "sane".""" |
Brett Cannon | 068915c | 2012-02-23 18:18:48 -0500 | [diff] [blame] | 921 | if not isinstance(name, str): |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 922 | raise TypeError('module name must be str, not {}'.format(type(name))) |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 923 | if level < 0: |
| 924 | raise ValueError('level must be >= 0') |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 925 | if package: |
Brett Cannon | 068915c | 2012-02-23 18:18:48 -0500 | [diff] [blame] | 926 | if not isinstance(package, str): |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 927 | raise TypeError('__package__ not set to a string') |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 928 | elif package not in sys.modules: |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 929 | msg = ('Parent module {!r} not loaded, cannot perform relative ' |
| 930 | 'import') |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 931 | raise SystemError(msg.format(package)) |
| 932 | if not name and level == 0: |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 933 | raise ValueError('Empty module name') |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 934 | |
| 935 | |
Brett Cannon | 0075110 | 2013-07-06 14:48:18 -0400 | [diff] [blame] | 936 | _ERR_MSG_PREFIX = 'No module named ' |
| 937 | _ERR_MSG = _ERR_MSG_PREFIX + '{!r}' |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 938 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 939 | def _find_and_load_unlocked(name, import_): |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 940 | path = None |
| 941 | parent = name.rpartition('.')[0] |
| 942 | if parent: |
| 943 | if parent not in sys.modules: |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 944 | _call_with_frames_removed(import_, parent) |
Brett Cannon | 927d874 | 2012-04-02 20:33:56 -0400 | [diff] [blame] | 945 | # Crazy side-effects! |
| 946 | if name in sys.modules: |
| 947 | return sys.modules[name] |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 948 | parent_module = sys.modules[parent] |
| 949 | try: |
| 950 | path = parent_module.__path__ |
| 951 | except AttributeError: |
Brett Cannon | 224b261 | 2013-11-22 14:52:36 -0500 | [diff] [blame] | 952 | msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent) |
Serhiy Storchaka | c446405 | 2014-11-21 20:33:57 +0200 | [diff] [blame] | 953 | raise ImportError(msg, name=name) from None |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 954 | spec = _find_spec(name, path) |
| 955 | if spec is None: |
Brett Cannon | 0075110 | 2013-07-06 14:48:18 -0400 | [diff] [blame] | 956 | raise ImportError(_ERR_MSG.format(name), name=name) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 957 | else: |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 958 | module = _load_unlocked(spec) |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 959 | if parent: |
| 960 | # Set the module as an attribute on its parent. |
| 961 | parent_module = sys.modules[parent] |
| 962 | setattr(parent_module, name.rpartition('.')[2], module) |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 963 | return module |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 964 | |
| 965 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 966 | def _find_and_load(name, import_): |
| 967 | """Find and load the module, and release the import lock.""" |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 968 | with _ModuleLockManager(name): |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 969 | return _find_and_load_unlocked(name, import_) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 970 | |
| 971 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 972 | def _gcd_import(name, package=None, level=0): |
| 973 | """Import and return the module based on its name, the package the call is |
| 974 | being made from, and the level adjustment. |
| 975 | |
| 976 | This function represents the greatest common denominator of functionality |
Eric V. Smith | 4169826 | 2011-03-14 10:56:33 -0400 | [diff] [blame] | 977 | between import_module and __import__. This includes setting __package__ if |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 978 | the loader did not. |
| 979 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 980 | """ |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 981 | _sanity_check(name, package, level) |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 982 | if level > 0: |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 983 | name = _resolve_name(name, package, level) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 984 | _imp.acquire_lock() |
| 985 | if name not in sys.modules: |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 986 | return _find_and_load(name, _gcd_import) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 987 | module = sys.modules[name] |
| 988 | if module is None: |
| 989 | _imp.release_lock() |
Brett Cannon | f0cb692 | 2013-07-12 11:04:23 -0400 | [diff] [blame] | 990 | message = ('import of {} halted; ' |
| 991 | 'None in sys.modules'.format(name)) |
Brett Cannon | 82da888 | 2013-07-04 17:48:16 -0400 | [diff] [blame] | 992 | raise ImportError(message, name=name) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 993 | _lock_unlock_module(name) |
| 994 | return module |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 995 | |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 996 | def _handle_fromlist(module, fromlist, import_): |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 997 | """Figure out what __import__ should return. |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 998 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 999 | The import_ parameter is a callable which takes the name of module to |
| 1000 | import. It is required to decouple the function from assuming importlib's |
| 1001 | import implementation is desired. |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 1002 | |
| 1003 | """ |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 1004 | # The hell that is fromlist ... |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1005 | # If a package was imported, try to import stuff from fromlist. |
| 1006 | if hasattr(module, '__path__'): |
Brett Cannon | 461c813 | 2012-07-10 10:05:00 -0400 | [diff] [blame] | 1007 | if '*' in fromlist: |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1008 | fromlist = list(fromlist) |
| 1009 | fromlist.remove('*') |
Brett Cannon | 461c813 | 2012-07-10 10:05:00 -0400 | [diff] [blame] | 1010 | if hasattr(module, '__all__'): |
| 1011 | fromlist.extend(module.__all__) |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 1012 | for x in fromlist: |
| 1013 | if not hasattr(module, x): |
Brett Cannon | a6ce4fd | 2012-10-10 19:03:46 -0400 | [diff] [blame] | 1014 | from_name = '{}.{}'.format(module.__name__, x) |
Brett Cannon | 7385adc | 2012-08-17 13:21:16 -0400 | [diff] [blame] | 1015 | try: |
Brett Cannon | a6ce4fd | 2012-10-10 19:03:46 -0400 | [diff] [blame] | 1016 | _call_with_frames_removed(import_, from_name) |
Brett Cannon | 679ecb5 | 2013-07-04 17:51:50 -0400 | [diff] [blame] | 1017 | except ImportError as exc: |
Brett Cannon | 7385adc | 2012-08-17 13:21:16 -0400 | [diff] [blame] | 1018 | # Backwards-compatibility dictates we ignore failed |
Brett Cannon | 12c6bda | 2012-08-24 18:25:59 -0400 | [diff] [blame] | 1019 | # imports triggered by fromlist for modules that don't |
| 1020 | # exist. |
Brett Cannon | 0075110 | 2013-07-06 14:48:18 -0400 | [diff] [blame] | 1021 | if str(exc).startswith(_ERR_MSG_PREFIX): |
Brett Cannon | 679ecb5 | 2013-07-04 17:51:50 -0400 | [diff] [blame] | 1022 | if exc.name == from_name: |
| 1023 | continue |
Brett Cannon | a6ce4fd | 2012-10-10 19:03:46 -0400 | [diff] [blame] | 1024 | raise |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1025 | return module |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1026 | |
| 1027 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1028 | def _calc___package__(globals): |
| 1029 | """Calculate what __package__ should be. |
| 1030 | |
| 1031 | __package__ is not guaranteed to be defined or could be set to None |
| 1032 | to represent that its proper value is unknown. |
| 1033 | |
| 1034 | """ |
| 1035 | package = globals.get('__package__') |
| 1036 | if package is None: |
| 1037 | package = globals['__name__'] |
| 1038 | if '__path__' not in globals: |
| 1039 | package = package.rpartition('.')[0] |
| 1040 | return package |
| 1041 | |
| 1042 | |
Brett Cannon | cb4996a | 2012-08-06 16:34:44 -0400 | [diff] [blame] | 1043 | def __import__(name, globals=None, locals=None, fromlist=(), level=0): |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1044 | """Import a module. |
| 1045 | |
| 1046 | The 'globals' argument is used to infer where the import is occuring from |
| 1047 | to handle relative imports. The 'locals' argument is ignored. The |
| 1048 | 'fromlist' argument specifies what should exist as attributes on the module |
| 1049 | being imported (e.g. ``from module import <fromlist>``). The 'level' |
| 1050 | argument represents the package location to import from in a relative |
| 1051 | import (e.g. ``from ..pkg import mod`` would have a 'level' of 2). |
| 1052 | |
| 1053 | """ |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1054 | if level == 0: |
| 1055 | module = _gcd_import(name) |
| 1056 | else: |
Brett Cannon | cb4996a | 2012-08-06 16:34:44 -0400 | [diff] [blame] | 1057 | globals_ = globals if globals is not None else {} |
| 1058 | package = _calc___package__(globals_) |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1059 | module = _gcd_import(name, package, level) |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1060 | if not fromlist: |
| 1061 | # Return up to the first dot in 'name'. This is complicated by the fact |
| 1062 | # that 'name' may be relative. |
| 1063 | if level == 0: |
Antoine Pitrou | 6efa50a | 2012-05-07 21:41:59 +0200 | [diff] [blame] | 1064 | return _gcd_import(name.partition('.')[0]) |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1065 | elif not name: |
| 1066 | return module |
| 1067 | else: |
Brett Cannon | 8ed677d | 2012-09-28 16:41:39 -0400 | [diff] [blame] | 1068 | # Figure out where to slice the module's name up to the first dot |
| 1069 | # in 'name'. |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1070 | cut_off = len(name) - len(name.partition('.')[0]) |
Brett Cannon | 8ed677d | 2012-09-28 16:41:39 -0400 | [diff] [blame] | 1071 | # Slice end needs to be positive to alleviate need to special-case |
| 1072 | # when ``'.' not in name``. |
Brett Cannon | 49f8d8b | 2012-04-14 21:50:00 -0400 | [diff] [blame] | 1073 | return sys.modules[module.__name__[:len(module.__name__)-cut_off]] |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1074 | else: |
| 1075 | return _handle_fromlist(module, fromlist, _gcd_import) |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1076 | |
| 1077 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1078 | def _builtin_from_name(name): |
| 1079 | spec = BuiltinImporter.find_spec(name) |
Brett Cannon | fddc311 | 2013-11-22 11:58:17 -0500 | [diff] [blame] | 1080 | if spec is None: |
| 1081 | raise ImportError('no built-in module named ' + name) |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 1082 | return _load_unlocked(spec) |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1083 | |
Brett Cannon | 24117a7 | 2012-04-20 18:04:03 -0400 | [diff] [blame] | 1084 | |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1085 | def _setup(sys_module, _imp_module): |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1086 | """Setup importlib by importing needed built-in modules and injecting them |
| 1087 | into the global namespace. |
| 1088 | |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1089 | As sys is needed for sys.modules access and _imp is needed to load built-in |
Brett Cannon | 0568d6f | 2012-02-14 18:38:11 -0500 | [diff] [blame] | 1090 | modules, those two modules must be explicitly passed in. |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1091 | |
| 1092 | """ |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 1093 | global _imp, sys |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1094 | _imp = _imp_module |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1095 | sys = sys_module |
| 1096 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1097 | # Set up the spec for existing builtin/frozen modules. |
Brett Cannon | 0ecd30b | 2013-02-01 14:04:12 -0500 | [diff] [blame] | 1098 | module_type = type(sys) |
Brett Cannon | da9cf0e | 2013-02-01 15:31:49 -0500 | [diff] [blame] | 1099 | for name, module in sys.modules.items(): |
Brett Cannon | 0ecd30b | 2013-02-01 14:04:12 -0500 | [diff] [blame] | 1100 | if isinstance(module, module_type): |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1101 | if name in sys.builtin_module_names: |
| 1102 | loader = BuiltinImporter |
| 1103 | elif _imp.is_frozen(name): |
| 1104 | loader = FrozenImporter |
| 1105 | else: |
| 1106 | continue |
| 1107 | spec = _spec_from_module(module, loader) |
Brett Cannon | 2a17bde | 2014-05-30 14:55:29 -0400 | [diff] [blame] | 1108 | _init_module_attrs(spec, module) |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1109 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1110 | # Directly load built-in modules needed during bootstrap. |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1111 | self_module = sys.modules[__name__] |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 1112 | for builtin_name in ('_warnings',): |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1113 | if builtin_name not in sys.modules: |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1114 | builtin_module = _builtin_from_name(builtin_name) |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1115 | else: |
| 1116 | builtin_module = sys.modules[builtin_name] |
| 1117 | setattr(self_module, builtin_name, builtin_module) |
| 1118 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1119 | # Directly load the _thread module (needed during bootstrap). |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1120 | try: |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1121 | thread_module = _builtin_from_name('_thread') |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1122 | except ImportError: |
| 1123 | # Python was built without threads |
| 1124 | thread_module = None |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1125 | setattr(self_module, '_thread', thread_module) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1126 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 1127 | # Directly load the _weakref module (needed during bootstrap). |
| 1128 | weakref_module = _builtin_from_name('_weakref') |
| 1129 | setattr(self_module, '_weakref', weakref_module) |
| 1130 | |
Brett Cannon | 0568d6f | 2012-02-14 18:38:11 -0500 | [diff] [blame] | 1131 | |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1132 | def _install(sys_module, _imp_module): |
Brett Cannon | feccc09 | 2012-05-04 16:47:54 -0400 | [diff] [blame] | 1133 | """Install importlib as the implementation of import.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1134 | _setup(sys_module, _imp_module) |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 1135 | |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 1136 | sys.meta_path.append(BuiltinImporter) |
| 1137 | sys.meta_path.append(FrozenImporter) |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 1138 | |
Eric Snow | 183a941 | 2015-05-15 21:54:59 -0600 | [diff] [blame] | 1139 | global _bootstrap_external |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 1140 | import _frozen_importlib_external |
Eric Snow | 183a941 | 2015-05-15 21:54:59 -0600 | [diff] [blame] | 1141 | _bootstrap_external = _frozen_importlib_external |
Eric Snow | 32439d6 | 2015-05-02 19:15:18 -0600 | [diff] [blame] | 1142 | _frozen_importlib_external._install(sys.modules[__name__]) |