ยปCore Development>Code coverage>Lib/importlib/__init__.py

Python code coverage for Lib/importlib/__init__.py

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