小编Max*_*Max的帖子

当函数返回 None 时,使内置 lru_cache 跳过缓存

这是一个简化的函数,我试图为其添加一个lru_cachefor -

from functools import lru_cache, wraps

@lru_cache(maxsize=1000)
def validate_token(token):
    if token % 3:
        return None
    return True

for x in range(1000):
    validate_token(x)

print(validate_token.cache_info())
Run Code Online (Sandbox Code Playgroud)

输出 -

CacheInfo(hits=0, misses=1000, maxsize=1000, currsize=1000)
Run Code Online (Sandbox Code Playgroud)

正如我们所看到的,它也会缓存args返回returnedNone。在上面的示例中,我希望cache_size为 334,我们返回非 None 值。就我而言,我的函数有很大的编号。如果之前的值为 ,则ofargs可能会返回不同的值None所以我想避免缓存None

我想避免重新发明轮子并lru_cache从头开始实施。有什么好的方法可以做到这一点吗?

以下是我的一些尝试 -

1.尝试实现自己的缓存(这里不是lru)-

from functools import wraps 

# global cache object
MY_CACHE = {}

def get_func_hash(func):
    # generates unique key for a function. TODO: …
Run Code Online (Sandbox Code Playgroud)

python lru python-3.x python-decorators

7
推荐指数
2
解决办法
2662
查看次数

标签 统计

lru ×1

python ×1

python-3.x ×1

python-decorators ×1