This is the code:
import numpy as np
from functools import cache, wraps
def np_cache(function):
@cache
def cached_wrapper(*args, **kwargs):
args = [np.array(a) if isinstance(a, tuple) else a for a in args]
kwargs = {
k: np.array(v) if isinstance(v, tuple) else v for k, v in kwargs.items()
}
return function(*args, **kwargs)
@wraps(function)
def wrapper(*args, **kwargs):
args = [tuple(a) if isinstance(a, np.ndarray) else a for a in args]
kwargs = {
k: tuple(v) if isinstance(v, np.ndarray) else v for k, v in kwargs.items()
}
return cached_wrapper(*args, **kwargs)
wrapper.cache_info = cached_wrapper.cache_info
wrapper.cache_clear = cached_wrapper.cache_clear
return wrapper
x = np.array([[1,2],[3,4]])
y = np.array([2, 4])
@np_cache
def test2(x,shown = False):
if shown:
print(x)
return x
test2(y,True)
test2(x)
I get this error:
(array([[1, 2],
[3, 4]]), True)
[(array([1, 2]), array([3, 4])), True]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-79-73b6dd94e3a9> in <cell line: 42>()
40
41 #test2(y,True)
---> 42 test2(x, True)
43
44
<ipython-input-79-73b6dd94e3a9> in wrapper(*args, **kwargs)
23 k: tuple(v) if isinstance(v, np.ndarray) else v for k, v in kwargs.items()
24 }
---> 25 return cached_wrapper(*args, **kwargs)
26
27 wrapper.cache_info = cached_wrapper.cache_info
TypeError: unhashable type: 'numpy.ndarray'
As you can see, The array is correctly converted to a tuple of arrays, so I don’t know why it is not working.
I think the key is making some modifications in the wrapper, but I am not sure how.
Thanks in advance
New contributor
Offel21 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.