-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy.py
52 lines (41 loc) · 988 Bytes
/
lazy.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
class Uncomputed:
"""
A singleton to denote uncomputed values.
"""
pass
class lazy(object):
"""
Doubles up as a descriptor for lazy properties and a decorator for lazy functions.
Example usage:
# === as a descriptor:
class A(...):
foo = lazy(lambda self: self._foo())
def foo(self):
...
# example:
a = A()
print a.foo # computed
print a.foo # looked up
# === as a decorator:
@lazy
def foo():
...
print foo() # computed
print foo() # looked up
"""
def __init__(self, thunk):
self.thunk = thunk
self.cache = {}
self.value = Uncomputed
def __get__(self, instance, owner):
if self.cache.get(instance, Uncomputed) == Uncomputed:
self.cache[instance] = self.thunk(instance)
return self.cache[instance]
def __set__(self, instance, value):
self.cache[instance] = value
def __delete__(self, instance):
pass
def __call__(self):
if self.value == Uncomputed:
self.value = self.thunk()
return self.value