Debian Codegraph @

Lib/importlib/abc.py

raw
1 """Abstract base classes related to import."""
2 from . import _bootstrap_external
3 from . import machinery
4 try:
5 import _frozen_importlib
6 except ImportError as exc:
7 if exc.name != '_frozen_importlib':
8 raise
9 _frozen_importlib = None
10 try:
11 import _frozen_importlib_external
12 except ImportError:
13 _frozen_importlib_external = _bootstrap_external
14 from ._abc import Loader
15 import abc
16
17
18 __all__ = [
19 'Loader', 'MetaPathFinder', 'PathEntryFinder',
20 'ResourceLoader', 'InspectLoader', 'ExecutionLoader',
21 'FileLoader', 'SourceLoader',
22 ]
23
24
25 def _register(abstract_cls, *classes):
26 for cls in classes:
27 abstract_cls.register(cls)
28 if _frozen_importlib is not None:
29 try:
30 frozen_cls = getattr(_frozen_importlib, cls.__name__)
31 except AttributeError:
32 frozen_cls = getattr(_frozen_importlib_external, cls.__name__)
33 abstract_cls.register(frozen_cls)
34
35
36 class MetaPathFinder(metaclass=abc.ABCMeta):
37
38 """Abstract base class for import finders on sys.meta_path."""
39
40 # We don't define find_spec() here since that would break
41 # hasattr checks we do to support backward compatibility.
42
43 def invalidate_caches(self):
44 """An optional method for clearing the finder's cache, if any.
45 This method is used by importlib.invalidate_caches().
46 """
47
48 _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter,
49 machinery.PathFinder, machinery.WindowsRegistryFinder)
50
51
52 class PathEntryFinder(metaclass=abc.ABCMeta):
53
54 """Abstract base class for path entry finders used by PathFinder."""
55
56 def invalidate_caches(self):
57 """An optional method for clearing the finder's cache, if any.
58 This method is used by PathFinder.invalidate_caches().
59 """
60
61 _register(PathEntryFinder, machinery.FileFinder)
62
63
64 class ResourceLoader(Loader):
65
66 """Abstract base class for loaders which can return data from their
67 back-end storage to facilitate reading data to perform an import.
68
69 This ABC represents one of the optional protocols specified by PEP 302.
70
71 For directly loading resources, use TraversableResources instead. This class
72 primarily exists for backwards compatibility with other ABCs in this module.
73
74 """
75
76 @abc.abstractmethod
77 def get_data(self, path):
78 """Abstract method which when implemented should return the bytes for
79 the specified path. The path must be a str."""
80 raise OSError
81
82
83 class InspectLoader(Loader):
84
85 """Abstract base class for loaders which support inspection about the
86 modules they can load.
87
88 This ABC represents one of the optional protocols specified by PEP 302.
89
90 """
91
92 def is_package(self, fullname):
93 """Optional method which when implemented should return whether the
94 module is a package. The fullname is a str. Returns a bool.
95
96 Raises ImportError if the module cannot be found.
97 """
98 raise ImportError
99
100 def get_code(self, fullname):
101 """Method which returns the code object for the module.
102
103 The fullname is a str. Returns a types.CodeType if possible, else
104 returns None if a code object does not make sense
105 (e.g. built-in module). Raises ImportError if the module cannot be
106 found.
107 """
108 source = self.get_source(fullname)
109 if source is None:
110 return None
111 return self.source_to_code(source)
112
113 @abc.abstractmethod
114 def get_source(self, fullname):
115 """Abstract method which should return the source code for the
116 module. The fullname is a str. Returns a str.
117
118 Raises ImportError if the module cannot be found.
119 """
120 raise ImportError
121
122 @staticmethod
123 def source_to_code(data, path='<string>'):
124 """Compile 'data' into a code object.
125
126 The 'data' argument can be anything that compile() can handle. The'path'
127 argument should be where the data was retrieved (when applicable)."""
128 return compile(data, path, 'exec', dont_inherit=True)
129
130 exec_module = _bootstrap_external._LoaderBasics.exec_module
131 load_module = _bootstrap_external._LoaderBasics.load_module
132
133 _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.NamespaceLoader)
134
135
136 class ExecutionLoader(InspectLoader):
137
138 """Abstract base class for loaders that wish to support the execution of
139 modules as scripts.
140
141 This ABC represents one of the optional protocols specified in PEP 302.
142
143 """
144
145 @abc.abstractmethod
146 def get_filename(self, fullname):
147 """Abstract method which should return the value that __file__ is to be
148 set to.
149
150 Raises ImportError if the module cannot be found.
151 """
152 raise ImportError
153
154 def get_code(self, fullname):
155 """Method to return the code object for fullname.
156
157 Should return None if not applicable (e.g. built-in module).
158 Raise ImportError if the module cannot be found.
159 """
160 source = self.get_source(fullname)
161 if source is None:
162 return None
163 try:
164 path = self.get_filename(fullname)
165 except ImportError:
166 return self.source_to_code(source)
167 else:
168 return self.source_to_code(source, path)
169
170 _register(
171 ExecutionLoader,
172 machinery.ExtensionFileLoader,
173 machinery.AppleFrameworkLoader,
174 )
175
176
177 class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader):
178
179 """Abstract base class partially implementing the ResourceLoader and
180 ExecutionLoader ABCs."""
181
182 _register(FileLoader, machinery.SourceFileLoader,
183 machinery.SourcelessFileLoader)
184
185
186 class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader):
187
188 """Abstract base class for loading source code (and optionally any
189 corresponding bytecode).
190
191 To support loading from source code, the abstractmethods inherited from
192 ResourceLoader and ExecutionLoader need to be implemented. To also support
193 loading from bytecode, the optional methods specified directly by this ABC
194 is required.
195
196 Inherited abstractmethods not implemented in this ABC:
197
198 * ResourceLoader.get_data
199 * ExecutionLoader.get_filename
200
201 """
202
203 def path_mtime(self, path):
204 """Return the (int) modification time for the path (str)."""
205 import warnings
206 warnings.warn('SourceLoader.path_mtime is deprecated in favour of '
207 'SourceLoader.path_stats().',
208 DeprecationWarning, stacklevel=2)
209 if self.path_stats.__func__ is SourceLoader.path_stats:
210 raise OSError
211 return int(self.path_stats(path)['mtime'])
212
213 def path_stats(self, path):
214 """Return a metadata dict for the source pointed to by the path (str).
215 Possible keys:
216 - 'mtime' (mandatory) is the numeric timestamp of last source
217 code modification;
218 - 'size' (optional) is the size in bytes of the source code.
219 """
220 if self.path_mtime.__func__ is SourceLoader.path_mtime:
221 raise OSError
222 return {'mtime': self.path_mtime(path)}
223
224 def set_data(self, path, data):
225 """Write the bytes to the path (if possible).
226
227 Accepts a str path and data as bytes.
228
229 Any needed intermediary directories are to be created. If for some
230 reason the file cannot be written because of permissions, fail
231 silently.
232 """
233
234 _register(SourceLoader, machinery.SourceFileLoader)