Python中内存中的时间到期字典

kir*_*bak 4 python caching dictionary ttl

我只是想知道如何在 Python 的内存中有效地实现一个时间到期字典,以便键值对在指定的时间间隔后到期。

Acu*_*nus 6

通常执行此操作的设计模式不是通过字典,而是通过函数或方法装饰器。字典由缓存在后台管理。

这个答案ttl_cachecachetools==3.1.0Python 3.7 中使用了装饰器。它的工作原理很像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
Run Code Online (Sandbox Code Playgroud)

但是,如果您坚持使用字典,cachetools也有TTLCache.

import cachetools

ttl_cache = cachetools.TTLCache(maxsize=128, ttl=10 * 60)
Run Code Online (Sandbox Code Playgroud)