python - 如果来自 Python 字典的子类,LRU 缓存不可散列类型

标签 python dictionary lru

我试图找出为什么以下代码不起作用

from functools import lru_cache
import numpy as np

class Mask(dict):
    def __init__(self, shape, data = None):
        super().__init__(data)
        self.shape = shape

    @lru_cache(maxsize=1)
    def tomatrix(self):
        dense = np.zeros(self.shape[0] * self.shape[1])
        for uid, entries in self.items():
            dense[entries] = uid
        return np.reshape(dense, self.shape)

cells = {i : np.arange(i * 10, (i + 1) * 10) for i in range(10)}
mask = Mask((10, 10), cells)

r1 = mask.tomatrix()
r2 = mask.tomatrix()                       

错误提示

TypeError: unhashable type: 'Mask'

就好像lru_cache尝试在self.tomatrix()中缓存self

另一方面,如果我不从 dict 子类化,而是使用一个内部成员 self.data 来存储实际数据,则 LRU 包装器不会提示。

有效的代码:

from functools import lru_cache
import numpy as np

class Mask:
    def __init__(self, shape, data = None):
        self.data = data
        self.shape = shape

    @lru_cache(maxsize=1)
    def tomatrix(self):
        dense = np.zeros(self.shape[0] * self.shape[1])
        for uid, entries in self.data.items():
            dense[entries] = uid
        return np.reshape(dense, self.shape)

cells = {i : np.arange(i * 10, (i + 1) * 10) for i in range(10)}
mask = Mask((10, 10), cells)

r1 = mask.tomatrix()
r2 = mask.tomatrix()                       

谁能帮我解开这个谜团?我想继续从 dict 进行子类化,并且需要使用 LRU 缓存。

最佳答案

解决方案是获取为继承自object的用户类定义的默认__hash__函数。 dict 定义了自己的 __eq__,但没有 __hash__,因此被阻止。

添加行

__hash__ = object.__hash__

Mask(dict)有效。

非常感谢this回答另一个问题!

关于python - 如果来自 Python 字典的子类,LRU 缓存不可散列类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68119031/

相关文章:

python - 将 PostGIS 几何类型作为几何类型从 Shapely 导入 Python?

c++ - 显示 `std::map`

java LRU缓存: LinkedHashMap with a timestamp?

python - 从字符串 [Python] 创建多级字典

dictionary - Realm中的HashMap序列化(移动数据库)

scala - Scala 中的 LRUCache?

c++ - 用C++实现LRU缓存

创建矩阵时的 Python 错误

python - 石头、剪刀、布 - Python

python - 打印包含字符串和 2 个其他变量的变量