Memoize with a Time-to-Live

medium
Unit 13 · Decorators & Classes0/3 to milestone

Calling an LLM or API with the same input twice is wasteful, but caching forever serves stale results. A TTL cache remembers results for a limited time.

Implement a decorator factory ttl_cache(seconds, clock=time.monotonic):

  • Cache results keyed by the call's positional and keyword arguments (keyword order shouldn't matter).
  • A cached value is reused while clock() - stored_at < seconds. After that, call the function again and refresh the entry.
  • Exceptions aren't cached.
  • The wrapped function gets cache_clear() (empties the cache) and cache_info(), returning a dict {"hits": h, "misses": m, "size": n}.
  • Preserve the function's name with functools.wraps.
#decorators#caching#closures2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Memoize with a Time-to-Live · TechGradify