【问题标题】:Call this memoized function raises TypeError: unhashable type: 'dict'调用这个记忆函数会引发 TypeError: unhashable type: 'dict'
【发布时间】:2021-02-17 16:38:55
【问题描述】:

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

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'

【问题讨论】:

  • Highly related,但我不认为是骗子(见第一个答案)。

标签: python function python-decorators


【解决方案1】:

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

我从Python Decorator LibraryMemoize 部分得到这个想法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多