-
Notifications
You must be signed in to change notification settings - Fork 8
/
lazyasd-py2.py
381 lines (316 loc) · 11.6 KB
/
lazyasd-py2.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"""Lazy and self destructive containers for speeding up module import."""
# Copyright 2015-2016, the xonsh developers. All rights reserved.
import os
import sys
import time
import types
import threading
import importlib
try:
from importlib.util import resolve_name
except ImportError:
def resolve_name(name, package):
if name.startswith('.'):
raise NotImplementedError('Python 3 needed for relative modules')
return name
try:
from collections.abc import MutableMapping
except ImportError:
from collections import MutableMapping
__version__ = '0.1.4'
class LazyObject(object):
def __init__(self, load, ctx, name):
"""Lazily loads an object via the load function the first time an
attribute is accessed. Once loaded it will replace itself in the
provided context (typically the globals of the call site) with the
given name.
For example, you can prevent the compilation of a regular expreession
until it is actually used::
DOT = LazyObject((lambda: re.compile('.')), globals(), 'DOT')
Parameters
----------
load : function with no arguments
A loader function that performs the actual object construction.
ctx : Mapping
Context to replace the LazyObject instance in
with the object returned by load().
name : str
Name in the context to give the loaded object. This *should*
be the name on the LHS of the assignment.
"""
self._lasdo = {
'loaded': False,
'load': load,
'ctx': ctx,
'name': name,
}
def _lazy_obj(self):
d = self._lasdo
if d['loaded']:
obj = d['obj']
else:
obj = d['load']()
d['ctx'][d['name']] = d['obj'] = obj
d['loaded'] = True
return obj
def __getattribute__(self, name):
if name == '_lasdo' or name == '_lazy_obj':
return super(LazyObject, self).__getattribute__(name)
obj = self._lazy_obj()
return getattr(obj, name)
def __add__(self, other):
obj = self._lazy_obj()
return obj + other
def __radd__(self, other):
obj = self._lazy_obj()
return other + obj
def __bool__(self):
obj = self._lazy_obj()
return bool(obj)
def __iter__(self):
obj = self._lazy_obj()
for item in obj:
yield item
def __getitem__(self, item):
obj = self._lazy_obj()
return obj[item]
def __setitem__(self, key, value):
obj = self._lazy_obj()
obj[key] = value
def __delitem__(self, item):
obj = self._lazy_obj()
del obj[item]
def __call__(self, *args, **kwargs):
obj = self._lazy_obj()
return obj(*args, **kwargs)
def __lt__(self, other):
obj = self._lazy_obj()
return obj < other
def __le__(self, other):
obj = self._lazy_obj()
return obj <= other
def __eq__(self, other):
obj = self._lazy_obj()
return obj == other
def __ne__(self, other):
obj = self._lazy_obj()
return obj != other
def __gt__(self, other):
obj = self._lazy_obj()
return obj > other
def __ge__(self, other):
obj = self._lazy_obj()
return obj >= other
def __hash__(self):
obj = self._lazy_obj()
return hash(obj)
def __or__(self, other):
obj = self._lazy_obj()
return obj | other
def __str__(self):
return str(self._lazy_obj())
def __repr__(self):
return repr(self._lazy_obj())
def lazyobject(f):
"""Decorator for constructing lazy objects from a function."""
return LazyObject(f, f.__globals__, f.__name__)
class LazyDict(MutableMapping):
def __init__(self, loaders, ctx, name):
"""Dictionary like object that lazily loads its values from an initial
dict of key-loader function pairs. Each key is loaded when its value
is first accessed. Once fully loaded, this object will replace itself
in the provided context (typically the globals of the call site) with
the given name.
For example, you can prevent the compilation of a bunch of regular
expressions until they are actually used::
RES = LazyDict({
'dot': lambda: re.compile('.'),
'all': lambda: re.compile('.*'),
'two': lambda: re.compile('..'),
}, globals(), 'RES')
Parameters
----------
loaders : Mapping of keys to functions with no arguments
A mapping of loader function that performs the actual value
construction upon acces.
ctx : Mapping
Context to replace the LazyDict instance in
with the the fully loaded mapping.
name : str
Name in the context to give the loaded mapping. This *should*
be the name on the LHS of the assignment.
"""
self._loaders = loaders
self._ctx = ctx
self._name = name
self._d = type(loaders)() # make sure to return the same type
def _destruct(self):
if len(self._loaders) == 0:
self._ctx[self._name] = self._d
def __getitem__(self, key):
d = self._d
if key in d:
val = d[key]
else:
# pop will raise a key error for us
loader = self._loaders.pop(key)
d[key] = val = loader()
self._destruct()
return val
def __setitem__(self, key, value):
self._d[key] = value
if key in self._loaders:
del self._loaders[key]
self._destruct()
def __delitem__(self, key):
if key in self._d:
del self._d[key]
else:
del self._loaders[key]
self._destruct()
def __iter__(self):
for item in (set(self._d.keys()) | set(self._loaders.keys())):
yield item
def __len__(self):
return len(self._d) + len(self._loaders)
def lazydict(f):
"""Decorator for constructing lazy dicts from a function."""
return LazyDict(f, f.__globals__, f.__name__)
class LazyBool(object):
def __init__(self, load, ctx, name):
"""Boolean like object that lazily computes it boolean value when it is
first asked. Once loaded, this result will replace itself
in the provided context (typically the globals of the call site) with
the given name.
For example, you can prevent the complex boolean until it is actually
used::
ALIVE = LazyDict(lambda: not DEAD, globals(), 'ALIVE')
Parameters
----------
load : function with no arguments
A loader function that performs the actual boolean evaluation.
ctx : Mapping
Context to replace the LazyBool instance in
with the the fully loaded mapping.
name : str
Name in the context to give the loaded mapping. This *should*
be the name on the LHS of the assignment.
"""
self._load = load
self._ctx = ctx
self._name = name
self._result = None
def __bool__(self):
if self._result is None:
res = self._ctx[self._name] = self._result = self._load()
else:
res = self._result
return res
def lazybool(f):
"""Decorator for constructing lazy booleans from a function."""
return LazyBool(f, f.__globals__, f.__name__)
#
# Background module loaders
#
class BackgroundModuleProxy(types.ModuleType):
"""Proxy object for modules loaded in the background that block attribute
access until the module is loaded..
"""
def __init__(self, modname):
self.__dct__ = {
'loaded': False,
'modname': modname,
}
def __getattribute__(self, name):
passthrough = frozenset({'__dct__', '__class__', '__spec__'})
if name in passthrough:
return super(BackgroundModuleProxy, self).__getattribute__(name)
dct = self.__dct__
modname = dct['modname']
if dct['loaded']:
mod = sys.modules[modname]
else:
delay_types = (BackgroundModuleProxy, type(None))
while isinstance(sys.modules.get(modname, None), delay_types):
time.sleep(0.001)
mod = sys.modules[modname]
dct['loaded'] = True
# some modules may do construction after import, give them a second
stall = 0
while not hasattr(mod, name) and stall < 1000:
stall += 1
time.sleep(0.001)
return getattr(mod, name)
class BackgroundModuleLoader(threading.Thread):
"""Thread to load modules in the background."""
def __init__(self, name, package, replacements, *args, **kwargs):
super(BackgroundModuleLoader, self).__init__(*args, **kwargs)
self.daemon = True
self.name = name
self.package = package
self.replacements = replacements
self.start()
def run(self):
# wait for other modules to stop being imported
# We assume that module loading is finished when sys.modules doesn't
# get longer in 5 consecutive 1ms waiting steps
counter = 0
last = -1
while counter < 5:
new = len(sys.modules)
if new == last:
counter += 1
else:
last = new
counter = 0
time.sleep(0.001)
# now import module properly
modname = resolve_name(self.name, self.package)
if isinstance(sys.modules[modname], BackgroundModuleProxy):
del sys.modules[modname]
mod = importlib.import_module(self.name, package=self.package)
for targname, varname in self.replacements.items():
if targname in sys.modules:
targmod = sys.modules[targname]
setattr(targmod, varname, mod)
def load_module_in_background(name, package=None, debug='DEBUG', env=None,
replacements=None):
"""Entry point for loading modules in background thread.
Parameters
----------
name : str
Module name to load in background thread.
package : str or None, optional
Package name, has the same meaning as in importlib.import_module().
debug : str, optional
Debugging symbol name to look up in the environment.
env : Mapping or None, optional
Environment this will default to __xonsh_env__, if available, and
os.environ otherwise.
replacements : Mapping or None, optional
Dictionary mapping fully qualified module names (eg foo.bar.baz) that
import the lazily loaded moudle, with the variable name in that
module. For example, suppose that foo.bar imports module a as b,
this dict is then {'foo.bar': 'b'}.
Returns
-------
module : ModuleType
This is either the original module that is found in sys.modules or
a proxy module that will block until delay attribute access until the
module is fully loaded.
"""
modname = resolve_name(name, package)
if modname in sys.modules:
return sys.modules[modname]
if env is None:
try:
import builtins
env = getattr(builtins, '__xonsh_env__', os.environ)
except:
return os.environ
if env.get(debug, None):
mod = importlib.import_module(name, package=package)
return mod
proxy = sys.modules[modname] = BackgroundModuleProxy(modname)
BackgroundModuleLoader(name, package, replacements or {})
return proxy