I'm writing a memoize decorator but I get a unhashable type 'dict' error when trying it on a simple example. Here is my code:
def memoize(func):
"""Store the results of the decorated function for fast lookup
"""
# Store results in a dict that maps arguments to results
cache = {}
# Define the wrapper function to return
def wrapper(*args, **kwargs):
# If these arguments haven't been seen before,
if (args, kwargs) not in cache:
# Call func() and store the result.
cache[(args, kwargs)] = func(*args, **kwargs)
return cache[(args, kwargs)]
return wrapper
And here is a simple function created to test my decorator:
import time
@memoize
def slow_func(a, b):
print("Sleeping...")
time.sleep(5)
return a+ b
slow_func(2, 7)
I end up with this error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17888/3627587563.py in <module>
----> 1 slow_func(2, 7)
~\AppData\Local\Temp/ipykernel_17888/52581778.py in wrapper(*args, **kwargs)
7 def wrapper(*args, **kwargs):
8 # If these arguments haven't been seen before,
----> 9 if (args, kwargs) not in cache:
10 # Call func() and store the result.
11 cache[(args, kwargs)] = func(*args, **kwargs)
TypeError: unhashable type: 'dict'
I tested just in case if my Python was working properly with:
(2, 3) not in {} which resulted in the correct output True.
Any help would be appreciated!