_bootstrap.py 37 KB
Newer Older
1 2 3 4 5 6 7 8
"""Core implementation of import.

This module is NOT meant to be directly imported! It has been designed such
that it can be bootstrapped into Python as the implementation of import. As
such it requires the injection of specific modules and attributes in order to
work. One should use importlib as the public-facing version of this module.

"""
9 10 11
#
# IMPORTANT: Whenever making changes to this module, be sure to run
# a top-level make in order to get the frozen version of the module
12
# updated. Not doing so will result in the Makefile to fail for
13 14 15
# all others who don't have a ./python around to freeze the module
# in the early stages of compilation.
#
16

17 18
# See importlib._setup() for what is injected into the global namespace.

19 20 21 22
# When editing this code be aware that code executed at import time CANNOT
# reference any injected objects! This includes not only global code but also
# anything specified at the class level.

23 24
# Bootstrap-related code ######################################################

25 26
_bootstrap_external = None

27
def _wrap(new, old):
28
    """Simple substitute for functools.update_wrapper."""
29
    for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
30 31
        if hasattr(old, replace):
            setattr(new, replace, getattr(old, replace))
32 33 34
    new.__dict__.update(old.__dict__)


35 36 37 38
def _new_module(name):
    return type(sys)(name)


39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
class _ManageReload:

    """Manages the possible clean-up of sys.modules for load_module()."""

    def __init__(self, name):
        self._name = name

    def __enter__(self):
        self._is_reload = self._name in sys.modules

    def __exit__(self, *args):
        if any(arg is not None for arg in args) and not self._is_reload:
            try:
                del sys.modules[self._name]
            except KeyError:
                pass

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
# Module-level locking ########################################################

# A dict mapping module names to weakrefs of _ModuleLock instances
_module_locks = {}
# A dict mapping thread ids to _ModuleLock instances
_blocking_on = {}


class _DeadlockError(RuntimeError):
    pass


class _ModuleLock:
    """A recursive lock implementation which is able to detect deadlocks
    (e.g. thread 1 trying to take locks A then B, and thread 2 trying to
    take locks B then A).
    """

    def __init__(self, name):
        self.lock = _thread.allocate_lock()
        self.wakeup = _thread.allocate_lock()
        self.name = name
        self.owner = None
        self.count = 0
        self.waiters = 0

    def has_deadlock(self):
        # Deadlock avoidance for concurrent circular imports.
        me = _thread.get_ident()
        tid = self.owner
        while True:
            lock = _blocking_on.get(tid)
            if lock is None:
                return False
            tid = lock.owner
            if tid == me:
                return True

    def acquire(self):
        """
        Acquire the module lock.  If a potential deadlock is detected,
        a _DeadlockError is raised.
        Otherwise, the lock is always acquired and True is returned.
        """
        tid = _thread.get_ident()
        _blocking_on[tid] = self
        try:
            while True:
                with self.lock:
                    if self.count == 0 or self.owner == tid:
                        self.owner = tid
                        self.count += 1
                        return True
                    if self.has_deadlock():
110
                        raise _DeadlockError('deadlock detected by %r' % self)
111 112 113 114 115 116 117 118 119 120 121 122
                    if self.wakeup.acquire(False):
                        self.waiters += 1
                # Wait for a release() call
                self.wakeup.acquire()
                self.wakeup.release()
        finally:
            del _blocking_on[tid]

    def release(self):
        tid = _thread.get_ident()
        with self.lock:
            if self.owner != tid:
123
                raise RuntimeError('cannot release un-acquired lock')
124 125 126 127 128 129 130 131 132
            assert self.count > 0
            self.count -= 1
            if self.count == 0:
                self.owner = None
                if self.waiters:
                    self.waiters -= 1
                    self.wakeup.release()

    def __repr__(self):
133
        return '_ModuleLock({!r}) at {}'.format(self.name, id(self))
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149


class _DummyModuleLock:
    """A simple _ModuleLock equivalent for Python builds without
    multi-threading support."""

    def __init__(self, name):
        self.name = name
        self.count = 0

    def acquire(self):
        self.count += 1
        return True

    def release(self):
        if self.count == 0:
150
            raise RuntimeError('cannot release un-acquired lock')
151 152 153
        self.count -= 1

    def __repr__(self):
154
        return '_DummyModuleLock({!r}) at {}'.format(self.name, id(self))
155 156


