类型错误:不可哈希类型:应用装饰器函数时'dict'



我有以下代码定义decoratordecorated函数。当我调用装饰函数时,我得到一个类型错误:不可哈希类型:"dict"。问题出在哪里?欣赏输入。我在桌面上使用jupyter笔记本。

def memorize(func):
""" Store the results of a decorated function for last lookup"""
#store results in a dictionary that maps arguments to results
cache = {}
# define the wrappaer function that the decorator returns
def wrapper(*args,**kwargs):
#if these arguments haven't been seen before
if (args, kwargs) not in cache:
cache[(args,kwargs)] = func(*args, **kwargs)
return cache[(args, kwargs)]
return wrapper
@memorize
def slow_function(a,b):
print('Sleeping.....')
time.sleep(5)
return a+b
slow_function(3,7)
TypeError: unhashable type: 'dict'

当您尝试在cache[(args,kwargs)]中使用(args,kwargs)作为键(或键的一部分(时,kwargs属于dict类型。dict类型不能用作字典中的键。事实上,没有可变的数据结构可以用作字典中的键。

另一种方法是使用tuple(kwargs.items())作为cache字典中键的这一部分,并根据需要转换回字典。仅当kwargs字典中没有引用字典(或其他可变对象(时,才有可能执行此操作。

我没有亲自使用它,但frozendict似乎将字典转换为不可变类型。

下面是一个示例,说明了传入位置参数和关键字参数的类型。

def f(*args,**kwargs):
print(type(args),type(kwargs))

f(1,2,3)的输出为

<class 'tuple'> <class 'dict'>

最新更新