【问题标题】:Access lru_cache's cache访问 lru_cache 的缓存
【发布时间】:2018-01-02 09:19:46
【问题描述】:

一般问题:如何访问函数闭包中的变量?

具体问题:如何从用functools.lru_cache() 包装的python 函数访问原始cache?

如果我记住一个函数(示例取自docs)...

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

这里是 cache 的定义位置:https://github.com/python/cpython/blob/f0851910eb8e711bf8f22165cb0df33bb27b09d6/Lib/functools.py#L491

当fib() 被记忆时,lru_cache 将cache_info() 和cache_clear() 函数添加到包装器中。 cache_clear() 可以访问cache,我可以访问cache_clear(),所以我可以用它直接访问cache 吗?

【问题讨论】:

  • 这似乎不是你应该能够做的事情,它是该函数中的一个局部变量。你唯一的希望就是反思。你为什么要这样做?
  • 为什么?因为我可以。真的为什么?我想在开发过程中在重启之间保留缓存。
  • 你读过this吗?
  • 虽然您可以做到这一点,但在实现细节上有很多脆弱的地方,最好只使用您自己的 memoization 实现。

标签: python python-3.x caching scope


【解决方案1】:

您可以通过Shay Palachy 使用cachier。你可以告诉它缓存到pickle file。

或者,看看Andrew Barnert开发的persistent_lru_cache。

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2017-02-21
    • 2021-03-28
    • 2021-12-17
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多