我正在尝试用 Python 实现缓存功能。代码如下所示:
def memoize(func):
"""Store the results of the decorated function for fast lookup
"""
# Store results in a dict that maps arguments to results
cache = {}
def wrapper(*args, **kwargs):
# If these arguments haven't been seen before, call func() and store the result.
if (args, kwargs) not in cache:
cache[(args, kwargs)] = func(*args, **kwargs)
return cache[(args, kwargs)]
return wrapper
@memoize
def add(a, b):
print('Sleeping...')
return a + b
add(1, 2)
当我运行代码时,我得到 TypeError: unhashable type: 'dict'
。
怎么了?
最佳答案
dict
的键必须是可散列的。您提供了一个不可散列的 key (args,kwargs)
因为 kwargs
是一个不可散列的 dict
。
要解决这个问题,您应该从 args
和 kwargs
的组合中生成一个可散列的键。例如,您可以使用(假设 args
和 kwargs
的所有值都是可哈希的)
key = ( args , tuple((kwargs.items())))
def memoize(func):
"""Store the results of the decorated function for fast lookup
"""
# Store results in a dict that maps arguments to results
cache = {}
def wrapper(*args, **kwargs):
# If these arguments haven't been seen before, call func() and store the result.
key = ( args , tuple((kwargs.items())))
if key not in cache:
cache[key] = cc = func(*args, **kwargs)
return cc
return cache[key]
return wrapper
@memoize
def add(a, b):
print('Sleeping...')
return a + b
print(add(1, 2))
关于Python 缓存 : TypeError: unhashable type: 'dict' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64641718/