如何使用 @functools.lru_cache 装饰器绕过函数

Jos*_*hua 6 caching python-3.x

希望你一切顺利!

我正在使用一个利用 functools 库的 lru_cache 的函数。例如:

@functools.lru_cache(maxsize=pow(2,13))
def get_id(word):
    # retrieving id, using cache if possible
Run Code Online (Sandbox Code Playgroud)

在某些情况下,我想绕过缓存,从而直接从源获取 ID,但我不想创建两个运行完全相同的代码的独立函数(一个有缓存,另一个没有)。阅读 docs.python 上 functools 的文档我了解到可以绕过缓存:

原始的底层函数可以通过wrapped 属性访问。这对于内省、绕过缓存或使用不同的缓存重新包装函数非常有用。

我尝试使用包装函数来执行此操作,但由于内部函数仅在外部函数运行时存在,因此每次调用时都会重置缓存。

我将不胜感激任何有关此事的帮助。

hir*_*ist 5

文档告诉您的是,您可以通过这种方式直接访问包装的函数(绕过缓存):

get_id.__wrapped__(word="hello")
Run Code Online (Sandbox Code Playgroud)

您可以添加一个带有标志的附加层:

from functools import lru_cache

@lru_cache(maxsize=pow(2, 13))
def get_cached(word):
    return get_raw(word)

def get_raw(word):
    # your logic goes here...
    pass

def get_id(word, cached=True):
    if cached:
        return get_cached(word)
    else:
        return get_raw(word)
Run Code Online (Sandbox Code Playgroud)