python Cachetools 项目可以有不同的 ttl 吗?

Car*_*los 3 python caching pandas

我用来@cachetools.func.ttl_cache(maxsize=3, ttl=3600, timer=time.time, typed=False)缓存不同的数据帧。被包装的函数本身并不构建 DF,但给定参数会调用正确的函数。

鉴于我想修改项目 ttl(生存时间),根据参数,DF 的构建可能会很耗时或很快。因此,第 1 项的 ttl=3600,而第 2 项的 ttl=10800。

支持该功能吗?使用全局变量或任何其他方式?文档

小智 5

威尔很可能是正确的,但万一你想尝试,我认为子类 TTLCache 并覆盖一个函数应该可以工作:

from cachetools import Cache, TTLCache

cache = TTLItemCache(maxsize=2, ttl=100)
# ttl=100
cache.__setitem__('key1', 'val1')
# ttl=200
cache.__setitem__('key2', 'val2', ttl=200)

class TTLItemCache(TTLCache):
    def __setitem__(self, key, value, cache_setitem=Cache.__setitem__, ttl=None):
        super(TTLItemCache, self).__setitem__(key, value)
        if ttl:
            link = self._TTLCache__links.get(key, None)
            if link:
                link.expire += ttl - self.ttl
Run Code Online (Sandbox Code Playgroud)