如何应用 functools.lru_cache 来使用可变参数?
How to apply functools.lru_cache to function with mutable parameters?
我有一个函数,其中一个参数为 numpy.ndarray。它是可变的,所以它不能被 lru_cache.
缓存
有现成的解决方案吗?
可能最简单的方法是记忆一个只接受不可变对象的版本。
假设您的函数接受一个 np.array
,我们假设它是一个一维数组。幸运的是,它很容易被翻译成 tuple
:
import numpy as np
a = np.array([1, 2, 3, 4])
>> tuple(a)
(1, 2, 3, 4)
反之亦然:
>> np.array(tuple(a))
array([1, 2, 3, 4])
所以你得到类似
的东西
# Function called by the rest of your program
array_foo(a) # `a` is an `np.array`
...
return tuple_foo(tuple(a))
然后 memoize 而不是这个函数:
# Internal implementation
@functools.lru_cache
tuple_foo(t) # `t` is a tuple
...
a = np.array(t)
我有一个函数,其中一个参数为 numpy.ndarray。它是可变的,所以它不能被 lru_cache.
缓存有现成的解决方案吗?
可能最简单的方法是记忆一个只接受不可变对象的版本。
假设您的函数接受一个 np.array
,我们假设它是一个一维数组。幸运的是,它很容易被翻译成 tuple
:
import numpy as np
a = np.array([1, 2, 3, 4])
>> tuple(a)
(1, 2, 3, 4)
反之亦然:
>> np.array(tuple(a))
array([1, 2, 3, 4])
所以你得到类似
的东西# Function called by the rest of your program
array_foo(a) # `a` is an `np.array`
...
return tuple_foo(tuple(a))
然后 memoize 而不是这个函数:
# Internal implementation
@functools.lru_cache
tuple_foo(t) # `t` is a tuple
...
a = np.array(t)