157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
class _ModuleLockManager:

    def __init__(self, name):
        self._name = name
        self._lock = None

    def __enter__(self):
        try:
            self._lock = _get_module_lock(self._name)
        finally:
            _imp.release_lock()
        self._lock.acquire()

    def __exit__(self, *args, **kwargs):
        self._lock.release()


174 175 176 177 178 179 180
# The following two functions are for consumption by Python/import.c.

def _get_module_lock(name):
    """Get or create the module lock for a given module name.

    Should only be called with the import lock taken."""
    lock = None
181
    try:
182
        lock = _module_locks[name]()
183 184
    except KeyError:
        pass
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    if lock is None:
        if _thread is None:
            lock = _DummyModuleLock(name)
        else:
            lock = _ModuleLock(name)
        def cb(_):
            del _module_locks[name]
        _module_locks[name] = _weakref.ref(lock, cb)
    return lock

def _lock_unlock_module(name):
    """Release the global import lock, and acquires then release the
    module lock for a given module name.
    This is used to ensure a module is completely initialized, in the
    event it is being imported by another thread.

    Should only be called with the import lock taken."""
    lock = _get_module_lock(name)
    _imp.release_lock()
    try:
        lock.acquire()
    except _DeadlockError:
        # Concurrent circular import, we'll accept a partially initialized
        # module object.
        pass
    else:
        lock.release()

213 214 215 216 217 218 219 220 221 222 223 224
# Frame stripping magic ###############################################
def _call_with_frames_removed(f, *args, **kwds):
    """remove_importlib_frames in import.c will always remove sequences
    of importlib frames that end with a call to this function

    Use it instead of a normal call in places where including the importlib
    frames introduces unwanted noise into the traceback (e.g. when executing
    module code)
    """
    return f(*args, **kwds)


