首页 > 解决方案 > 调用这个记忆函数会引发 TypeError: unhashable type: 'dict'

问题描述

我有这个代码,当我打印出来时出现这个错误,有人可以告诉我如何解决这个问题吗?

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))

错误:
TypeError: unhashable type: 'dict'

标签: pythonfunctionpython-decorators

解决方案


这是避免问题的简单方法。它通过将kwargs字典转换为字符串(连同args)来避免错误,以生成可接受的字典键。

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

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))

推荐阅读