Skip to content

Commit cdbf34b

Browse files
committed
-
1 parent 8a027e5 commit cdbf34b

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

python_toolbox/caching/cached_property.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,14 @@ def _get_personality(self):
2727
return 'Nice person'
2828
2929
personality = CachedProperty(_get_personality)
30-
30+
31+
You can also put in a value as the first argument if you'd like to have it
32+
returned instead of using a getter. (It can be a totally static value like
33+
`0`). If this value happens to be a callable but you'd still like it to be
34+
used as a static value, use `force_value_not_getter=True`.
3135
'''
32-
def __init__(self, getter_or_value, doc=None, name=None):
36+
def __init__(self, getter_or_value, doc=None, name=None,
37+
force_value_not_getter=False):
3338
'''
3439
Construct the cached property.
3540
@@ -41,8 +46,10 @@ def __init__(self, getter_or_value, doc=None, name=None):
4146
class; this will save a bit of processing later.
4247
'''
4348
misc_tools.OwnNameDiscoveringDescriptor.__init__(self, name=name)
44-
self.getter = getter_or_value if callable(getter_or_value) \
45-
else lambda thing: getter_or_value
49+
if callable(getter_or_value) and not force_value_not_getter:
50+
self.getter = getter_or_value
51+
else:
52+
self.getter = lambda thing: getter_or_value
4653
self.__doc__ = doc or getattr(self.getter, '__doc__', None)
4754

4855

test_python_toolbox/test_caching/test_cached_property.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,4 +177,12 @@ def my_method(self, x, y=3):
177177
assert a.my_method(y=7, x=8) == (8, 7, 2)
178178
with a.reentrant_context_manager:
179179
assert a.my_method(y=7, x=8) == (8, 7, 3)
180-
180+
181+
def test_force_value_not_getter():
182+
class A(object):
183+
personality = CachedProperty(counting_func,
184+
force_value_not_getter=True)
185+
186+
a = A()
187+
assert a.personality == counting_func == a.personality == counting_func
188+

0 commit comments

Comments
 (0)