python - 调用此内存函数会引发 TypeError : unhashable type: 'dict'

标签 python function python-decorators

我有这个代码,当我打印它时,我遇到了这个错误。有人可以告诉我如何解决这个问题吗?

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 wraper(*args, **kwargs):
        if (args, kwargs) not in cache:
            cache[(args, kwargs)] = func(*args, **kwargs)
        return cache[(args, kwargs)]
    return wraper

@memoize 
def slow_function(a, b):
    print('Sleeping...')
    time.sleep(5)
    return a + b

print(slow_function(3,4))

错误:类型错误:不可散列的类型:'dict'

最佳答案

这里有一个简单的方法来避免该问题,即将 kwargs 字典转换为字符串(以及 args),以生成可接受的字典键。

我从 Memoize 得到了这个想法Python Decorator Library 部分.

import time

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):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = func(*args, **kwargs)
        return cache[key]
    return wrapper

@memoize
def slow_function(a, b):
    print('Sleeping...')
    time.sleep(5)
    return a + b

print(slow_function(3,4))

关于python - 调用此内存函数会引发 TypeError : unhashable type: 'dict' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64689319/

相关文章:

用模拟函数替换真实返回值和函数实现的 Pythonic 方法

python - Py2Exe + FTDI 驱动程序

python - 如何比较两列的值并根据比较对值重新排序

python - 无法安装 RAY

python - Django loaddata UNIQUE 约束失败

python - 如何使用基于类的装饰器的缩写符号向 __call__ 提供 *args 和 **kwargs?

function - YUI3、模块、命名空间、调用函数

Javascript - 带有对象的函数

python - 非递归函数 follow_me(d, s) 其中 d 是字典,s 是字符串

python - 如何将实例变量传递给类定义内的装饰器?