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)

2 Answers

1
donkopotamus On

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

1
youknowone On

A solution with ring, valid only in single-threaded program.

import ring

@ring.lru(maxsize=2048)
def fetch_cached_data(query, *args, **kwargs):
    return query

if __name__ == '__main__':
    is_cached = fetch_cached_data.has('query')
    data = fetch_cached_data('query')
    print(is_cached, data)

    is_cached = fetch_cached_data.has('query')
    data = fetch_cached_data('query')
    print(is_cached, data)

Then output is:

False query
True query