我只是想知道如何在Python中有效地实现内存中的时间到期字典,使得键值对在指定的时间间隔后到期。
通常这样做的设计模式不是通过字典,而是通过函数或方法装饰器。字典由缓存在后台管理。
这个答案使用ttl_cache
中的cachetools==3.1.0
装饰器和Python 3.7。它有点像functools.lru_cache
,但有一个time to live。至于它的实现逻辑,考虑它的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
如果你坚持使用字典,cachetools
也有TTLCache
。
import cachetools
ttl_cache = cachetools.TTLCache(maxsize=128, ttl=10 * 60)