forked from estebistec/python-memoized-property
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemoized_property.py
executable file
·45 lines (35 loc) · 1.07 KB
/
memoized_property.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
# -*- coding: utf-8 -*-
from functools import wraps
import six
def memoized_property(fget):
"""
Return a property attribute for new-style classes that only calls its getter on the first
access. The result is stored and on subsequent accesses is returned, preventing the need to
call the getter any more.
Example::
>>> class C(object):
... load_name_count = 0
... @memoized_property
... def name(self):
... "name's docstring"
... self.load_name_count += 1
... return "the name"
>>> c = C()
>>> c.load_name_count
0
>>> c.name
"the name"
>>> c.load_name_count
1
>>> c.name
"the name"
>>> c.load_name_count
1
"""
attr_name = six.text_type('_{0}').format(fget.__name__)
@wraps(fget)
def fget_memoized(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fget(self))
return getattr(self, attr_name)
return property(fget_memoized)