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

标签 python python-3.x

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

相关文章:

python - Stripe API : filter for Payout ID when I have destination ID (bank ID)

python - 如何将子流程输出保存为字符串列表以供进一步分析?

python-3.x - Python 请求发布 pdf 响应 406

python - 与多级索引数据帧一起使用时 pd.DataFrame.drop 的意外行为

python - 如何以与使用记事本应用程序打开时相同的格式打印 csv 文件?

python - 在 python 中解包值

python - TypeError : PyQt4. QtCore.QVariantAnimation 表示 C++ 抽象类,无法实例化

mysql - 如何从 SQL 快照访问数据

python - 如何将 Python 脚本链接到 React Native 应用程序

python - Pyparsing 标识符被压入堆栈两次