Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
""" # noqa
- def __init__(self, ttl=300):
- self.ttl = ttl
-
- def __call__(self, func, doc=None):
+ def __init__(self, ttl=None):
+ ttl_or_func = ttl
+ self.ttl = None
+ if callable(ttl_or_func):
+ self.prepare_func(ttl_or_func)
+ else:
+ self.ttl = ttl_or_func
+
+ def prepare_func(self, func, doc=None):
+ '''Prepare to cache object method.'''
self.func = func
self.__doc__ = doc or func.__doc__
self.__name__ = func.__name__
self.__module__ = func.__module__
+ def __call__(self, func, doc=None):
+ self.prepare_func(func, doc)
return self
def __get__(self, obj, cls):
now = time()
try:
value, last_update = obj._cache[self.__name__]
- if self.ttl > 0 and now - last_update > self.ttl:
+ if self.ttl and self.ttl > 0 and now - last_update > self.ttl:
raise AttributeError
except (KeyError, AttributeError):
value = self.func(obj)
self.total1 += 1
return self.total1
- @cached_property()
+ @cached_property
def add_cached(self):
self.total2 += 1
return self.total2
self.assertEqual(c.add_cached, 1)
self.assertEqual(c.add_cached, 1)
+ # Cannot expire the cache.
+ with freeze_time("9999-01-01"):
+ self.assertEqual(c.add_cached, 1)
+
# It's customary for descriptors to return themselves if accessed
# though the class, rather than through an instance.
self.assertTrue(isinstance(Check.add_cached, cached_property))
def __init__(self):
self.total = 0
- @cached_property()
+ @cached_property
def add_cached(self):
self.total += 1
return self.total
def __init__(self):
self.total = None
- @cached_property()
+ @cached_property
def add_cached(self):
return self.total
self.total = 0
self.lock = Lock()
- @cached_property()
+ @cached_property
def add_cached(self):
sleep(1)
# Need to guard this since += isn't atomic.
class TestCachedPropertyWithTTL(unittest.TestCase):
+
def test_ttl_expiry(self):
class Check(object):
self.total1 += 1
return self.total1
- @threaded_cached_property()
+ @threaded_cached_property
def add_cached(self):
self.total2 += 1
return self.total2
def __init__(self):
self.total = 0
- @threaded_cached_property()
+ @threaded_cached_property
def add_cached(self):
self.total += 1
return self.total
def __init__(self):
self.total = None
- @threaded_cached_property()
+ @threaded_cached_property
def add_cached(self):
return self.total
self.total = 0
self.lock = Lock()
- @threaded_cached_property()
+ @threaded_cached_property
def add_cached(self):
sleep(1)
# Need to guard this since += isn't atomic.