225
def _verbose_message(message, *args, verbosity=1):
226
    """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
227
    if sys.flags.verbose >= verbosity:
228
        if not message.startswith(('#', 'import ')):
229 230 231
            message = '# ' + message
        print(message.format(*args), file=sys.stderr)

232

233 234
def _requires_builtin(fxn):
    """Decorator to verify the named module is built-in."""
235
    def _requires_builtin_wrapper(self, fullname):
236
        if fullname not in sys.builtin_module_names:
237
            raise ImportError('{!r} is not a built-in module'.format(fullname),
238
                              name=fullname)
239
        return fxn(self, fullname)
240 241
    _wrap(_requires_builtin_wrapper, fxn)
    return _requires_builtin_wrapper
242 243


244 245
def _requires_frozen(fxn):
    """Decorator to verify the named module is frozen."""
246
    def _requires_frozen_wrapper(self, fullname):
247
        if not _imp.is_frozen(fullname):
248
            raise ImportError('{!r} is not a frozen module'.format(fullname),
249
                              name=fullname)
250
        return fxn(self, fullname)
251 252
    _wrap(_requires_frozen_wrapper, fxn)
    return _requires_frozen_wrapper
253 254


255 256
# Typically used by loader classes as a method replacement.
def _load_module_shim(self, fullname):
257 258 259 260 261
    """Load the specified module into sys.modules and return it.

    This method is deprecated.  Use loader.exec_module instead.

    """
262
    spec = spec_from_loader(fullname, self)
263 264
    if fullname in sys.modules:
        module = sys.modules[fullname]
265
        _exec(spec, module)
266 267
        return sys.modules[fullname]
    else:
268
        return _load(spec)
269 270 271 272 273 274 275

# Module specifications #######################################################

def _module_repr(module):
    # The implementation of ModuleType__repr__().
    loader = getattr(module, '__loader__', None)
    if hasattr(loader, 'module_repr'):
276 277 278
        # As soon as BuiltinImporter, FrozenImporter, and NamespaceLoader
        # drop their implementations for module_repr. we can add a
        # deprecation warning here.
279 280 281 282 283 284 285 286 287 288
        try:
            return loader.module_repr(module)
        except Exception:
            pass
    try:
        spec = module.__spec__
    except AttributeError:
        pass
    else:
        if spec is not None:
289
            return _module_repr_from_spec(spec)
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

    # We could use module.__class__.__name__ instead of 'module' in the
    # various repr permutations.
    try:
        name = module.__name__
    except AttributeError:
        name = '?'
    try:
        filename = module.__file__
    except AttributeError:
        if loader is None:
            return '<module {!r}>'.format(name)
        else:
            return '<module {!r} ({!r})>'.format(name, loader)
    else:
        return '<module {!r} from {!r}>'.format(name, filename)


class _installed_safely:

    def __init__(self, module):
        self._module = module
        self._spec = module.__spec__

    def __enter__(self):
        # This must be done before putting the module in sys.modules
        # (otherwise an optimization shortcut in import.c becomes
        # wrong)
        self._spec._initializing = True
        sys.modules[self._spec.name] = self._module

    def __exit__(self, *args):
        try:
            spec = self._spec
            if any(arg is not None for arg in args):
                try:
                    del sys.modules[spec.name]
                except KeyError:
                    pass
            else:
                _verbose_message('import {!r} # {!r}', spec.name, spec.loader)
        finally:
            self._spec._initializing = False


class ModuleSpec:
    """The specification for a module, used for loading.

    A module's spec is the source for information about the module.  For
    data associated with the module, including source, use the spec's
    loader.

    `name` is the absolute name of the module.  `loader` is the loader
    to use when loading the module.  `parent` is the name of the
    package the module is in.  The parent is derived from the name.

    `is_package` determines if the module is considered a package or
    not.  On modules this is reflected by the `__path__` attribute.

    `origin` is the specific location used by the loader from which to
    load the module, if that information is available.  When filename is
    set, origin will match.

    `has_location` indicates that a spec's "origin" reflects a location.
    When this is True, `__file__` attribute of the module is set.

    `cached` is the location of the cached bytecode file, if any.  It
    corresponds to the `__cached__` attribute.

    `submodule_search_locations` is the sequence of path entries to
    search when importing submodules.  If set, is_package should be
    True--and False otherwise.

    Packages are simply modules that (may) have submodules.  If a spec
    has a non-None value in `submodule_search_locations`, the import
    system will consider modules loaded from the spec as packages.

    Only finders (see importlib.abc.MetaPathFinder and
    importlib.abc.PathEntryFinder) should modify ModuleSpec instances.

    """

    def __init__(self, name, loader, *, origin=None, loader_state=None,
                 is_package=None):
        self.name = name
        self.loader = loader
        self.origin = origin
        self.loader_state = loader_state
        self.submodule_search_locations = [] if is_package else None

        # file-location attributes
        self._set_fileattr = False
        self._cached = None

    def __repr__(self):
        args = ['name={!r}'.format(self.name),
                'loader={!r}'.format(self.loader)]
        if self.origin is not None:
            args.append('origin={!r}'.format(self.origin))
        if self.submodule_search_locations is not None:
            args.append('submodule_search_locations={}'
                        .format(self.submodule_search_locations))
        return '{}({})'.format(self.__class__.__name__, ', '.join(args))

    def __eq__(self, other):
        smsl = self.submodule_search_locations
        try:
            return (self.name == other.name and
                    self.loader == other.loader and
                    self.origin == other.origin and
                    smsl == other.submodule_search_locations and
                    self.cached == other.cached and
                    self.has_location == other.has_location)
        except AttributeError:
            return False

    @property
    def cached(self):
        if self._cached is None:
            if self.origin is not None and self._set_fileattr:
410 411
                if _bootstrap_external is None:
                    raise NotImplementedError
412
                self._cached = _bootstrap_external._get_cached(self.origin)
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        return self._cached

    @cached.setter
    def cached(self, cached):
        self._cached = cached

    @property
    def parent(self):
        """The name of the module's parent."""
        if self.submodule_search_locations is None:
            return self.name.rpartition('.')[0]
        else:
            return self.name

    @property
    def has_location(self):
        return self._set_fileattr

431 432 433 434
    @has_location.setter
    def has_location(self, value):
        self._set_fileattr = bool(value)

435 436 437 438

def spec_from_loader(name, loader, *, origin=None, is_package=None):
    """Return a module spec based on various loader methods."""
    if hasattr(loader, 'get_filename'):
439 440 441 442
        if _bootstrap_external is None:
            raise NotImplementedError
        spec_from_file_location = _bootstrap_external.spec_from_file_location

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
        if is_package is None:
            return spec_from_file_location(name, loader=loader)
        search = [] if is_package else None
        return spec_from_file_location(name, loader=loader,
                                       submodule_search_locations=search)

    if is_package is None:
        if hasattr(loader, 'is_package'):
            try:
                is_package = loader.is_package(name)
            except ImportError:
                is_package = None  # aka, undefined
        else:
            # the default
            is_package = False

    return ModuleSpec(name, loader, origin=origin, is_package=is_package)


