Commit 580d7a6 1 parent 4563139 commit 580d7a6 Copy full SHA for 580d7a6
File tree 1 file changed +25
-10
lines changed
1 file changed +25
-10
lines changed Original file line number Diff line number Diff line change 5
5
Lazily-evaluated property pattern in Python.
6
6
7
7
https://en.wikipedia.org/wiki/Lazy_evaluation
8
- http://stevenloria.com/lazy-evaluated-properties-in-python/
8
+
9
+ References:
10
+ bottle
11
+ https://github.com/bottlepy/bottle/blob/cafc15419cbb4a6cb748e6ecdccf92893bb25ce5/bottle.py#L270
12
+ django
13
+ https://github.com/django/django/blob/ffd18732f3ee9e6f0374aff9ccf350d85187fac2/django/utils/functional.py#L19
14
+ pip
15
+ https://github.com/pypa/pip/blob/cb75cca785629e15efb46c35903827b3eae13481/pip/utils/__init__.py#L821
16
+ pyramimd
17
+ https://github.com/Pylons/pyramid/blob/7909e9503cdfc6f6e84d2c7ace1d3c03ca1d8b73/pyramid/decorator.py#L4
18
+ werkzeug
19
+ https://github.com/pallets/werkzeug/blob/5a2bf35441006d832ab1ed5a31963cbc366c99ac/werkzeug/utils.py#L35
9
20
"""
10
21
11
22
12
- def lazy_property (fn ):
13
- """Decorator that makes a property lazy-evaluated."""
14
- attr_name = '_lazy_' + fn .__name__
23
+ import functools
24
+
25
+
26
+ class lazy_property (object ):
27
+ def __init__ (self , function ):
28
+ self .function = function
29
+ functools .update_wrapper (self , function )
15
30
16
- @ property
17
- def _lazy_property ( self ) :
18
- if not hasattr ( self , attr_name ):
19
- setattr ( self , attr_name , fn ( self ) )
20
- return getattr ( self , attr_name )
21
- return _lazy_property
31
+ def __get__ ( self , obj , type_ ):
32
+ if obj is None :
33
+ return self
34
+ val = self . function ( obj )
35
+ obj . __dict__ [ self . function . __name__ ] = val
36
+ return val
22
37
23
38
24
39
class Person (object ):
You can’t perform that action at this time.
0 commit comments