Skip to content

Commit ad718a0

Browse files
author
Steve Canny
committed
shr: add lazyproperty decorator
1 parent 1e975b6 commit ad718a0

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

docx/shared.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# encoding: utf-8
2+
3+
"""
4+
Objects shared by docx modules.
5+
"""
6+
7+
from __future__ import absolute_import, print_function, unicode_literals
8+
9+
10+
def lazyproperty(f):
11+
"""
12+
@lazyprop decorator. Decorated method will be called only on first access
13+
to calculate a cached property value. After that, the cached value is
14+
returned.
15+
"""
16+
cache_attr_name = '_%s' % f.__name__ # like '_foobar' for prop 'foobar'
17+
docstring = f.__doc__
18+
19+
def get_prop_value(obj):
20+
try:
21+
return getattr(obj, cache_attr_name)
22+
except AttributeError:
23+
value = f(obj)
24+
setattr(obj, cache_attr_name, value)
25+
return value
26+
27+
return property(get_prop_value, doc=docstring)

0 commit comments

Comments
 (0)