__init__.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. """A pure Python implementation of import."""
  2. __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']
  3. # Bootstrap help #####################################################
  4. # Until bootstrapping is complete, DO NOT import any modules that attempt
  5. # to import importlib._bootstrap (directly or indirectly). Since this
  6. # partially initialised package would be present in sys.modules, those
  7. # modules would get an uninitialised copy of the source version, instead
  8. # of a fully initialised version (either the frozen one or the one
  9. # initialised below if the frozen one is not available).
  10. import _imp # Just the builtin component, NOT the full Python module
  11. import sys
  12. try:
  13. import _frozen_importlib as _bootstrap
  14. except ImportError:
  15. from . import _bootstrap
  16. _bootstrap._setup(sys, _imp)
  17. else:
  18. # importlib._bootstrap is the built-in import, ensure we don't create
  19. # a second copy of the module.
  20. _bootstrap.__name__ = 'importlib._bootstrap'
  21. _bootstrap.__package__ = 'importlib'
  22. try:
  23. _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py')
  24. except NameError:
  25. # __file__ is not guaranteed to be defined, e.g. if this code gets
  26. # frozen by a tool like cx_Freeze.
  27. pass
  28. sys.modules['importlib._bootstrap'] = _bootstrap
  29. try:
  30. import _frozen_importlib_external as _bootstrap_external
  31. except ImportError:
  32. from . import _bootstrap_external
  33. _bootstrap_external._setup(_bootstrap)
  34. _bootstrap._bootstrap_external = _bootstrap_external
  35. else:
  36. _bootstrap_external.__name__ = 'importlib._bootstrap_external'
  37. _bootstrap_external.__package__ = 'importlib'
  38. try:
  39. _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py')
  40. except NameError:
  41. # __file__ is not guaranteed to be defined, e.g. if this code gets
  42. # frozen by a tool like cx_Freeze.
  43. pass
  44. sys.modules['importlib._bootstrap_external'] = _bootstrap_external
  45. # To simplify imports in test code
  46. _pack_uint32 = _bootstrap_external._pack_uint32
  47. _unpack_uint32 = _bootstrap_external._unpack_uint32
  48. # Fully bootstrapped at this point, import whatever you like, circular
  49. # dependencies and startup overhead minimisation permitting :)
  50. import types
  51. import warnings
  52. # Public API #########################################################
  53. from ._bootstrap import __import__
  54. def invalidate_caches():
  55. """Call the invalidate_caches() method on all meta path finders stored in
  56. sys.meta_path (where implemented)."""
  57. for finder in sys.meta_path:
  58. if hasattr(finder, 'invalidate_caches'):
  59. finder.invalidate_caches()
  60. def find_loader(name, path=None):
  61. """Return the loader for the specified module.
  62. This is a backward-compatible wrapper around find_spec().
  63. This function is deprecated in favor of importlib.util.find_spec().
  64. """
  65. warnings.warn('Deprecated since Python 3.4. '
  66. 'Use importlib.util.find_spec() instead.',
  67. DeprecationWarning, stacklevel=2)
  68. try:
  69. loader = sys.modules[name].__loader__
  70. if loader is None:
  71. raise ValueError('{}.__loader__ is None'.format(name))
  72. else:
  73. return loader
  74. except KeyError:
  75. pass
  76. except AttributeError:
  77. raise ValueError('{}.__loader__ is not set'.format(name)) from None
  78. spec = _bootstrap._find_spec(name, path)
  79. # We won't worry about malformed specs (missing attributes).
  80. if spec is None:
  81. return None
  82. if spec.loader is None:
  83. if spec.submodule_search_locations is None:
  84. raise ImportError('spec for {} missing loader'.format(name),
  85. name=name)
  86. raise ImportError('namespace packages do not have loaders',
  87. name=name)
  88. return spec.loader
  89. def import_module(name, package=None):
  90. """Import a module.
  91. The 'package' argument is required when performing a relative import. It
  92. specifies the package to use as the anchor point from which to resolve the
  93. relative import to an absolute import.
  94. """
  95. level = 0
  96. if name.startswith('.'):
  97. if not package:
  98. msg = ("the 'package' argument is required to perform a relative "
  99. "import for {!r}")
  100. raise TypeError(msg.format(name))
  101. for character in name:
  102. if character != '.':
  103. break
  104. level += 1
  105. return _bootstrap._gcd_import(name[level:], package, level)
  106. _RELOADING = {}
  107. def reload(module):
  108. """Reload the module and return it.
  109. The module must have been successfully imported before.
  110. """
  111. if not module or not isinstance(module, types.ModuleType):
  112. raise TypeError("reload() argument must be a module")
  113. try:
  114. name = module.__spec__.name
  115. except AttributeError:
  116. name = module.__name__
  117. if sys.modules.get(name) is not module:
  118. msg = "module {} not in sys.modules"
  119. raise ImportError(msg.format(name), name=name)
  120. if name in _RELOADING:
  121. return _RELOADING[name]
  122. _RELOADING[name] = module
  123. try:
  124. parent_name = name.rpartition('.')[0]
  125. if parent_name:
  126. try:
  127. parent = sys.modules[parent_name]
  128. except KeyError:
  129. msg = "parent {!r} not in sys.modules"
  130. raise ImportError(msg.format(parent_name),
  131. name=parent_name) from None
  132. else:
  133. pkgpath = parent.__path__
  134. else:
  135. pkgpath = None
  136. target = module
  137. spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
  138. if spec is None:
  139. raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
  140. _bootstrap._exec(spec, module)
  141. # The module may have replaced itself in sys.modules!
  142. return sys.modules[name]
  143. finally:
  144. try:
  145. del _RELOADING[name]
  146. except KeyError:
  147. pass