TypeError:不可散列的类型:应用装饰器函数时为“ dict”

时间:2020-06-06 10:54:53

标签: python-3.x function dictionary

我有以下代码定义了decoratordecorated函数。当我调用修饰的函数时,我得到一个TypeError:不能散列的类型:'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'

1 个答案:

答案 0 :(得分:1)

当您尝试在(args,kwargs)中使用cache[(args,kwargs)]作为键(或键的一部分)时,kwargsdict类型的。 dict类型不能用作字典中的键。实际上,任何可变数据结构都不能用作字典中的键。

一种替代方法是使用tuple(kwargs.items())作为cache字典中密钥的这一部分,然后根据需要转换回字典。只有在kwargs字典中没有引用字典(或其他可变对象)的情况下,才有可能。

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

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

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

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

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