forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlazy.py
More file actions
42 lines (32 loc) · 998 Bytes
/
lazy.py
File metadata and controls
42 lines (32 loc) · 998 Bytes
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
class LazyProperty:
def __init__(self, method):
self.method = method
self.method_name = method.__name__
# print(f"function overriden: {self.fget}")
# print(f"function's name: {self.func_name}")
def __get__(self, obj, cls):
if not obj:
return None
value = self.method(obj)
# print(f'value {value}')
setattr(obj, self.method_name, value)
return value
class Test:
def __init__(self):
self.x = 'foo'
self.y = 'bar'
self._resource = None
@LazyProperty
def resource(self):
print(f'initializing self._resource which is: {self._resource}')
self._resource = tuple(range(5)) # expensive
return self._resource
def main():
t = Test()
print(t.x)
print(t.y)
# do more work...
print(t.resource)
print(t.resource)
if __name__ == '__main__':
main()