I have a simple implementation using the wrapper lru_cache around a function that fetches data from a remote database. I want to be able to tell if the result might be "stale" (i.e., it was fetched from the cache vs from the database). How can I figure that out?
Code is simple, just:
@lru_cache(maxsize=2048)
def fetch_cached_data(query, *args, **kwargs):
return fetch_data(query, *args, **kwargs)
A poor solution, valid only in a single-threaded program, could be to monitor the cache_info
of the function to see if the statistics are changing:
hits = f.cache_info().hits
result = f(some_arg)
if f.cache_info().hits > hits:
# this result was retrieved from cache
...
A better solution might be to think more about what you consider stale ... all the values have ultimately come from the database ... what makes one that you queried in a past function call stale ... the time since it was last queried, a version stamp on the rows returned etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With