首页 > 解决方案 > 如果来自 Python 字典的子类,则 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试图缓存selfself.tomatrix().

另一方面,如果我没有从子类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 缓存。

标签: pythondictionarylru

解决方案


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

添加行

__hash__ = object.__hash__

工作Mask(dict)

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


推荐阅读