Show More
@@ -1,27 +1,28 | |||
|
1 | 1 | class LazyProperty(object): |
|
2 | 2 | """ |
|
3 | 3 | Decorator for easier creation of ``property`` from potentially expensive to |
|
4 | 4 | calculate attribute of the class. |
|
5 | 5 | |
|
6 | 6 | Usage:: |
|
7 | 7 | |
|
8 | 8 | class Foo(object): |
|
9 | 9 | @LazyProperty |
|
10 | 10 | def bar(self): |
|
11 | 11 | print 'Calculating self._bar' |
|
12 | 12 | return 42 |
|
13 | 13 | |
|
14 | 14 | Taken from http://blog.pythonisito.com/2008/08/lazy-descriptors.html and |
|
15 | 15 | used widely. |
|
16 | 16 | """ |
|
17 | 17 | |
|
18 | 18 | def __init__(self, func): |
|
19 | 19 | self._func = func |
|
20 | self.__module__ = func.__module__ | |
|
20 | 21 | self.__name__ = func.__name__ |
|
21 | 22 | self.__doc__ = func.__doc__ |
|
22 | 23 | |
|
23 | 24 | def __get__(self, obj, klass=None): |
|
24 | 25 | if obj is None: |
|
25 |
return |
|
|
26 | return self | |
|
26 | 27 | result = obj.__dict__[self.__name__] = self._func(obj) |
|
27 | 28 | return result |
General Comments 0
You need to be logged in to leave comments.
Login now