构建具有生存时间的单元素缓存非常简单:_last_result_time = None
_last_result_value = None
def result(val):
global _last_result_time
global _last_result_value
now = datetime.datetime.now()
if not _last_result_time or now - _last_result_time > datetime.timedelta(hours=1):
_last_result_value =
_last_result_time = now
return _last_result_value
如果你想把它概括为一个装饰师,这并不难:
^{pr2}$
如果您希望它处理不同的参数,为每个参数存储生存时间:def cache(ttl=datetime.timedelta(hours=1)):
def wrap(func):
cache = {}
@functools.wraps(func)
def wrapped(*args, **kw):
now = datetime.datetime.now()
# see lru_cache for fancier alternatives
key = tuple(args), frozenset(kw.items())
if key not in cache or now - cache[key][0] > ttl:
value = func(*args, **kw)
cache[key] = (now, value)
return cache[key][1]
return wrapped
return wrap
当然,您可以通过键添加特性来给它一个最大大小,并按存储时间或LRU或其他任何你想要的方式逐出,将缓存统计信息作为修饰函数的属性公开,等等。stdlib中的^{}的实现应该有助于向您展示如何做大多数更棘手的事情(因为它几乎完成了所有这些)。在