blob: 931754e1544fa4e5427625bc1bef8a15032c5862 [file] [log] [blame]
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001"""Core implementation of import.
2
3This module is NOT meant to be directly imported! It has been designed such
4that it can be bootstrapped into Python as the implementation of import. As
5such it requires the injection of specific modules and attributes in order to
6work. One should use importlib as the public-facing version of this module.
7
8"""
Marc-Andre Lemburg7541c8e2012-04-25 10:54:48 +02009#
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 Cannon2a17bde2014-05-30 14:55:29 -040012# updated. Not doing so will result in the Makefile to fail for
Marc-Andre Lemburg7541c8e2012-04-25 10:54:48 +020013# all others who don't have a ./python around to freeze the module
14# in the early stages of compilation.
15#
Brett Cannon23cbd8a2009-01-18 00:24:28 +000016
Brett Cannoned672d62012-04-20 21:19:53 -040017# See importlib._setup() for what is injected into the global namespace.
18
Brett Cannon23cbd8a2009-01-18 00:24:28 +000019# 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 Cannonce43ddf2009-03-12 22:28:55 +000023# Bootstrap-related code ######################################################
24
Eric Snow183a9412015-05-15 21:54:59 -060025_bootstrap_external = None
26
Brett Cannon3eeaa0a2009-03-12 22:07:17 +000027def _wrap(new, old):
Florent Xicluna79d79a02012-07-07 13:16:44 +020028 """Simple substitute for functools.update_wrapper."""
Meador Inge96ff0842011-12-14 22:53:13 -060029 for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
Brett Cannon8490fab2012-02-08 18:44:14 -050030 if hasattr(old, replace):
31 setattr(new, replace, getattr(old, replace))
Brett Cannon51d8bfc2009-02-07 02:13:28 +000032 new.__dict__.update(old.__dict__)
33
34
Eric Snowb523f842013-11-22 09:05:39 -070035def _new_module(name):
36 return type(sys)(name)
37
38
Brett Cannond2476c62013-11-29 11:00:11 -050039class _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 Pitrouea3eb882012-05-17 18:55:59 +020056# 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
64class _DeadlockError(RuntimeError):
65 pass
66
67
68class _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 Cannonf0cb6922013-07-12 11:04:23 -0400110 raise _DeadlockError('deadlock detected by %r' % self)
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200111 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 Cannonf0cb6922013-07-12 11:04:23 -0400123 raise RuntimeError('cannot release un-acquired lock')
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200124 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 Cannonf0cb6922013-07-12 11:04:23 -0400133 return '_ModuleLock({!r}) at {}'.format(self.name, id(self))
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200134
135
136class _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 Cannonf0cb6922013-07-12 11:04:23 -0400150 raise RuntimeError('cannot release un-acquired lock')
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200151 self.count -= 1
152
153 def __repr__(self):
Brett Cannonf0cb6922013-07-12 11:04:23 -0400154 return '_DummyModuleLock({!r}) at {}'.format(self.name, id(self))
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200155
156
Eric Snowb523f842013-11-22 09:05:39 -0700157class _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 Pitrouea3eb882012-05-17 18:55:59 +0200174# The following two functions are for consumption by Python/import.c.
175
176def _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 Pitrou4f0338c2012-08-28 00:24:52 +0200181 try:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200182 lock = _module_locks[name]()
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200183 except KeyError:
184 pass
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200185 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
195def _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 Coghlan42c07662012-07-31 21:14:18 +1000213# Frame stripping magic ###############################################
Nick Coghlan42c07662012-07-31 21:14:18 +1000214def _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 Cannonf8ffec02013-04-01 13:10:51 -0400225def _verbose_message(message, *args, verbosity=1):
Brett Cannonfd074152012-04-14 14:10:13 -0400226 """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
Brett Cannonf8ffec02013-04-01 13:10:51 -0400227 if sys.flags.verbose >= verbosity:
Philip Jenveyf8f31902012-04-15 12:21:32 -0700228 if not message.startswith(('#', 'import ')):
Brett Cannonfd074152012-04-14 14:10:13 -0400229 message = '# ' + message
230 print(message.format(*args), file=sys.stderr)
231
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100232
Brett Cannona113ac52009-03-15 01:41:33 +0000233def _requires_builtin(fxn):
234 """Decorator to verify the named module is built-in."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500235 def _requires_builtin_wrapper(self, fullname):
Brett Cannona113ac52009-03-15 01:41:33 +0000236 if fullname not in sys.builtin_module_names:
Brett Cannon224b2612013-11-22 14:52:36 -0500237 raise ImportError('{!r} is not a built-in module'.format(fullname),
Brett Cannonbbb66802012-04-12 21:09:01 -0400238 name=fullname)
Brett Cannona113ac52009-03-15 01:41:33 +0000239 return fxn(self, fullname)
Brett Cannonf522aea2012-01-16 11:46:22 -0500240 _wrap(_requires_builtin_wrapper, fxn)
241 return _requires_builtin_wrapper
Brett Cannona113ac52009-03-15 01:41:33 +0000242
243
Brett Cannon8d110132009-03-15 02:20:16 +0000244def _requires_frozen(fxn):
245 """Decorator to verify the named module is frozen."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500246 def _requires_frozen_wrapper(self, fullname):
Brett Cannon6f44d662012-04-15 16:08:47 -0400247 if not _imp.is_frozen(fullname):
Brett Cannon224b2612013-11-22 14:52:36 -0500248 raise ImportError('{!r} is not a frozen module'.format(fullname),
Brett Cannonbbb66802012-04-12 21:09:01 -0400249 name=fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000250 return fxn(self, fullname)
Brett Cannonf522aea2012-01-16 11:46:22 -0500251 _wrap(_requires_frozen_wrapper, fxn)
252 return _requires_frozen_wrapper
Brett Cannon8d110132009-03-15 02:20:16 +0000253
254
Brett Cannon42535f02014-05-30 16:28:00 -0400255# Typically used by loader classes as a method replacement.
256def _load_module_shim(self, fullname):
Eric Snow1500d492014-01-06 20:49:04 -0700257 """Load the specified module into sys.modules and return it.
258
259 This method is deprecated. Use loader.exec_module instead.
260
261 """
Brett Cannon42535f02014-05-30 16:28:00 -0400262 spec = spec_from_loader(fullname, self)
Eric Snowb523f842013-11-22 09:05:39 -0700263 if fullname in sys.modules:
264 module = sys.modules[fullname]
Brett Cannon2a17bde2014-05-30 14:55:29 -0400265 _exec(spec, module)
Eric Snowb523f842013-11-22 09:05:39 -0700266 return sys.modules[fullname]
267 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400268 return _load(spec)
Eric Snowb523f842013-11-22 09:05:39 -0700269
Eric Snowb523f842013-11-22 09:05:39 -0700270# Module specifications #######################################################
271
272def _module_repr(module):
273 # The implementation of ModuleType__repr__().
274 loader = getattr(module, '__loader__', None)
275 if hasattr(loader, 'module_repr'):
Eric Snow1500d492014-01-06 20:49:04 -0700276 # As soon as BuiltinImporter, FrozenImporter, and NamespaceLoader
277 # drop their implementations for module_repr. we can add a
278 # deprecation warning here.
Eric Snowb523f842013-11-22 09:05:39 -0700279 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 Cannon2a17bde2014-05-30 14:55:29 -0400289 return _module_repr_from_spec(spec)
Eric Snowb523f842013-11-22 09:05:39 -0700290
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
308class _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
335class 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 Snow183a9412015-05-15 21:54:59 -0600410 if _bootstrap_external is None:
411 raise NotImplementedError
Eric Snow32439d62015-05-02 19:15:18 -0600412 self._cached = _bootstrap_external._get_cached(self.origin)
Eric Snowb523f842013-11-22 09:05:39 -0700413 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 Snowb282b3d2013-12-10 22:16:41 -0700431 @has_location.setter
432 def has_location(self, value):
433 self._set_fileattr = bool(value)
434
Eric Snowb523f842013-11-22 09:05:39 -0700435
436def spec_from_loader(name, loader, *, origin=None, is_package=None):
437 """Return a module spec based on various loader methods."""
Eric Snowb523f842013-11-22 09:05:39 -0700438 if hasattr(loader, 'get_filename'):
Eric Snow183a9412015-05-15 21:54:59 -0600439 if _bootstrap_external is None:
440 raise NotImplementedError
441 spec_from_file_location = _bootstrap_external.spec_from_file_location
442
Eric Snowb523f842013-11-22 09:05:39 -0700443 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 Snowb523f842013-11-22 09:05:39 -0700465def _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 Cannon2a17bde2014-05-30 14:55:29 -0400510def _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 Snow183a9412015-05-15 21:54:59 -0600525 if _bootstrap_external is None:
526 raise NotImplementedError
527 _NamespaceLoader = _bootstrap_external._NamespaceLoader
528
Brett Cannon2a17bde2014-05-30 14:55:29 -0400529 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 Snowb523f842013-11-22 09:05:39 -0700560
Brett Cannon2a17bde2014-05-30 14:55:29 -0400561 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 Snowb523f842013-11-22 09:05:39 -0700568
Eric Snowe4314e02014-01-07 23:29:19 -0700569
Brett Cannon2a17bde2014-05-30 14:55:29 -0400570def 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 Cannon02d84542015-01-09 11:39:21 -0500578 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 Cannon2a17bde2014-05-30 14:55:29 -0400582 if module is None:
583 module = _new_module(spec.name)
584 _init_module_attrs(spec, module)
585 return module
Eric Snowb523f842013-11-22 09:05:39 -0700586
Brett Cannon2a17bde2014-05-30 14:55:29 -0400587
588def _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 Snowb523f842013-11-22 09:05:39 -0700595 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400596 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 Snowb523f842013-11-22 09:05:39 -0700602
Eric Snowb523f842013-11-22 09:05:39 -0700603
Brett Cannon2a17bde2014-05-30 14:55:29 -0400604# Used by importlib.reload() and _load_module_shim().
605def _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 Snowb523f842013-11-22 09:05:39 -0700628
Eric Snowb523f842013-11-22 09:05:39 -0700629
Brett Cannon2a17bde2014-05-30 14:55:29 -0400630def _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 Snowb523f842013-11-22 09:05:39 -0700653 try:
654 module.__spec__ = spec
655 except AttributeError:
656 pass
Brett Cannon2a17bde2014-05-30 14:55:29 -0400657 return module
Eric Snowb523f842013-11-22 09:05:39 -0700658
Brett Cannon2a17bde2014-05-30 14:55:29 -0400659def _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 Snowb523f842013-11-22 09:05:39 -0700665
Brett Cannon2a17bde2014-05-30 14:55:29 -0400666 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 Snowb523f842013-11-22 09:05:39 -0700672 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400673 spec.loader.exec_module(module)
Eric Snowb523f842013-11-22 09:05:39 -0700674
Brett Cannon2a17bde2014-05-30 14:55:29 -0400675 # 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 Snowb523f842013-11-22 09:05:39 -0700679
Brett Cannon2a17bde2014-05-30 14:55:29 -0400680# A method used during testing of _load_unlocked() and by
681# _load_module_shim().
682def _load(spec):
683 """Return a new module object, loaded by the spec's loader.
Eric Snowb523f842013-11-22 09:05:39 -0700684
Brett Cannon2a17bde2014-05-30 14:55:29 -0400685 The module is not added to its parent.
Eric Snowb523f842013-11-22 09:05:39 -0700686
Brett Cannon2a17bde2014-05-30 14:55:29 -0400687 If a module is already in sys.modules, that existing module gets
688 clobbered.
Eric Snowb523f842013-11-22 09:05:39 -0700689
Brett Cannon2a17bde2014-05-30 14:55:29 -0400690 """
691 _imp.acquire_lock()
692 with _ModuleLockManager(spec.name):
693 return _load_unlocked(spec)
Eric Snowb523f842013-11-22 09:05:39 -0700694
695
Brett Cannone9103d22009-03-12 22:37:06 +0000696# Loaders #####################################################################
Brett Cannonce43ddf2009-03-12 22:28:55 +0000697
Brett Cannon5abdc932009-01-22 22:43:07 +0000698class BuiltinImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000699
Brett Cannon7aa21f72009-03-15 00:53:05 +0000700 """Meta path import for built-in modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000701
Brett Cannon7aa21f72009-03-15 00:53:05 +0000702 All methods are either class or static methods to avoid the need to
703 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000704
705 """
706
Eric Snowb523f842013-11-22 09:05:39 -0700707 @staticmethod
708 def module_repr(module):
Eric Snow1500d492014-01-06 20:49:04 -0700709 """Return repr for the module.
710
711 The method is deprecated. The import machinery does the job itself.
712
713 """
Brett Cannonf0cb6922013-07-12 11:04:23 -0400714 return '<module {!r} (built-in)>'.format(module.__name__)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400715
716 @classmethod
Eric Snowb523f842013-11-22 09:05:39 -0700717 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 Cannon5abdc932009-01-22 22:43:07 +0000726 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000727 """Find the built-in module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000728
729 If 'path' is ever specified then the search is considered a failure.
730
Eric Snow1500d492014-01-06 20:49:04 -0700731 This method is deprecated. Use find_spec() instead.
732
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000733 """
Eric Snowb523f842013-11-22 09:05:39 -0700734 spec = cls.find_spec(fullname, path)
735 return spec.loader if spec is not None else None
736
Brett Cannon78246b62009-01-25 04:56:30 +0000737 @classmethod
Nick Coghland5cacbb2015-05-23 22:24:10 +1000738 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 Cannon23cbd8a2009-01-18 00:24:28 +0000749
Brett Cannona113ac52009-03-15 01:41:33 +0000750 @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 Xicluna79d79a02012-07-07 13:16:44 +0200765 """Return False as built-in modules are never packages."""
Brett Cannona113ac52009-03-15 01:41:33 +0000766 return False
767
Nick Coghland5cacbb2015-05-23 22:24:10 +1000768 load_module = classmethod(_load_module_shim)
769
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000770
Brett Cannon5abdc932009-01-22 22:43:07 +0000771class FrozenImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000772
Brett Cannon7aa21f72009-03-15 00:53:05 +0000773 """Meta path import for frozen modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000774
Brett Cannon7aa21f72009-03-15 00:53:05 +0000775 All methods are either class or static methods to avoid the need to
776 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000777
Brett Cannon5abdc932009-01-22 22:43:07 +0000778 """
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000779
Eric Snowb523f842013-11-22 09:05:39 -0700780 @staticmethod
781 def module_repr(m):
Eric Snow1500d492014-01-06 20:49:04 -0700782 """Return repr for the module.
783
784 The method is deprecated. The import machinery does the job itself.
785
786 """
Brett Cannonf0cb6922013-07-12 11:04:23 -0400787 return '<module {!r} (frozen)>'.format(m.__name__)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400788
789 @classmethod
Eric Snowb523f842013-11-22 09:05:39 -0700790 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 Cannon5abdc932009-01-22 22:43:07 +0000797 def find_module(cls, fullname, path=None):
Eric Snow1500d492014-01-06 20:49:04 -0700798 """Find a frozen module.
799
800 This method is deprecated. Use find_spec() instead.
801
802 """
Brett Cannon6f44d662012-04-15 16:08:47 -0400803 return cls if _imp.is_frozen(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000804
Brett Cannon02d84542015-01-09 11:39:21 -0500805 @classmethod
806 def create_module(cls, spec):
807 """Use default semantics for module creation."""
808
Eric Snowb523f842013-11-22 09:05:39 -0700809 @staticmethod
810 def exec_module(module):
811 name = module.__spec__.name
812 if not _imp.is_frozen(name):
Brett Cannon224b2612013-11-22 14:52:36 -0500813 raise ImportError('{!r} is not a frozen module'.format(name),
Eric Snowb523f842013-11-22 09:05:39 -0700814 name=name)
815 code = _call_with_frames_removed(_imp.get_frozen_object, name)
816 exec(code, module.__dict__)
817
Brett Cannon5abdc932009-01-22 22:43:07 +0000818 @classmethod
819 def load_module(cls, fullname):
Eric Snow1500d492014-01-06 20:49:04 -0700820 """Load a frozen module.
821
822 This method is deprecated. Use exec_module() instead.
823
824 """
Eric Snowb523f842013-11-22 09:05:39 -0700825 return _load_module_shim(cls, fullname)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000826
Brett Cannon8d110132009-03-15 02:20:16 +0000827 @classmethod
828 @_requires_frozen
829 def get_code(cls, fullname):
830 """Return the code object for the frozen module."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400831 return _imp.get_frozen_object(fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000832
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 Jenvey688a5512012-08-10 16:21:35 -0700842 """Return True if the frozen module is a package."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400843 return _imp.is_frozen_package(fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000844
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000845
Brett Cannonce43ddf2009-03-12 22:28:55 +0000846# Import itself ###############################################################
847
Brett Cannone9103d22009-03-12 22:37:06 +0000848class _ImportLockContext:
849
850 """Context manager for the import lock."""
851
852 def __enter__(self):
853 """Acquire the import lock."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400854 _imp.acquire_lock()
Brett Cannone9103d22009-03-12 22:37:06 +0000855
856 def __exit__(self, exc_type, exc_value, exc_traceback):
857 """Release the import lock regardless of any raised exceptions."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400858 _imp.release_lock()
Brett Cannone9103d22009-03-12 22:37:06 +0000859
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000860
Brett Cannon7fab6762012-02-16 13:43:41 -0500861def _resolve_name(name, package, level):
862 """Resolve a relative module name to an absolute one."""
Philip Jenvey4b42ff62012-02-24 21:48:17 -0800863 bits = package.rsplit('.', level - 1)
Brett Cannon625cd232012-02-24 11:20:54 -0500864 if len(bits) < level:
865 raise ValueError('attempted relative import beyond top-level package')
866 base = bits[0]
Florent Xicluna79d79a02012-07-07 13:16:44 +0200867 return '{}.{}'.format(base, name) if name else base
Brett Cannon7fab6762012-02-16 13:43:41 -0500868
869
Eric Snow1500d492014-01-06 20:49:04 -0700870def _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 Snowb523f842013-11-22 09:05:39 -0700879def _find_spec(name, path, target=None):
Brett Cannon7fab6762012-02-16 13:43:41 -0500880 """Find a module's loader."""
Brett Cannon5e8b04e2014-10-10 10:54:28 -0400881 if sys.meta_path is not None and not sys.meta_path:
Brett Cannonce418b42012-04-27 14:01:58 -0400882 _warnings.warn('sys.meta_path is empty', ImportWarning)
Eric Snowb523f842013-11-22 09:05:39 -0700883 # 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 Snowcdf60122013-10-31 22:22:15 -0600886 is_reload = name in sys.modules
Brett Cannonce418b42012-04-27 14:01:58 -0400887 for finder in sys.meta_path:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200888 with _ImportLockContext():
Eric Snowb523f842013-11-22 09:05:39 -0700889 try:
890 find_spec = finder.find_spec
891 except AttributeError:
Eric Snow1500d492014-01-06 20:49:04 -0700892 spec = _find_spec_legacy(finder, name, path)
893 if spec is None:
Eric Snowb523f842013-11-22 09:05:39 -0700894 continue
Brett Cannon7fab6762012-02-16 13:43:41 -0500895 else:
Eric Snowb523f842013-11-22 09:05:39 -0700896 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 Snowcdf60122013-10-31 22:22:15 -0600901 try:
Eric Snowb523f842013-11-22 09:05:39 -0700902 __spec__ = module.__spec__
Eric Snowcdf60122013-10-31 22:22:15 -0600903 except AttributeError:
Eric Snowb523f842013-11-22 09:05:39 -0700904 # 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 Cannon7fab6762012-02-16 13:43:41 -0500915 else:
916 return None
917
918
Brett Cannon7fab6762012-02-16 13:43:41 -0500919def _sanity_check(name, package, level):
920 """Verify arguments are "sane"."""
Brett Cannon068915c2012-02-23 18:18:48 -0500921 if not isinstance(name, str):
Brett Cannonf0cb6922013-07-12 11:04:23 -0400922 raise TypeError('module name must be str, not {}'.format(type(name)))
Brett Cannon34d8e412012-02-22 18:33:05 -0500923 if level < 0:
924 raise ValueError('level must be >= 0')
Brett Cannon7fab6762012-02-16 13:43:41 -0500925 if package:
Brett Cannon068915c2012-02-23 18:18:48 -0500926 if not isinstance(package, str):
Brett Cannonf0cb6922013-07-12 11:04:23 -0400927 raise TypeError('__package__ not set to a string')
Brett Cannon7fab6762012-02-16 13:43:41 -0500928 elif package not in sys.modules:
Brett Cannonf0cb6922013-07-12 11:04:23 -0400929 msg = ('Parent module {!r} not loaded, cannot perform relative '
930 'import')
Brett Cannon7fab6762012-02-16 13:43:41 -0500931 raise SystemError(msg.format(package))
932 if not name and level == 0:
Brett Cannonf0cb6922013-07-12 11:04:23 -0400933 raise ValueError('Empty module name')
Brett Cannon7fab6762012-02-16 13:43:41 -0500934
935
Brett Cannon00751102013-07-06 14:48:18 -0400936_ERR_MSG_PREFIX = 'No module named '
937_ERR_MSG = _ERR_MSG_PREFIX + '{!r}'
Brett Cannon7fab6762012-02-16 13:43:41 -0500938
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200939def _find_and_load_unlocked(name, import_):
Brett Cannon7fab6762012-02-16 13:43:41 -0500940 path = None
941 parent = name.rpartition('.')[0]
942 if parent:
943 if parent not in sys.modules:
Nick Coghlan42c07662012-07-31 21:14:18 +1000944 _call_with_frames_removed(import_, parent)
Brett Cannon927d8742012-04-02 20:33:56 -0400945 # Crazy side-effects!
946 if name in sys.modules:
947 return sys.modules[name]
Brett Cannon7fab6762012-02-16 13:43:41 -0500948 parent_module = sys.modules[parent]
949 try:
950 path = parent_module.__path__
951 except AttributeError:
Brett Cannon224b2612013-11-22 14:52:36 -0500952 msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
Serhiy Storchakac4464052014-11-21 20:33:57 +0200953 raise ImportError(msg, name=name) from None
Eric Snowb523f842013-11-22 09:05:39 -0700954 spec = _find_spec(name, path)
955 if spec is None:
Brett Cannon00751102013-07-06 14:48:18 -0400956 raise ImportError(_ERR_MSG.format(name), name=name)
Eric Snowb523f842013-11-22 09:05:39 -0700957 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400958 module = _load_unlocked(spec)
Brett Cannon34d8e412012-02-22 18:33:05 -0500959 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 Cannon34d8e412012-02-22 18:33:05 -0500963 return module
Brett Cannon7fab6762012-02-16 13:43:41 -0500964
965
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200966def _find_and_load(name, import_):
967 """Find and load the module, and release the import lock."""
Eric Snowb523f842013-11-22 09:05:39 -0700968 with _ModuleLockManager(name):
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200969 return _find_and_load_unlocked(name, import_)
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200970
971
Brett Cannon7f9876c2009-02-06 02:47:33 +0000972def _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. Smith41698262011-03-14 10:56:33 -0400977 between import_module and __import__. This includes setting __package__ if
Brett Cannon2c318a12009-02-07 01:15:27 +0000978 the loader did not.
979
Brett Cannon7f9876c2009-02-06 02:47:33 +0000980 """
Brett Cannon7fab6762012-02-16 13:43:41 -0500981 _sanity_check(name, package, level)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000982 if level > 0:
Brett Cannon7fab6762012-02-16 13:43:41 -0500983 name = _resolve_name(name, package, level)
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200984 _imp.acquire_lock()
985 if name not in sys.modules:
Brett Cannon34d8e412012-02-22 18:33:05 -0500986 return _find_and_load(name, _gcd_import)
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200987 module = sys.modules[name]
988 if module is None:
989 _imp.release_lock()
Brett Cannonf0cb6922013-07-12 11:04:23 -0400990 message = ('import of {} halted; '
991 'None in sys.modules'.format(name))
Brett Cannon82da8882013-07-04 17:48:16 -0400992 raise ImportError(message, name=name)
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200993 _lock_unlock_module(name)
994 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000995
Brett Cannon4b03b682012-02-23 20:47:57 -0500996def _handle_fromlist(module, fromlist, import_):
Brett Cannon7fab6762012-02-16 13:43:41 -0500997 """Figure out what __import__ should return.
Brett Cannon2c318a12009-02-07 01:15:27 +0000998
Brett Cannon7fab6762012-02-16 13:43:41 -0500999 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 Cannon2c318a12009-02-07 01:15:27 +00001002
1003 """
Brett Cannon2c318a12009-02-07 01:15:27 +00001004 # The hell that is fromlist ...
Brett Cannon4b03b682012-02-23 20:47:57 -05001005 # If a package was imported, try to import stuff from fromlist.
1006 if hasattr(module, '__path__'):
Brett Cannon461c8132012-07-10 10:05:00 -04001007 if '*' in fromlist:
Brett Cannon4b03b682012-02-23 20:47:57 -05001008 fromlist = list(fromlist)
1009 fromlist.remove('*')
Brett Cannon461c8132012-07-10 10:05:00 -04001010 if hasattr(module, '__all__'):
1011 fromlist.extend(module.__all__)
Florent Xicluna79d79a02012-07-07 13:16:44 +02001012 for x in fromlist:
1013 if not hasattr(module, x):
Brett Cannona6ce4fd2012-10-10 19:03:46 -04001014 from_name = '{}.{}'.format(module.__name__, x)
Brett Cannon7385adc2012-08-17 13:21:16 -04001015 try:
Brett Cannona6ce4fd2012-10-10 19:03:46 -04001016 _call_with_frames_removed(import_, from_name)
Brett Cannon679ecb52013-07-04 17:51:50 -04001017 except ImportError as exc:
Brett Cannon7385adc2012-08-17 13:21:16 -04001018 # Backwards-compatibility dictates we ignore failed
Brett Cannon12c6bda2012-08-24 18:25:59 -04001019 # imports triggered by fromlist for modules that don't
1020 # exist.
Brett Cannon00751102013-07-06 14:48:18 -04001021 if str(exc).startswith(_ERR_MSG_PREFIX):
Brett Cannon679ecb52013-07-04 17:51:50 -04001022 if exc.name == from_name:
1023 continue
Brett Cannona6ce4fd2012-10-10 19:03:46 -04001024 raise
Brett Cannon4b03b682012-02-23 20:47:57 -05001025 return module
Brett Cannon354c26e2012-02-08 18:50:22 -05001026
1027
Brett Cannon7fab6762012-02-16 13:43:41 -05001028def _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 Cannoncb4996a2012-08-06 16:34:44 -04001043def __import__(name, globals=None, locals=None, fromlist=(), level=0):
Brett Cannon7fab6762012-02-16 13:43:41 -05001044 """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 Cannon7fab6762012-02-16 13:43:41 -05001054 if level == 0:
1055 module = _gcd_import(name)
1056 else:
Brett Cannoncb4996a2012-08-06 16:34:44 -04001057 globals_ = globals if globals is not None else {}
1058 package = _calc___package__(globals_)
Brett Cannon7fab6762012-02-16 13:43:41 -05001059 module = _gcd_import(name, package, level)
Brett Cannon4b03b682012-02-23 20:47:57 -05001060 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 Pitrou6efa50a2012-05-07 21:41:59 +02001064 return _gcd_import(name.partition('.')[0])
Brett Cannon4b03b682012-02-23 20:47:57 -05001065 elif not name:
1066 return module
1067 else:
Brett Cannon8ed677d2012-09-28 16:41:39 -04001068 # Figure out where to slice the module's name up to the first dot
1069 # in 'name'.
Brett Cannon4b03b682012-02-23 20:47:57 -05001070 cut_off = len(name) - len(name.partition('.')[0])
Brett Cannon8ed677d2012-09-28 16:41:39 -04001071 # Slice end needs to be positive to alleviate need to special-case
1072 # when ``'.' not in name``.
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001073 return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
Brett Cannon4b03b682012-02-23 20:47:57 -05001074 else:
1075 return _handle_fromlist(module, fromlist, _gcd_import)
Brett Cannon7fab6762012-02-16 13:43:41 -05001076
1077
Eric Snowb523f842013-11-22 09:05:39 -07001078def _builtin_from_name(name):
1079 spec = BuiltinImporter.find_spec(name)
Brett Cannonfddc3112013-11-22 11:58:17 -05001080 if spec is None:
1081 raise ImportError('no built-in module named ' + name)
Brett Cannon2a17bde2014-05-30 14:55:29 -04001082 return _load_unlocked(spec)
Eric Snowb523f842013-11-22 09:05:39 -07001083
Brett Cannon24117a72012-04-20 18:04:03 -04001084
Brett Cannon6f44d662012-04-15 16:08:47 -04001085def _setup(sys_module, _imp_module):
Brett Cannon354c26e2012-02-08 18:50:22 -05001086 """Setup importlib by importing needed built-in modules and injecting them
1087 into the global namespace.
1088
Brett Cannon6f44d662012-04-15 16:08:47 -04001089 As sys is needed for sys.modules access and _imp is needed to load built-in
Brett Cannon0568d6f2012-02-14 18:38:11 -05001090 modules, those two modules must be explicitly passed in.
Brett Cannon354c26e2012-02-08 18:50:22 -05001091
1092 """
Brett Cannonf299abd2015-04-13 14:21:02 -04001093 global _imp, sys
Brett Cannon6f44d662012-04-15 16:08:47 -04001094 _imp = _imp_module
Brett Cannon354c26e2012-02-08 18:50:22 -05001095 sys = sys_module
1096
Eric Snowb523f842013-11-22 09:05:39 -07001097 # Set up the spec for existing builtin/frozen modules.
Brett Cannon0ecd30b2013-02-01 14:04:12 -05001098 module_type = type(sys)
Brett Cannonda9cf0e2013-02-01 15:31:49 -05001099 for name, module in sys.modules.items():
Brett Cannon0ecd30b2013-02-01 14:04:12 -05001100 if isinstance(module, module_type):
Eric Snowb523f842013-11-22 09:05:39 -07001101 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 Cannon2a17bde2014-05-30 14:55:29 -04001108 _init_module_attrs(spec, module)
Brett Cannon354c26e2012-02-08 18:50:22 -05001109
Eric Snowb523f842013-11-22 09:05:39 -07001110 # Directly load built-in modules needed during bootstrap.
Brett Cannon354c26e2012-02-08 18:50:22 -05001111 self_module = sys.modules[__name__]
Eric Snow32439d62015-05-02 19:15:18 -06001112 for builtin_name in ('_warnings',):
Brett Cannon354c26e2012-02-08 18:50:22 -05001113 if builtin_name not in sys.modules:
Eric Snowb523f842013-11-22 09:05:39 -07001114 builtin_module = _builtin_from_name(builtin_name)
Brett Cannon354c26e2012-02-08 18:50:22 -05001115 else:
1116 builtin_module = sys.modules[builtin_name]
1117 setattr(self_module, builtin_name, builtin_module)
1118
Eric Snowb523f842013-11-22 09:05:39 -07001119 # Directly load the _thread module (needed during bootstrap).
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001120 try:
Eric Snowb523f842013-11-22 09:05:39 -07001121 thread_module = _builtin_from_name('_thread')
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001122 except ImportError:
1123 # Python was built without threads
1124 thread_module = None
Eric Snowb523f842013-11-22 09:05:39 -07001125 setattr(self_module, '_thread', thread_module)
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001126
Eric Snowb523f842013-11-22 09:05:39 -07001127 # Directly load the _weakref module (needed during bootstrap).
1128 weakref_module = _builtin_from_name('_weakref')
1129 setattr(self_module, '_weakref', weakref_module)
1130
Brett Cannon0568d6f2012-02-14 18:38:11 -05001131
Brett Cannon6f44d662012-04-15 16:08:47 -04001132def _install(sys_module, _imp_module):
Brett Cannonfeccc092012-05-04 16:47:54 -04001133 """Install importlib as the implementation of import."""
Brett Cannon6f44d662012-04-15 16:08:47 -04001134 _setup(sys_module, _imp_module)
Eric Snow32439d62015-05-02 19:15:18 -06001135
Martin v. Löwise3010a82012-07-28 21:33:05 +02001136 sys.meta_path.append(BuiltinImporter)
1137 sys.meta_path.append(FrozenImporter)
Eric Snow32439d62015-05-02 19:15:18 -06001138
Eric Snow183a9412015-05-15 21:54:59 -06001139 global _bootstrap_external
Eric Snow32439d62015-05-02 19:15:18 -06001140 import _frozen_importlib_external
Eric Snow183a9412015-05-15 21:54:59 -06001141 _bootstrap_external = _frozen_importlib_external
Eric Snow32439d62015-05-02 19:15:18 -06001142 _frozen_importlib_external._install(sys.modules[__name__])