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

问题描述 投票:1回答:1

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

python dictionary caching ttl
1个回答
0
投票

通常这样做的设计模式不是通过字典,而是通过函数或方法装饰器。字典由缓存在后台管理。

这个答案使用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)
© www.soinside.com 2019 - 2024. All rights reserved.