_POPULATE = object()


def _spec_from_module(module, loader=None, origin=None):
    # This function is meant for use in _setup().
    try:
        spec = module.__spec__
    except AttributeError:
        pass
    else:
        if spec is not None:
            return spec

    name = module.__name__
    if loader is None:
        try:
            loader = module.__loader__
        except AttributeError:
            # loader will stay None.
            pass
    try:
        location = module.__file__
    except AttributeError:
        location = None
    if origin is None:
        if location is None:
            try:
                origin = loader._ORIGIN
            except AttributeError:
                origin = None
        else:
            origin = location
    try:
        cached = module.__cached__
    except AttributeError:
        cached = None
    try:
        submodule_search_locations = list(module.__path__)
    except AttributeError:
        submodule_search_locations = None

    spec = ModuleSpec(name, loader, origin=origin)
    spec._set_fileattr = False if location is None else True
    spec.cached = cached
    spec.submodule_search_locations = submodule_search_locations
    return spec


510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
def _init_module_attrs(spec, module, *, override=False):
    # The passed-in module may be not support attribute assignment,
    # in which case we simply don't set the attributes.
    # __name__
    if (override or getattr(module, '__name__', None) is None):
        try:
            module.__name__ = spec.name
        except AttributeError:
            pass
    # __loader__
    if override or getattr(module, '__loader__', None) is None:
        loader = spec.loader
        if loader is None:
            # A backward compatibility hack.
            if spec.submodule_search_locations is not None:
525 526 527 528
                if _bootstrap_external is None:
                    raise NotImplementedError
                _NamespaceLoader = _bootstrap_external._NamespaceLoader

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
                loader = _NamespaceLoader.__new__(_NamespaceLoader)
                loader._path = spec.submodule_search_locations
        try:
            module.__loader__ = loader
        except AttributeError:
            pass
    # __package__
    if override or getattr(module, '__package__', None) is None:
        try:
            module.__package__ = spec.parent
        except AttributeError:
            pass
    # __spec__
    try:
        module.__spec__ = spec
    except AttributeError:
        pass
    # __path__
    if override or getattr(module, '__path__', None) is None:
        if spec.submodule_search_locations is not None:
549
            try:
550
                module.__path__ = spec.submodule_search_locations
551 552
            except AttributeError:
                pass
553 554 555
    # __file__/__cached__
    if spec.has_location:
        if override or getattr(module, '__file__', None) is None:
556
            try:
557
                module.__file__ = spec.origin
558 559 560
            except AttributeError:
                pass

561 562
        if override or getattr(module, '__cached__', None) is None:
            if spec.cached is not None:
563
                try:
564
                    module.__cached__ = spec.cached
565 566
                except AttributeError:
                    pass
567
    return module
568 569


570 571 572 573 574 575 576 577
def module_from_spec(spec):
    """Create a module based on the provided spec."""
    # Typically loaders will not implement create_module().
    module = None
    if hasattr(spec.loader, 'create_module'):
        # If create_module() returns `None` then it means default
        # module creation should be used.
        module = spec.loader.create_module(spec)
578 579 580 581
    elif hasattr(spec.loader, 'exec_module'):
        _warnings.warn('starting in Python 3.6, loaders defining exec_module() '
                       'must also define create_module()',
                       DeprecationWarning, stacklevel=2)
582 583 584 585
    if module is None:
        module = _new_module(spec.name)
    _init_module_attrs(spec, module)
    return module
586 587


588 589 590 591 592 593 594
def _module_repr_from_spec(spec):
    """Return the repr to use for the module."""
    # We mostly replicate _module_repr() using the spec attributes.
    name = '?' if spec.name is None else spec.name
    if spec.origin is None:
        if spec.loader is None:
            return '<module {!r}>'.format(name)
595
        else:
596 597 598 599 600 601
            return '<module {!r} ({!r})>'.format(name, spec.loader)
    else:
        if spec.has_location:
            return '<module {!r} from {!r}>'.format(name, spec.origin)
        else:
            return '<module {!r} ({})>'.format(spec.name, spec.origin)
602 603


