在 Python 中只弹出 lru_cache 中的一项

Pop only one item from lru_cache in Python

我正在使用 functools 中的 lru_cache 装饰器,我需要使其中的 只有一个 项无效,其余的保持不变。 documentation states that the __wrapped__ attribute is there for rewrapping the function with a different cache. I checked the source 也是,但我不知道如何使用它。它说

Users should only access the lru_cache through its public API: cache_info, cache_clear, and f.__wrapped__ The internals of the lru_cache are encapsulated for thread safety and to allow the implementation to change

是否可以(安全地)从 lru_cache 中删除一项,或者我应该编写自己的缓存功能?

lru_cache in Python 3.9 甚至没有在 Python 中暴露任何东西,除了 public API - 其中包括一个 cache_clear 调用这将使整个缓存失效,而不仅仅是一个键。

因此,与其寻找解决方法,不如自己编写可以完全控制的缓存。

__wrapped__ 属性本身只是原始功能,根本没有 lru_cache 功能。实际上,您可以利用它 完全绕过 一次调用的缓存 - 该函数将 运行 与重复参数作为普通 Python 函数- 但它的响应根本不会被缓存。

也就是说,对于


from functools import lru_cache

@lru_cache
def test(a):
   print("side effect")

test(23)
test.__wrapped__(23)

两次调用的函数体都是 运行。