python - 调用这个记忆函数会引发 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'
解决方案
这是避免问题的简单方法。它通过将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))
推荐阅读
- c# - 可暂停的 System.Timers.Timer
- firebase - BigQuery 与 Cloud SQL 自动扩缩?
- vehicle-routing - jsprit 能解决需求负的 VRPC 还是 VRPB 更好?
- neural-network - 使用无意义的类来预训练模型重要吗?
- node.js - 在 NodeJS 环境中使用 react-native
- google-compute-engine - 有一个谷歌计算云实例 - 我的密码是什么?
- android - 切换按钮 Recyclerview 问题
- javascript - 有没有办法在不断开客户端的情况下切换html文件?
- c++ - 使用纹理数组时,为什么我不必将采样器绑定到着色器?
- java - 空指针异常 JUnit Mockito