604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
# Used by importlib.reload() and _load_module_shim().
def _exec(spec, module):
    """Execute the spec in an existing module's namespace."""
    name = spec.name
    _imp.acquire_lock()
    with _ModuleLockManager(name):
        if sys.modules.get(name) is not module:
            msg = 'module {!r} not in sys.modules'.format(name)
            raise ImportError(msg, name=name)
        if spec.loader is None:
            if spec.submodule_search_locations is None:
                raise ImportError('missing loader', name=spec.name)
            # namespace package
            _init_module_attrs(spec, module, override=True)
            return module
        _init_module_attrs(spec, module, override=True)
        if not hasattr(spec.loader, 'exec_module'):
            # (issue19713) Once BuiltinImporter and ExtensionFileLoader
            # have exec_module() implemented, we can add a deprecation
            # warning here.
            spec.loader.load_module(name)
        else:
            spec.loader.exec_module(module)
    return sys.modules[name]


def _load_backward_compatible(spec):
    # (issue19713) Once BuiltinImporter and ExtensionFileLoader
    # have exec_module() implemented, we can add a deprecation
    # warning here.
    spec.loader.load_module(spec.name)
    # The module must be in sys.modules at this point!
    module = sys.modules[spec.name]
    if getattr(module, '__loader__', None) is None:
        try:
            module.__loader__ = spec.loader
        except AttributeError:
            pass
    if getattr(module, '__package__', None) is None:
        try:
            # Since module.__path__ may not line up with
            # spec.submodule_search_paths, we can't necessarily rely
            # on spec.parent here.
            module.__package__ = module.__name__
            if not hasattr(module, '__path__'):
                module.__package__ = spec.name.rpartition('.')[0]
        except AttributeError:
            pass
    if getattr(module, '__spec__', None) is None:
        try:
            module.__spec__ = spec
        except AttributeError:
            pass
    return module
658

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
def _load_unlocked(spec):
    # A helper for direct use by the import system.
    if spec.loader is not None:
        # not a namespace package
        if not hasattr(spec.loader, 'exec_module'):
            return _load_backward_compatible(spec)

    module = module_from_spec(spec)
    with _installed_safely(module):
        if spec.loader is None:
            if spec.submodule_search_locations is None:
                raise ImportError('missing loader', name=spec.name)
            # A namespace package so do nothing.
        else:
            spec.loader.exec_module(module)
674

675 676 677 678
    # We don't ensure that the import-related module attributes get
    # set in the sys.modules replacement case.  Such modules are on
    # their own.
    return sys.modules[spec.name]
679

680 681 682 683
# A method used during testing of _load_unlocked() and by
# _load_module_shim().
def _load(spec):
    """Return a new module object, loaded by the spec's loader.
684

685
    The module is not added to its parent.
686

687 688
    If a module is already in sys.modules, that existing module gets
    clobbered.
689

690 691 692 693
    """
    _imp.acquire_lock()
    with _ModuleLockManager(spec.name):
        return _load_unlocked(spec)
694 695


696
# Loaders #####################################################################
697

698
class BuiltinImporter:
699

700
    """Meta path import for built-in modules.
701

702 703
    All methods are either class or static methods to avoid the need to
    instantiate the class.
704 705 706

    """

707 708
    @staticmethod
    def module_repr(module):
709 710 711 712 713
        """Return repr for the module.

        The method is deprecated.  The import machinery does the job itself.

        """
714
        return '<module {!r} (built-in)>'.format(module.__name__)
715

716 717 718 719 720 721 722 723 724
    @classmethod
    def find_spec(cls, fullname, path=None, target=None):
        if path is not None:
            return None
        if _imp.is_builtin(fullname):
            return spec_from_loader(fullname, cls, origin='built-in')
        else:
            return None

725 726
    @classmethod
    def find_module(cls, fullname, path=None):
727
        """Find the built-in module.
728 729 730

        If 'path' is ever specified then the search is considered a failure.

731 732
        This method is deprecated.  Use find_spec() instead.

733
        """
734 735 736
        spec = cls.find_spec(fullname, path)
        return spec.loader if spec is not None else None

737
    @classmethod
738 739 740 741 742 743 744 745 746 747
    def create_module(self, spec):
        """Create a built-in module"""
        if spec.name not in sys.builtin_module_names:
            raise ImportError('{!r} is not a built-in module'.format(spec.name),
                              name=spec.name)
        return _call_with_frames_removed(_imp.create_builtin, spec)

    @classmethod
    def exec_module(self, module):
        """Exec a built-in module"""
748
        _call_with_frames_removed(_imp.exec_builtin, module)
