How to create a time-aware Python cache without extra dependencies?

One of native methods supporting caching in Python is @lru_cache decorator. It caches method execution by parameters and it's the key of the solution proposed in this tip.

Since the cache is parameter-based, to make it time-aware we need simply to add another parameter being the interval of cache refresh. Let's start with the tested function:

import time
from functools import lru_cache

generation_calls = []

@lru_cache()
def cached_method(param, refresh_time):
    print('Generation triggered')
    generation_calls.append(1)

Let's say now that we want to cache a call for 5 seconds. To do that, we can parameterize refresh_time on that interval, like that:

cached_method("a", round(time.time() / 5))
cached_method("a", round(time.time() / 5))
cached_method("b", round(time.time() / 5))
assert len(generation_calls) == 2

time.sleep(5)
cached_method("a", round(time.time() / 5))
assert len(generation_calls) == 3

The solution works and maybe will fit into your need. You should remember that it's not the most optimal though. Every call with different refresh interval will be added to the cache whereas in a normal TTL-based cache, we should retrieve a single cached entry for every parameters combination. So concretely it means that with the solution proposed here we store 3 entries in cache (2 for "a" and 1 for "b") and with a classical approach we would have only 2 (1 for "a" and 1 for "b").