ยปCore Development>Code coverage>Lib/imp.py

Python code coverage for Lib/imp.py

#countcontent
1n/a"""This module provides the components needed to build your own __import__
2n/afunction. Undocumented functions are obsolete.
3n/a
4n/aIn most cases it is preferred you consider using the importlib module's
5n/afunctionality over this module.
6n/a
7n/a"""
8n/a# (Probably) need to stay in _imp
9n/afrom _imp import (lock_held, acquire_lock, release_lock,
10n/a get_frozen_object, is_frozen_package,
11n/a init_frozen, is_builtin, is_frozen,
12n/a _fix_co_filename)
13n/atry:
14n/a from _imp import create_dynamic
15n/aexcept ImportError:
16n/a # Platform doesn't support dynamic loading.
17n/a create_dynamic = None
18n/a
19n/afrom importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
20n/afrom importlib._bootstrap_external import SourcelessFileLoader
21n/a
22n/afrom importlib import machinery
23n/afrom importlib import util
24n/aimport importlib
25n/aimport os
26n/aimport sys
27n/aimport tokenize
28n/aimport types
29n/aimport warnings
30n/a
31n/awarnings.warn("the imp module is deprecated in favour of importlib; "
32n/a "see the module's documentation for alternative uses",
33n/a DeprecationWarning, stacklevel=2)
34n/a
35n/a# DEPRECATED
36n/aSEARCH_ERROR = 0
37n/aPY_SOURCE = 1
38n/aPY_COMPILED = 2
39n/aC_EXTENSION = 3
40n/aPY_RESOURCE = 4
41n/aPKG_DIRECTORY = 5
42n/aC_BUILTIN = 6
43n/aPY_FROZEN = 7
44n/aPY_CODERESOURCE = 8
45n/aIMP_HOOK = 9
46n/a
47n/a
48n/adef new_module(name):
49n/a """**DEPRECATED**
50n/a
51n/a Create a new module.
52n/a
53n/a The module is not entered into sys.modules.
54n/a
55n/a """
56n/a return types.ModuleType(name)
57n/a
58n/a
59n/adef get_magic():
60n/a """**DEPRECATED**
61n/a
62n/a Return the magic number for .pyc files.
63n/a """
64n/a return util.MAGIC_NUMBER
65n/a
66n/a
67n/adef get_tag():
68n/a """Return the magic tag for .pyc files."""
69n/a return sys.implementation.cache_tag
70n/a
71n/a
72n/adef cache_from_source(path, debug_override=None):
73n/a """**DEPRECATED**
74n/a
75n/a Given the path to a .py file, return the path to its .pyc file.
76n/a
77n/a The .py file does not need to exist; this simply returns the path to the
78n/a .pyc file calculated as if the .py file were imported.
79n/a
80n/a If debug_override is not None, then it must be a boolean and is used in
81n/a place of sys.flags.optimize.
82n/a
83n/a If sys.implementation.cache_tag is None then NotImplementedError is raised.
84n/a
85n/a """
86n/a with warnings.catch_warnings():
87n/a warnings.simplefilter('ignore')
88n/a return util.cache_from_source(path, debug_override)
89n/a
90n/a
91n/adef source_from_cache(path):
92n/a """**DEPRECATED**
93n/a
94n/a Given the path to a .pyc. file, return the path to its .py file.
95n/a
96n/a The .pyc file does not need to exist; this simply returns the path to
97n/a the .py file calculated to correspond to the .pyc file. If path does
98n/a not conform to PEP 3147 format, ValueError will be raised. If
99n/a sys.implementation.cache_tag is None then NotImplementedError is raised.
100n/a
101n/a """
102n/a return util.source_from_cache(path)
103n/a
104n/a
105n/adef get_suffixes():
106n/a """**DEPRECATED**"""
107n/a extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
108n/a source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
109n/a bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
110n/a
111n/a return extensions + source + bytecode
112n/a
113n/a
114n/aclass NullImporter:
115n/a
116n/a """**DEPRECATED**
117n/a
118n/a Null import object.
119n/a
120n/a """
121n/a
122n/a def __init__(self, path):
123n/a if path == '':
124n/a raise ImportError('empty pathname', path='')
125n/a elif os.path.isdir(path):
126n/a raise ImportError('existing directory', path=path)
127n/a
128n/a def find_module(self, fullname):
129n/a """Always returns None."""
130n/a return None
131n/a
132n/a
133n/aclass _HackedGetData:
134n/a
135n/a """Compatibility support for 'file' arguments of various load_*()
136n/a functions."""
137n/a
138n/a def __init__(self, fullname, path, file=None):
139n/a super().__init__(fullname, path)
140n/a self.file = file
141n/a
142n/a def get_data(self, path):
143n/a """Gross hack to contort loader to deal w/ load_*()'s bad API."""
144n/a if self.file and path == self.path:
145n/a if not self.file.closed:
146n/a file = self.file
147n/a else:
148n/a self.file = file = open(self.path, 'r')
149n/a
150n/a with file:
151n/a # Technically should be returning bytes, but
152n/a # SourceLoader.get_code() just passed what is returned to
153n/a # compile() which can handle str. And converting to bytes would
154n/a # require figuring out the encoding to decode to and
155n/a # tokenize.detect_encoding() only accepts bytes.
156n/a return file.read()
157n/a else:
158n/a return super().get_data(path)
159n/a
160n/a
161n/aclass _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
162n/a
163n/a """Compatibility support for implementing load_source()."""
164n/a
165n/a
166n/adef load_source(name, pathname, file=None):
167n/a loader = _LoadSourceCompatibility(name, pathname, file)
168n/a spec = util.spec_from_file_location(name, pathname, loader=loader)
169n/a if name in sys.modules:
170n/a module = _exec(spec, sys.modules[name])
171n/a else:
172n/a module = _load(spec)
173n/a # To allow reloading to potentially work, use a non-hacked loader which
174n/a # won't rely on a now-closed file object.
175n/a module.__loader__ = machinery.SourceFileLoader(name, pathname)
176n/a module.__spec__.loader = module.__loader__
177n/a return module
178n/a
179n/a
180n/aclass _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
181n/a
182n/a """Compatibility support for implementing load_compiled()."""
183n/a
184n/a
185n/adef load_compiled(name, pathname, file=None):
186n/a """**DEPRECATED**"""
187n/a loader = _LoadCompiledCompatibility(name, pathname, file)
188n/a spec = util.spec_from_file_location(name, pathname, loader=loader)
189n/a if name in sys.modules:
190n/a module = _exec(spec, sys.modules[name])
191n/a else:
192n/a module = _load(spec)
193n/a # To allow reloading to potentially work, use a non-hacked loader which
194n/a # won't rely on a now-closed file object.
195n/a module.__loader__ = SourcelessFileLoader(name, pathname)
196n/a module.__spec__.loader = module.__loader__
197n/a return module
198n/a
199n/a
200n/adef load_package(name, path):
201n/a """**DEPRECATED**"""
202n/a if os.path.isdir(path):
203n/a extensions = (machinery.SOURCE_SUFFIXES[:] +
204n/a machinery.BYTECODE_SUFFIXES[:])
205n/a for extension in extensions:
206n/a path = os.path.join(path, '__init__'+extension)
207n/a if os.path.exists(path):
208n/a break
209n/a else:
210n/a raise ValueError('{!r} is not a package'.format(path))
211n/a spec = util.spec_from_file_location(name, path,
212n/a submodule_search_locations=[])
213n/a if name in sys.modules:
214n/a return _exec(spec, sys.modules[name])
215n/a else:
216n/a return _load(spec)
217n/a
218n/a
219n/adef load_module(name, file, filename, details):
220n/a """**DEPRECATED**
221n/a
222n/a Load a module, given information returned by find_module().
223n/a
224n/a The module name must include the full package name, if any.
225n/a
226n/a """
227n/a suffix, mode, type_ = details
228n/a if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
229n/a raise ValueError('invalid file open mode {!r}'.format(mode))
230n/a elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
231n/a msg = 'file object required for import (type code {})'.format(type_)
232n/a raise ValueError(msg)
233n/a elif type_ == PY_SOURCE:
234n/a return load_source(name, filename, file)
235n/a elif type_ == PY_COMPILED:
236n/a return load_compiled(name, filename, file)
237n/a elif type_ == C_EXTENSION and load_dynamic is not None:
238n/a if file is None:
239n/a with open(filename, 'rb') as opened_file:
240n/a return load_dynamic(name, filename, opened_file)
241n/a else:
242n/a return load_dynamic(name, filename, file)
243n/a elif type_ == PKG_DIRECTORY:
244n/a return load_package(name, filename)
245n/a elif type_ == C_BUILTIN:
246n/a return init_builtin(name)
247n/a elif type_ == PY_FROZEN:
248n/a return init_frozen(name)
249n/a else:
250n/a msg = "Don't know how to import {} (type code {})".format(name, type_)
251n/a raise ImportError(msg, name=name)
252n/a
253n/a
254n/adef find_module(name, path=None):
255n/a """**DEPRECATED**
256n/a
257n/a Search for a module.
258n/a
259n/a If path is omitted or None, search for a built-in, frozen or special
260n/a module and continue search in sys.path. The module name cannot
261n/a contain '.'; to search for a submodule of a package, pass the
262n/a submodule name and the package's __path__.
263n/a
264n/a """
265n/a if not isinstance(name, str):
266n/a raise TypeError("'name' must be a str, not {}".format(type(name)))
267n/a elif not isinstance(path, (type(None), list)):
268n/a # Backwards-compatibility
269n/a raise RuntimeError("'path' must be None or a list, "
270n/a "not {}".format(type(path)))
271n/a
272n/a if path is None:
273n/a if is_builtin(name):
274n/a return None, None, ('', '', C_BUILTIN)
275n/a elif is_frozen(name):
276n/a return None, None, ('', '', PY_FROZEN)
277n/a else:
278n/a path = sys.path
279n/a
280n/a for entry in path:
281n/a package_directory = os.path.join(entry, name)
282n/a for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
283n/a package_file_name = '__init__' + suffix
284n/a file_path = os.path.join(package_directory, package_file_name)
285n/a if os.path.isfile(file_path):
286n/a return None, package_directory, ('', '', PKG_DIRECTORY)
287n/a for suffix, mode, type_ in get_suffixes():
288n/a file_name = name + suffix
289n/a file_path = os.path.join(entry, file_name)
290n/a if os.path.isfile(file_path):
291n/a break
292n/a else:
293n/a continue
294n/a break # Break out of outer loop when breaking out of inner loop.
295n/a else:
296n/a raise ImportError(_ERR_MSG.format(name), name=name)
297n/a
298n/a encoding = None
299n/a if 'b' not in mode:
300n/a with open(file_path, 'rb') as file:
301n/a encoding = tokenize.detect_encoding(file.readline)[0]
302n/a file = open(file_path, mode, encoding=encoding)
303n/a return file, file_path, (suffix, mode, type_)
304n/a
305n/a
306n/adef reload(module):
307n/a """**DEPRECATED**
308n/a
309n/a Reload the module and return it.
310n/a
311n/a The module must have been successfully imported before.
312n/a
313n/a """
314n/a return importlib.reload(module)
315n/a
316n/a
317n/adef init_builtin(name):
318n/a """**DEPRECATED**
319n/a
320n/a Load and return a built-in module by name, or None is such module doesn't
321n/a exist
322n/a """
323n/a try:
324n/a return _builtin_from_name(name)
325n/a except ImportError:
326n/a return None
327n/a
328n/a
329n/aif create_dynamic:
330n/a def load_dynamic(name, path, file=None):
331n/a """**DEPRECATED**
332n/a
333n/a Load an extension module.
334n/a """
335n/a import importlib.machinery
336n/a loader = importlib.machinery.ExtensionFileLoader(name, path)
337n/a
338n/a # Issue #24748: Skip the sys.modules check in _load_module_shim;
339n/a # always load new extension
340n/a spec = importlib.machinery.ModuleSpec(
341n/a name=name, loader=loader, origin=path)
342n/a return _load(spec)
343n/a
344n/aelse:
345n/a load_dynamic = None