749

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
    @classmethod
    @_requires_builtin
    def get_code(cls, fullname):
        """Return None as built-in modules do not have code objects."""
        return None

    @classmethod
    @_requires_builtin
    def get_source(cls, fullname):
        """Return None as built-in modules do not have source code."""
        return None

    @classmethod
    @_requires_builtin
    def is_package(cls, fullname):
765
        """Return False as built-in modules are never packages."""
766 767
        return False

768 769
    load_module = classmethod(_load_module_shim)

770

771
class FrozenImporter:
772

773
    """Meta path import for frozen modules.
774

775 776
    All methods are either class or static methods to avoid the need to
    instantiate the class.
777

778
    """
779

780 781
    @staticmethod
    def module_repr(m):
782 783 784 785 786
        """Return repr for the module.

        The method is deprecated.  The import machinery does the job itself.

        """
787
        return '<module {!r} (frozen)>'.format(m.__name__)
788

789 790 791 792 793 794 795
    @classmethod
    def find_spec(cls, fullname, path=None, target=None):
        if _imp.is_frozen(fullname):
            return spec_from_loader(fullname, cls, origin='frozen')
        else:
            return None

796 797
    @classmethod
    def find_module(cls, fullname, path=None):
798 799 800 801 802
        """Find a frozen module.

        This method is deprecated.  Use find_spec() instead.

        """
803
        return cls if _imp.is_frozen(fullname) else None
804

805 806 807 808
    @classmethod
    def create_module(cls, spec):
        """Use default semantics for module creation."""

809 810 811 812
    @staticmethod
    def exec_module(module):
        name = module.__spec__.name
        if not _imp.is_frozen(name):
813
            raise ImportError('{!r} is not a frozen module'.format(name),
814 815 816 817
                              name=name)
        code = _call_with_frames_removed(_imp.get_frozen_object, name)
        exec(code, module.__dict__)

818 819
    @classmethod
    def load_module(cls, fullname):
820 821 822 823 824
        """Load a frozen module.

        This method is deprecated.  Use exec_module() instead.

        """
825
        return _load_module_shim(cls, fullname)
826

827 828 829 830
    @classmethod
    @_requires_frozen
    def get_code(cls, fullname):
        """Return the code object for the frozen module."""
831
        return _imp.get_frozen_object(fullname)
832 833 834 835 836 837 838 839 840 841

    @classmethod
    @_requires_frozen
    def get_source(cls, fullname):
        """Return None as frozen modules do not have source code."""
        return None

    @classmethod
    @_requires_frozen
    def is_package(cls, fullname):
Philip Jenvey's avatar
Philip Jenvey committed
842
        """Return True if the frozen module is a package."""
843
        return _imp.is_frozen_package(fullname)
844

845

846
# Import itself ###############################################################
847

848 849 850 851 852 853
class _ImportLockContext:

    """Context manager for the import lock."""

    def __enter__(self):
        """Acquire the import lock."""
854
        _imp.acquire_lock()
855 856 857

    def __exit__(self, exc_type, exc_value, exc_traceback):
        """Release the import lock regardless of any raised exceptions."""
858
        _imp.release_lock()
859

860

861 862
def _resolve_name(name, package, level):
    """Resolve a relative module name to an absolute one."""
Philip Jenvey's avatar
Philip Jenvey committed
863
    bits = package.rsplit('.', level - 1)
864 865 866
    if len(bits) < level:
        raise ValueError('attempted relative import beyond top-level package')
    base = bits[0]
867
    return '{}.{}'.format(base, name) if name else base
868 869


870 871 872 873 874 875 876 877 878
def _find_spec_legacy(finder, name, path):
    # This would be a good place for a DeprecationWarning if
    # we ended up going that route.
    loader = finder.find_module(name, path)
    if loader is None:
        return None
    return spec_from_loader(name, loader)


879
def _find_spec(name, path, target=None):
880
    """Find a module's loader."""
881
    if sys.meta_path is not None and not sys.meta_path:
882
        _warnings.warn('sys.meta_path is empty', ImportWarning)
883 884 885
    # We check sys.modules here for the reload case.  While a passed-in
    # target will usually indicate a reload there is no guarantee, whereas
    # sys.modules provides one.
886
    is_reload = name in sys.modules
887
    for finder in sys.meta_path:
888
        with _ImportLockContext():
889 890 891
            try:
                find_spec = finder.find_spec
            except AttributeError:
892 893
                spec = _find_spec_legacy(finder, name, path)
                if spec is None:
894
                    continue
895
            else:
