-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path__init__.py
350 lines (274 loc) · 10.5 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""
lazy_loader
===========
Makes it easy to load subpackages and functions on demand.
"""
import ast
import builtins
import importlib
import importlib.util
import inspect
import os
import sys
import types
import warnings
from collections import defaultdict
from types import SimpleNamespace
__all__ = ["attach", "load", "attach_stub"]
def attach(package_name, submodules=None, submod_attrs=None):
"""Attach lazily loaded submodules, functions, or other attributes.
Typically, modules import submodules and attributes as follows::
import mysubmodule
import anothersubmodule
from .foo import someattr
The idea is to replace a package's `__getattr__`, `__dir__`, and
`__all__`, such that all imports work exactly the way they would
with normal imports, except that the import occurs upon first use.
The typical way to call this function, replacing the above imports, is::
__getattr__, __dir__, __all__ = lazy.attach(
__name__,
['mysubmodule', 'anothersubmodule'],
{'foo': ['someattr']}
)
This functionality requires Python 3.7 or higher.
Parameters
----------
package_name : str
Typically use ``__name__``.
submodules : set
List of submodules to attach.
submod_attrs : dict
Dictionary of submodule -> list of attributes / functions.
These attributes are imported as they are used.
Returns
-------
__getattr__, __dir__, __all__
"""
if submod_attrs is None:
submod_attrs = {}
if submodules is None:
submodules = set()
else:
submodules = set(submodules)
attr_to_modules = {
attr: mod for mod, attrs in submod_attrs.items() for attr in attrs
}
__all__ = sorted(submodules | attr_to_modules.keys())
def __getattr__(name):
if name in submodules:
return importlib.import_module(f"{package_name}.{name}")
elif name in attr_to_modules:
submod_path = f"{package_name}.{attr_to_modules[name]}"
submod = importlib.import_module(submod_path)
attr = getattr(submod, name)
# If the attribute lives in a file (module) with the same
# name as the attribute, ensure that the attribute and *not*
# the module is accessible on the package.
if name == attr_to_modules[name]:
pkg = sys.modules[package_name]
pkg.__dict__[name] = attr
return attr
else:
raise AttributeError(f"No {package_name} attribute {name}")
def __dir__():
return __all__
if os.environ.get("EAGER_IMPORT", ""):
for attr in set(attr_to_modules.keys()) | submodules:
__getattr__(attr)
return __getattr__, __dir__, list(__all__)
class DelayedImportErrorModule(types.ModuleType):
def __init__(self, frame_data, *args, **kwargs):
self.__frame_data = frame_data
super().__init__(*args, **kwargs)
def __getattr__(self, x):
if x in ("__class__", "__file__", "__frame_data"):
super().__getattr__(x)
else:
fd = self.__frame_data
raise ModuleNotFoundError(
f"No module named '{fd['spec']}'\n\n"
"This error is lazily reported, having originally occured in\n"
f' File {fd["filename"]}, line {fd["lineno"]}, in {fd["function"]}\n\n'
f'----> {"".join(fd["code_context"]).strip()}'
)
def load(fullname, error_on_import=False):
"""Return a lazily imported proxy for a module.
We often see the following pattern::
def myfunc():
import numpy as np
np.norm(...)
....
Putting the import inside the function prevents, in this case,
`numpy`, from being imported at function definition time.
That saves time if `myfunc` ends up not being called.
This `load` function returns a proxy module that, upon access, imports
the actual module. So the idiom equivalent to the above example is::
np = lazy.load("numpy")
def myfunc():
np.norm(...)
....
The initial import time is fast because the actual import is delayed
until the first attribute is requested. The overall import time may
decrease as well for users that don't make use of large portions
of your library.
Warning
-------
While lazily loading *sub*packages technically works, it causes the
package (that contains the subpackage) to be eagerly loaded even
if the package is already lazily loaded.
So, you probably shouldn't use subpackages with this `load` feature.
Instead you should encourage the package maintainers to use the
`lazy_loader.attach` to make their subpackages load lazily.
Parameters
----------
fullname : str
The full name of the module or submodule to import. For example::
sp = lazy.load('scipy') # import scipy as sp
error_on_import : bool
Whether to postpone raising import errors until the module is accessed.
If set to `True`, import errors are raised as soon as `load` is called.
Returns
-------
pm : importlib.util._LazyModule
Proxy module. Can be used like any regularly imported module.
Actual loading of the module occurs upon first attribute request.
"""
try:
return sys.modules[fullname]
except KeyError:
pass
if "." in fullname:
msg = (
"subpackages can technically be lazily loaded, but it causes the "
"package to be eagerly loaded even if it is already lazily loaded."
"So, you probably shouldn't use subpackages with this lazy feature."
)
warnings.warn(msg, RuntimeWarning)
spec = importlib.util.find_spec(fullname)
if spec is None:
if error_on_import:
raise ModuleNotFoundError(f"No module named '{fullname}'")
else:
try:
parent = inspect.stack()[1]
frame_data = {
"spec": fullname,
"filename": parent.filename,
"lineno": parent.lineno,
"function": parent.function,
"code_context": parent.code_context,
}
return DelayedImportErrorModule(frame_data, "DelayedImportErrorModule")
finally:
del parent
module = importlib.util.module_from_spec(spec)
sys.modules[fullname] = module
loader = importlib.util.LazyLoader(spec.loader)
loader.exec_module(module)
return module
class _StubVisitor(ast.NodeVisitor):
"""AST visitor to parse a stub file for submodules and submod_attrs."""
def __init__(self):
self._submodules = set()
self._submod_attrs = {}
def visit_ImportFrom(self, node: ast.ImportFrom):
if node.level != 1:
raise ValueError(
"Only within-module imports are supported (`from .* import`)"
)
if node.module:
attrs: list = self._submod_attrs.setdefault(node.module, [])
attrs.extend(alias.name for alias in node.names)
else:
self._submodules.update(alias.name for alias in node.names)
def attach_stub(package_name: str, filename: str):
"""Attach lazily loaded submodules, functions from a type stub.
This is a variant on ``attach`` that will parse a `.pyi` stub file to
infer ``submodules`` and ``submod_attrs``. This allows static type checkers
to find imports, while still providing lazy loading at runtime.
Parameters
----------
package_name : str
Typically use ``__name__``.
filename : str
Path to `.py` file which has an adjacent `.pyi` file.
Typically use ``__file__``.
Returns
-------
__getattr__, __dir__, __all__
The same output as ``attach``.
Raises
------
ValueError
If a stub file is not found for `filename`, or if the stubfile is formmated
incorrectly (e.g. if it contains an relative import from outside of the module)
"""
stubfile = (
filename if filename.endswith("i")
else f"{os.path.splitext(filename)[0]}.pyi"
)
if not os.path.exists(stubfile):
raise ValueError(
f"Cannot load imports from non-existent stub {stubfile!r}",
)
with open(stubfile) as f:
stub_node = ast.parse(f.read())
visitor = _StubVisitor()
visitor.visit(stub_node)
return attach(package_name, visitor._submodules, visitor._submod_attrs)
PLACEHOLDER = object()
class lazy_imports:
"""
Context manager that will block imports and make them lazy.
>>> import lazy_loader
>>> with lazy_loader.lazy_imports():
>>> from ._mod import some_func
"""
def __init__(self):
self.imports = []
self.submodules = []
self.submod_attrs = defaultdict(list)
def __enter__(self):
# Prevent normal importing
self.import_fun = builtins.__import__
builtins.__import__ = self._my_import
return self
def __exit__(self, type, value, tb):
# Restore importing
builtins.__import__ = self.import_fun
last_frame = inspect.currentframe().f_back
# Remove imported things
for submod in self.submodules:
mod = submod.partition(".")[0]
del last_frame.f_globals[mod]
for mod, attr_list in self.submod_attrs.items():
for attr in attr_list:
del last_frame.f_globals[attr]
# Inject the outputs into the module globals
package_name = last_frame.f_globals["__name__"]
g, d, a = attach(
package_name,
self.submodules,
self.submod_attrs,
)
last_frame.f_globals["__getattr__"] = g
last_frame.f_globals["__dir__"] = d
last_frame.f_globals["__all__"] = a
def _my_import(self, name, globals=None, locals=None, fromlist=(), level=0):
builtins.__import__ = self.import_fun
self.imports.append(
{"name": name, "fromlist": fromlist, "level": level}
)
if fromlist is None:
raise NotImplementedError(
"Absolute imports are not currently "
"supported by lazy_loader."
)
elif name == "":
self.submodules.extend(fromlist)
else:
self.submod_attrs[name].extend(fromlist)
builtins.__import__ = self._my_import
if fromlist:
return SimpleNamespace(**{k: PLACEHOLDER for k in fromlist})
return PLACEHOLDER