【问题标题】:TypeError: unhashable type: 'dict' while applying a decorator functionTypeError: unhashable type: 'dict' 在应用装饰器函数时
【发布时间】:2020-06-06 10:54:53
【问题描述】:

下面的代码定义了decoratordecorated 函数。当我调用修饰函数时,我得到一个 TypeError: unhashable type: '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'

【问题讨论】:

标签: python-3.x function dictionary


【解决方案1】:

当您尝试在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'>

【讨论】:

  • 谢谢@jpf。明白你的建议。它有效。太好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 2020-12-10
  • 1970-01-01
  • 2021-08-31
  • 2016-01-15
  • 1970-01-01
  • 2015-11-24
相关资源
最近更新 更多