896 897 898 899 900
                spec = find_spec(name, path, target)
        if spec is not None:
            # The parent import may have already imported this module.
            if not is_reload and name in sys.modules:
                module = sys.modules[name]
901
                try:
902
                    __spec__ = module.__spec__
903
                except AttributeError:
904 905 906 907 908 909 910 911 912 913 914
                    # We use the found spec since that is the one that
                    # we would have used if the parent module hadn't
                    # beaten us to the punch.
                    return spec
                else:
                    if __spec__ is None:
                        return spec
                    else:
                        return __spec__
            else:
                return spec
915 916
    else:
        return None
917

918

919 920
def _sanity_check(name, package, level):
    """Verify arguments are "sane"."""
921
    if not isinstance(name, str):
922
        raise TypeError('module name must be str, not {}'.format(type(name)))
923 924
    if level < 0:
        raise ValueError('level must be >= 0')
925
    if package:
926
        if not isinstance(package, str):
927
            raise TypeError('__package__ not set to a string')
928
        elif package not in sys.modules:
929 930
            msg = ('Parent module {!r} not loaded, cannot perform relative '
                   'import')
931 932
            raise SystemError(msg.format(package))
    if not name and level == 0:
933
        raise ValueError('Empty module name')
934 935


936 937
_ERR_MSG_PREFIX = 'No module named '
_ERR_MSG = _ERR_MSG_PREFIX + '{!r}'
938

939
def _find_and_load_unlocked(name, import_):
940 941 942 943
    path = None
    parent = name.rpartition('.')[0]
    if parent:
        if parent not in sys.modules:
944
            _call_with_frames_removed(import_, parent)
945 946 947
        # Crazy side-effects!
        if name in sys.modules:
            return sys.modules[name]
948 949 950 951
        parent_module = sys.modules[parent]
        try:
            path = parent_module.__path__
        except AttributeError:
952
            msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
953
            raise ImportError(msg, name=name) from None
954 955
    spec = _find_spec(name, path)
    if spec is None:
956
        raise ImportError(_ERR_MSG.format(name), name=name)
957
    else:
958
        module = _load_unlocked(spec)
959 960 961 962 963
    if parent:
        # Set the module as an attribute on its parent.
        parent_module = sys.modules[parent]
        setattr(parent_module, name.rpartition('.')[2], module)
    return module
964 965


966 967
def _find_and_load(name, import_):
    """Find and load the module, and release the import lock."""
968
    with _ModuleLockManager(name):
969 970 971
        return _find_and_load_unlocked(name, import_)


972 973 974 975 976 977 978 979 980 981
def _gcd_import(name, package=None, level=0):
    """Import and return the module based on its name, the package the call is
    being made from, and the level adjustment.

    This function represents the greatest common denominator of functionality
    between import_module and __import__. This includes setting __package__ if
    the loader did not.

    """
    _sanity_check(name, package, level)
982
    if level > 0:
983
        name = _resolve_name(name, package, level)
984 985
    _imp.acquire_lock()
    if name not in sys.modules:
986
        return _find_and_load(name, _gcd_import)
987 988 989
    module = sys.modules[name]
    if module is None:
        _imp.release_lock()
990 991
        message = ('import of {} halted; '
                   'None in sys.modules'.format(name))
992
        raise ImportError(message, name=name)
993 994
    _lock_unlock_module(name)
    return module
995

996
def _handle_fromlist(module, fromlist, import_):
997
    """Figure out what __import__ should return.
998

999 1000 1001
    The import_ parameter is a callable which takes the name of module to
    import. It is required to decouple the function from assuming importlib's
    import implementation is desired.
1002 1003

    """
1004
    # The hell that is fromlist ...
1005 1006
    # If a package was imported, try to import stuff from fromlist.
    if hasattr(module, '__path__'):
1007
        if '*' in fromlist:
1008 1009
            fromlist = list(fromlist)
            fromlist.remove('*')
1010 1011
            if hasattr(module, '__all__'):
                fromlist.extend(module.__all__)
1012 1013
        for x in fromlist:
            if not hasattr(module, x):
1014
                from_name = '{}.{}'.format(module.__name__, x)
1015
                try:
1016
                    _call_with_frames_removed(import_, from_name)
1017
                except ImportError as exc:
1018
                    # Backwards-compatibility dictates we ignore failed
1019 1020
                    # imports triggered by fromlist for modules that don't
                    # exist.
1021
                    if str(exc).startswith(_ERR_MSG_PREFIX):
1022 1023
                        if exc.name == from_name:
                            continue
