Wrong cache timing for long-running functions
gitanat opened this issue · 1 comments
I'm not sure if this actually a bug, or intended behaviour, but cached_property_with_ttl
doesn't consider the time that the cached function takes to execute, only the time between attribute accesses.
This means that, for long-running functions, the cache misses when it shouldn't (my use case is caching the result of HTTP requests).
Here's code that demonstrates the issue
from cached_property import cached_property_with_ttl
import time
class C(object):
@cached_property_with_ttl(ttl=1)
def value(self):
print("computing")
time.sleep(2)
c = C()
c.value
c.value
The function is called twice, despite the fact that the second attribute access happens "immediately"
This can be solved with the following patch
if not ttl_expired:
return value
+ now = time()
value = self.func(obj)
obj_dict[name] = (value, now)
return value
from cached_property import cached_property_with_ttl
import time
class C(object):
@cached_property_with_ttl(ttl=1)
def value(self):
print("computing")
time.sleep(2)
Add this import for the 'time' function
from time import time as current_time
c = C()
c.value
c.value