I was just wondering how one might efficiently implement a time expiry dictionary in memory in Python such that key-value pairs expire after a specified time interval.
I was just wondering how one might efficiently implement a time expiry dictionary in memory in Python such that key-value pairs expire after a specified time interval.
The design pattern to typically do this is not via a dictionary, but via a function or method decorator. The dictionary is managed behind the scenes by the cache.
This answer uses the ttl_cache decorator in cachetools==3.1.0 with Python 3.7. It works a lot like functools.lru_cache, but with a time to live. As for its implementation logic, consider its source code.
import cachetools.func
@cachetools.func.ttl_cache(maxsize=128, ttl=10 * 60)
def example_function(key):
return get_expensively_computed_value(key)
class ExampleClass:
EXP = 2
@classmethod
@cachetools.func.ttl_cache()
def example_classmethod(cls, i):
return i**cls.EXP
@staticmethod
@cachetools.func.ttl_cache()
def example_staticmethod(i):
return i**3
If however you insist on using a dictionary, cachetools also has TTLCache.
import cachetools
ttl_cache = cachetools.TTLCache(maxsize=128, ttl=10 * 60)