简体   繁体   English

如何合并数据类,属性和lru_cache

[英]How to combine dataclass, property, and lru_cache

I'm trying to combine dataclasses, properties and lru_caches for some computational science code: 我正在尝试将数据类,属性和lru_caches结合起来以用于一些计算科学代码:

from dataclasses import dataclass
from typing import Any
from functools import lru_cache
@dataclass
class F:
    a: Any = 1
    b: Any = 2
    c: Any = 3
    @property
    @lru_cache(1)
    def d(self):
        print('Computing d')
        return (self.a+self.b)**self.c
f=F()
print(f.d)
print(f.d)

I hoped to see 我希望看到

Computing d
27
27

but get 但是得到

TypeError: unhashable type: 'F'

Is there a way to fix this? 有没有办法解决这个问题?

lru_cache is like memoization so it hashes arguments passed to the function and stores the result. lru_cache就像lru_cache一样,因此它哈希传递给函数的参数并存储结果。 Your class isn't hashable. 您的课程不可散列。 To make it hashable, add something like this 为了使其可散列,请添加如下内容

class F:
    ....
    def __hash__(self):
        return hash((self.a, self.b, self.c))

The reason for this is that these 3 attributes make each instance 'unique' - we don't need to hash the methods as all instances have the same methods. 原因是这3个属性使每个实例“唯一”-我们无需对方法进行哈希处理,因为所有实例都具有相同的方法。

On most normal classes, it's __dict__ is used for general hashing unless a __hash__ method is found. 在大多数普通类上,除非找到__hash__方法,否则它使用__dict__进行常规哈希处理。 The dataclass documentation explains that it is possible for the dataclass to generate a hashing method but it depends on how you set up the dataclass as by default the object is assumed to be mutable (and mutable objects like lists can't be hashed). 数据类文档解释说,数据类可能会生成哈希方法,但是这取决于您如何设置数据类,因为默认情况下该对象被认为是可变的(并且可变对象(如列表)不能被哈希)。

The dataclass documentation states that a hash method will be generated if the parameters eq and frozen are set to True when decorating with @dataclass() , but your application may not warrant this as frozen prohibits attribute assignment on instances . 数据类文档指出哈希方法,如果参数生成的eqfrozen设置为True与装修时@dataclass()但您的应用程序可能无法保证这是frozen禁止在实例属性分配。

https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM