LRU Cache with Expiry in Python

3 Dec 2024

A decorator which adds expiry to the lru_cache function

from functools import wraps, lru_cache
from time import time

def lru_cache_with_expiry(max_age: int, maxsize:int =128, typed:bool =False):  
"""Least-recently-used cache decorator with time-based cache invalidation.  
  
Args:  
max_age: Time to live for cached results (in seconds).  
maxsize: Maximum cache size (see `functools.lru_cache`).  
typed: Cache on distinct input types (see `functools.lru_cache`).  
"""  
  
	def _decorator(fn):  
		@lru_cache(maxsize=maxsize, typed=typed)  
		def _new(*args, __time_salt, **kwargs):  
			return fn(*args, **kwargs)  
  
		@wraps(fn)  
		def _wrapped(*args, **kwargs):  
			return _new(*args, **kwargs, __time_salt=int(time() / max_age))  

		return _wrapped  
  
	return _decorator
	

Tags