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

Python code coverage for Lib/importlib/abc.py

#countcontent
1n/a"""Abstract base classes related to import."""
2n/afrom . import _bootstrap
3n/afrom . import _bootstrap_external
4n/afrom . import machinery
5n/atry:
6n/a import _frozen_importlib
7n/aexcept ImportError as exc:
8n/a if exc.name != '_frozen_importlib':
9n/a raise
10n/a _frozen_importlib = None
11n/atry:
12n/a import _frozen_importlib_external
13n/aexcept ImportError as exc:
14n/a _frozen_importlib_external = _bootstrap_external
15n/aimport abc
16n/a
17n/a
18n/adef _register(abstract_cls, *classes):
19n/a for cls in classes:
20n/a abstract_cls.register(cls)
21n/a if _frozen_importlib is not None:
22n/a try:
23n/a frozen_cls = getattr(_frozen_importlib, cls.__name__)
24n/a except AttributeError:
25n/a frozen_cls = getattr(_frozen_importlib_external, cls.__name__)
26n/a abstract_cls.register(frozen_cls)
27n/a
28n/a
29n/aclass Finder(metaclass=abc.ABCMeta):
30n/a
31n/a """Legacy abstract base class for import finders.
32n/a
33n/a It may be subclassed for compatibility with legacy third party
34n/a reimplementations of the import system. Otherwise, finder
35n/a implementations should derive from the more specific MetaPathFinder
36n/a or PathEntryFinder ABCs.
37n/a """
38n/a
39n/a @abc.abstractmethod
40n/a def find_module(self, fullname, path=None):
41n/a """An abstract method that should find a module.
42n/a The fullname is a str and the optional path is a str or None.
43n/a Returns a Loader object or None.
44n/a """
45n/a
46n/a
47n/aclass MetaPathFinder(Finder):
48n/a
49n/a """Abstract base class for import finders on sys.meta_path."""
50n/a
51n/a # We don't define find_spec() here since that would break
52n/a # hasattr checks we do to support backward compatibility.
53n/a
54n/a def find_module(self, fullname, path):
55n/a """Return a loader for the module.
56n/a
57n/a If no module is found, return None. The fullname is a str and
58n/a the path is a list of strings or None.
59n/a
60n/a This method is deprecated in favor of finder.find_spec(). If find_spec()
61n/a exists then backwards-compatible functionality is provided for this
62n/a method.
63n/a
64n/a """
65n/a if not hasattr(self, 'find_spec'):
66n/a return None
67n/a found = self.find_spec(fullname, path)
68n/a return found.loader if found is not None else None
69n/a
70n/a def invalidate_caches(self):
71n/a """An optional method for clearing the finder's cache, if any.
72n/a This method is used by importlib.invalidate_caches().
73n/a """
74n/a
75n/a_register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter,
76n/a machinery.PathFinder, machinery.WindowsRegistryFinder)
77n/a
78n/a
79n/aclass PathEntryFinder(Finder):
80n/a
81n/a """Abstract base class for path entry finders used by PathFinder."""
82n/a
83n/a # We don't define find_spec() here since that would break
84n/a # hasattr checks we do to support backward compatibility.
85n/a
86n/a def find_loader(self, fullname):
87n/a """Return (loader, namespace portion) for the path entry.
88n/a
89n/a The fullname is a str. The namespace portion is a sequence of
90n/a path entries contributing to part of a namespace package. The
91n/a sequence may be empty. If loader is not None, the portion will
92n/a be ignored.
93n/a
94n/a The portion will be discarded if another path entry finder
95n/a locates the module as a normal module or package.
96n/a
97n/a This method is deprecated in favor of finder.find_spec(). If find_spec()
98n/a is provided than backwards-compatible functionality is provided.
99n/a
100n/a """
101n/a if not hasattr(self, 'find_spec'):
102n/a return None, []
103n/a found = self.find_spec(fullname)
104n/a if found is not None:
105n/a if not found.submodule_search_locations:
106n/a portions = []
107n/a else:
108n/a portions = found.submodule_search_locations
109n/a return found.loader, portions
110n/a else:
111n/a return None, []
112n/a
113n/a find_module = _bootstrap_external._find_module_shim
114n/a
115n/a def invalidate_caches(self):
116n/a """An optional method for clearing the finder's cache, if any.
117n/a This method is used by PathFinder.invalidate_caches().
118n/a """
119n/a
120n/a_register(PathEntryFinder, machinery.FileFinder)
121n/a
122n/a
123n/aclass Loader(metaclass=abc.ABCMeta):
124n/a
125n/a """Abstract base class for import loaders."""
126n/a
127n/a def create_module(self, spec):
128n/a """Return a module to initialize and into which to load.
129n/a
130n/a This method should raise ImportError if anything prevents it
131n/a from creating a new module. It may return None to indicate
132n/a that the spec should create the new module.
133n/a """
134n/a # By default, defer to default semantics for the new module.
135n/a return None
136n/a
137n/a # We don't define exec_module() here since that would break
138n/a # hasattr checks we do to support backward compatibility.
139n/a
140n/a def load_module(self, fullname):
141n/a """Return the loaded module.
142n/a
143n/a The module must be added to sys.modules and have import-related
144n/a attributes set properly. The fullname is a str.
145n/a
146n/a ImportError is raised on failure.
147n/a
148n/a This method is deprecated in favor of loader.exec_module(). If
149n/a exec_module() exists then it is used to provide a backwards-compatible
150n/a functionality for this method.
151n/a
152n/a """
153n/a if not hasattr(self, 'exec_module'):
154n/a raise ImportError
155n/a return _bootstrap._load_module_shim(self, fullname)
156n/a
157n/a def module_repr(self, module):
158n/a """Return a module's repr.
159n/a
160n/a Used by the module type when the method does not raise
161n/a NotImplementedError.
162n/a
163n/a This method is deprecated.
164n/a
165n/a """
166n/a # The exception will cause ModuleType.__repr__ to ignore this method.
167n/a raise NotImplementedError
168n/a
169n/a
170n/aclass ResourceLoader(Loader):
171n/a
172n/a """Abstract base class for loaders which can return data from their
173n/a back-end storage.
174n/a
175n/a This ABC represents one of the optional protocols specified by PEP 302.
176n/a
177n/a """
178n/a
179n/a @abc.abstractmethod
180n/a def get_data(self, path):
181n/a """Abstract method which when implemented should return the bytes for
182n/a the specified path. The path must be a str."""
183n/a raise IOError
184n/a
185n/a
186n/aclass InspectLoader(Loader):
187n/a
188n/a """Abstract base class for loaders which support inspection about the
189n/a modules they can load.
190n/a
191n/a This ABC represents one of the optional protocols specified by PEP 302.
192n/a
193n/a """
194n/a
195n/a def is_package(self, fullname):
196n/a """Optional method which when implemented should return whether the
197n/a module is a package. The fullname is a str. Returns a bool.
198n/a
199n/a Raises ImportError if the module cannot be found.
200n/a """
201n/a raise ImportError
202n/a
203n/a def get_code(self, fullname):
204n/a """Method which returns the code object for the module.
205n/a
206n/a The fullname is a str. Returns a types.CodeType if possible, else
207n/a returns None if a code object does not make sense
208n/a (e.g. built-in module). Raises ImportError if the module cannot be
209n/a found.
210n/a """
211n/a source = self.get_source(fullname)
212n/a if source is None:
213n/a return None
214n/a return self.source_to_code(source)
215n/a
216n/a @abc.abstractmethod
217n/a def get_source(self, fullname):
218n/a """Abstract method which should return the source code for the
219n/a module. The fullname is a str. Returns a str.
220n/a
221n/a Raises ImportError if the module cannot be found.
222n/a """
223n/a raise ImportError
224n/a
225n/a @staticmethod
226n/a def source_to_code(data, path='<string>'):
227n/a """Compile 'data' into a code object.
228n/a
229n/a The 'data' argument can be anything that compile() can handle. The'path'
230n/a argument should be where the data was retrieved (when applicable)."""
231n/a return compile(data, path, 'exec', dont_inherit=True)
232n/a
233n/a exec_module = _bootstrap_external._LoaderBasics.exec_module
234n/a load_module = _bootstrap_external._LoaderBasics.load_module
235n/a
236n/a_register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter)
237n/a
238n/a
239n/aclass ExecutionLoader(InspectLoader):
240n/a
241n/a """Abstract base class for loaders that wish to support the execution of
242n/a modules as scripts.
243n/a
244n/a This ABC represents one of the optional protocols specified in PEP 302.
245n/a
246n/a """
247n/a
248n/a @abc.abstractmethod
249n/a def get_filename(self, fullname):
250n/a """Abstract method which should return the value that __file__ is to be
251n/a set to.
252n/a
253n/a Raises ImportError if the module cannot be found.
254n/a """
255n/a raise ImportError
256n/a
257n/a def get_code(self, fullname):
258n/a """Method to return the code object for fullname.
259n/a
260n/a Should return None if not applicable (e.g. built-in module).
261n/a Raise ImportError if the module cannot be found.
262n/a """
263n/a source = self.get_source(fullname)
264n/a if source is None:
265n/a return None
266n/a try:
267n/a path = self.get_filename(fullname)
268n/a except ImportError:
269n/a return self.source_to_code(source)
270n/a else:
271n/a return self.source_to_code(source, path)
272n/a
273n/a_register(ExecutionLoader, machinery.ExtensionFileLoader)
274n/a
275n/a
276n/aclass FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader):
277n/a
278n/a """Abstract base class partially implementing the ResourceLoader and
279n/a ExecutionLoader ABCs."""
280n/a
281n/a_register(FileLoader, machinery.SourceFileLoader,
282n/a machinery.SourcelessFileLoader)
283n/a
284n/a
285n/aclass SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader):
286n/a
287n/a """Abstract base class for loading source code (and optionally any
288n/a corresponding bytecode).
289n/a
290n/a To support loading from source code, the abstractmethods inherited from
291n/a ResourceLoader and ExecutionLoader need to be implemented. To also support
292n/a loading from bytecode, the optional methods specified directly by this ABC
293n/a is required.
294n/a
295n/a Inherited abstractmethods not implemented in this ABC:
296n/a
297n/a * ResourceLoader.get_data
298n/a * ExecutionLoader.get_filename
299n/a
300n/a """
301n/a
302n/a def path_mtime(self, path):
303n/a """Return the (int) modification time for the path (str)."""
304n/a if self.path_stats.__func__ is SourceLoader.path_stats:
305n/a raise IOError
306n/a return int(self.path_stats(path)['mtime'])
307n/a
308n/a def path_stats(self, path):
309n/a """Return a metadata dict for the source pointed to by the path (str).
310n/a Possible keys:
311n/a - 'mtime' (mandatory) is the numeric timestamp of last source
312n/a code modification;
313n/a - 'size' (optional) is the size in bytes of the source code.
314n/a """
315n/a if self.path_mtime.__func__ is SourceLoader.path_mtime:
316n/a raise IOError
317n/a return {'mtime': self.path_mtime(path)}
318n/a
319n/a def set_data(self, path, data):
320n/a """Write the bytes to the path (if possible).
321n/a
322n/a Accepts a str path and data as bytes.
323n/a
324n/a Any needed intermediary directories are to be created. If for some
325n/a reason the file cannot be written because of permissions, fail
326n/a silently.
327n/a """
328n/a
329n/a_register(SourceLoader, machinery.SourceFileLoader)