1024
                    raise
1025
    return module
1026 1027


1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
def _calc___package__(globals):
    """Calculate what __package__ should be.

    __package__ is not guaranteed to be defined or could be set to None
    to represent that its proper value is unknown.

    """
    package = globals.get('__package__')
    if package is None:
        package = globals['__name__']
        if '__path__' not in globals:
            package = package.rpartition('.')[0]
    return package


1043
def __import__(name, globals=None, locals=None, fromlist=(), level=0):
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    """Import a module.

    The 'globals' argument is used to infer where the import is occuring from
    to handle relative imports. The 'locals' argument is ignored. The
    'fromlist' argument specifies what should exist as attributes on the module
    being imported (e.g. ``from module import <fromlist>``).  The 'level'
    argument represents the package location to import from in a relative
    import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).

    """
    if level == 0:
        module = _gcd_import(name)
    else:
1057 1058
        globals_ = globals if globals is not None else {}
        package = _calc___package__(globals_)
1059
        module = _gcd_import(name, package, level)
1060 1061 1062 1063
    if not fromlist:
        # Return up to the first dot in 'name'. This is complicated by the fact
        # that 'name' may be relative.
        if level == 0:
1064
            return _gcd_import(name.partition('.')[0])
1065 1066 1067
        elif not name:
            return module
        else:
Brett Cannon's avatar
Brett Cannon committed
1068 1069
            # Figure out where to slice the module's name up to the first dot
            # in 'name'.
1070
            cut_off = len(name) - len(name.partition('.')[0])
Brett Cannon's avatar
Brett Cannon committed
1071 1072
            # Slice end needs to be positive to alleviate need to special-case
            # when ``'.' not in name``.
1073
            return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
1074 1075
    else:
        return _handle_fromlist(module, fromlist, _gcd_import)
1076 1077


1078 1079
def _builtin_from_name(name):
    spec = BuiltinImporter.find_spec(name)
1080 1081
    if spec is None:
        raise ImportError('no built-in module named ' + name)
1082
    return _load_unlocked(spec)
1083

1084

1085
def _setup(sys_module, _imp_module):
1086 1087 1088
    """Setup importlib by importing needed built-in modules and injecting them
    into the global namespace.

1089
    As sys is needed for sys.modules access and _imp is needed to load built-in
1090
    modules, those two modules must be explicitly passed in.
1091 1092

    """
1093
    global _imp, sys
1094
    _imp = _imp_module
1095 1096
    sys = sys_module

1097
    # Set up the spec for existing builtin/frozen modules.
1098
    module_type = type(sys)
1099
    for name, module in sys.modules.items():
1100
        if isinstance(module, module_type):
1101 1102 1103 1104 1105 1106 1107
            if name in sys.builtin_module_names:
                loader = BuiltinImporter
            elif _imp.is_frozen(name):
                loader = FrozenImporter
            else:
                continue
            spec = _spec_from_module(module, loader)
1108
            _init_module_attrs(spec, module)
1109

1110
    # Directly load built-in modules needed during bootstrap.
1111
    self_module = sys.modules[__name__]
1112
    for builtin_name in ('_warnings',):
1113
        if builtin_name not in sys.modules:
1114
            builtin_module = _builtin_from_name(builtin_name)
1115 1116 1117 1118
        else:
            builtin_module = sys.modules[builtin_name]
        setattr(self_module, builtin_name, builtin_module)

1119
    # Directly load the _thread module (needed during bootstrap).
1120
    try:
1121
        thread_module = _builtin_from_name('_thread')
1122 1123 1124
    except ImportError:
        # Python was built without threads
        thread_module = None
1125 1126 1127 1128 1129
    setattr(self_module, '_thread', thread_module)

    # Directly load the _weakref module (needed during bootstrap).
    weakref_module = _builtin_from_name('_weakref')
    setattr(self_module, '_weakref', weakref_module)
1130

1131

1132
def _install(sys_module, _imp_module):
Brett Cannon's avatar
Brett Cannon committed
1133
    """Install importlib as the implementation of import."""
1134
    _setup(sys_module, _imp_module)
1135

1136 1137
    sys.meta_path.append(BuiltinImporter)
    sys.meta_path.append(FrozenImporter)
1138

1139
    global _bootstrap_external
1140
    import _frozen_importlib_external
1141
    _bootstrap_external = _frozen_importlib_external
1142
    _frozen_importlib_external._install(sys.modules[__name__])