gpt4 book ai didi

Python 缓存 : TypeError: unhashable type: 'dict'

转载 作者:行者123 更新时间:2023-12-05 02:04:11 25 4
gpt4 key购买 nike

我正在尝试用 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

要解决这个问题,您应该从 argskwargs 的组合中生成一个可散列的键。例如,您可以使用(假设 argskwargs 的所有值都是可哈希的)

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com