python - Python中内存中的时间到期字典
问题描述
我只是想知道如何在 Python 中有效地在内存中实现时间过期字典,以便键值对在指定的时间间隔后过期。
解决方案
通常这样做的设计模式不是通过字典,而是通过函数或方法装饰器。字典由缓存在后台管理。
这个答案在Python 3.7中使用了ttl_cache
装饰器。cachetools==3.1.0
它的工作原理很像functools.lru_cache
,但有时间活。至于它的实现逻辑,看它的源码。
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)