如何应用functools.lru_cache来使用可变参数?

iur*_*adz 9 python memoization

我有一个函数,其中一个参数为numpy.ndarray.它是可变的,所以它不能被lru_cache缓存.

有没有现成的解决方案?

Ami*_*ory 6

可能最简单的方法是记住只接受不可变对象的版本.

假设你的函数需要一个np.array,我们假设它是一个1d数组.幸运的是,它很容易翻译成tuple:

import numpy as np

a = np.array([1, 2, 3, 4])
>> tuple(a)
(1, 2, 3, 4)
Run Code Online (Sandbox Code Playgroud)

反之亦然:

>> np.array(tuple(a))
array([1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)

所以你得到类似的东西

# Function called by the rest of your program
array_foo(a) # `a` is an `np.array`
    ...
    return tuple_foo(tuple(a))
Run Code Online (Sandbox Code Playgroud)

然后记住这个功能:

# Internal implementation
@functools.lru_cache
tuple_foo(t) # `t` is a tuple
    ...
    a = np.array(t)
Run Code Online (Sandbox Code Playgroud)