【问题标题】:Clear all lru_cache in Python在 Python 中清除所有 lru_cache
【发布时间】:2016-10-26 23:32:39
【问题描述】:

我在 python 中有具有 lru_cache 缓存的函数,例如

 @lru_cache(maxsize=None)
 def my_function():
    ...

虽然我可以单独清除缓存,例如my_function.cache_clear() 有没有办法一次清除每个函数的缓存? [我在想也许有一种方法可以返回所有加载到内存中的函数名,然后循环遍历它们以清除每个函数的缓存]。

我特别希望将其作为后备的一部分来实现,以应对我机器上 90% 的内存被使用的情况。

【问题讨论】:

  • 是的,装饰函数现在有方法my_function.cache_clear()。您还可以通过my_function.cache_info() 获取统计信息。见lru_cache
  • @AChampion - 当然,知道这两者,但问题是有没有一种方法可以将这些方法应用于每个修饰函数(即清除 all lru_cache 的)。
  • 不,没有简单的方法可以清除所有修饰函数缓存,它们都是独立的。您可以为所有这些函数创建一个注册表,然后遍历它们以清除它们。

标签: python caching lru


【解决方案1】:

也许有一种方法可以返回所有函数 名称加载到内存中,然后遍历它们清除缓存 从每个

是的,这也是可能的:

import functools
import gc

gc.collect()
wrappers = [
    a for a in gc.get_objects() 
    if isinstance(a, functools._lru_cache_wrapper)]

for wrapper in wrappers:
    wrapper.cache_clear()

我特别希望将其作为后备的一部分来实施,因为 比如说我机器上 90% 的内存被使用的情况。

这是您在正常情况下可能不会使用的代码,但对调试很有用。

在我的特殊情况下,我想清除一些 dangling file handles from matplotlib(以便专注于我自己松散的文件句柄),因此无法使用 Alex Hall 的解决方案。

【讨论】:

  • 继承了一个很难测试的代码库,因为它依赖于在测试之间共享状态的 lru_caches。
【解决方案2】:

您可以创建一个修改过的装饰器,它还记录缓存的函数:

cached_functions = []

def clearable_lru_cache(*args, **kwargs):
    def decorator(func):
        func = lru_cache(*args, **kwargs)(func)
        cached_functions.append(func)
        return func

    return decorator

def clear_all_cached_functions():
    for func in cached_functions:
        func.cache_clear()

如果你真的想要你也可以使用猴子补丁来替换原来的装饰器。

测试:

@clearable_lru_cache()
def foo(x):
    print('foo', x)

@clearable_lru_cache()
def bar(x):
    print('bar', x)

for i in [1, 2]:
    for j in [1, 2]:
        print('Calling functions')
        for k in [1, 2, 3]:
            for f in [foo, bar]:
                f(k)
        print('Functions called - if you saw nothing they were cached')
    print('Clearing cache')
    clear_all_cached_functions()

输出:

Calling functions
foo 1
bar 1
foo 2
bar 2
foo 3
bar 3
Functions called - if you saw nothing they were cached
Calling functions
Functions called - if you saw nothing they were cached
Clearing cache
Calling functions
foo 1
bar 1
foo 2
bar 2
foo 3
bar 3
Functions called - if you saw nothing they were cached
Calling functions
Functions called - if you saw nothing they were cached
Clearing cache

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2016-03-14
    • 2017-10-11
    • 2017-12-30
    相关资源
    最近更新 更多