[英]Error: unhashable type: 'dict' with @dataclass
I have a class Table:我有一个班级表:
@dataclass(frozen=True, eq=True)
class Table:
name: str
signature: Dict[str, Type[DBType]]
prinmary_key: str
foreign_keys: Dict[str, Type[ForeignKey]]
indexed: List[str]
And need to create such dictionary:并且需要创建这样的字典:
table = Table(*args)
{table: 'id'}
TypeError: unhashable type: 'dict'
类型错误:不可散列的类型:'dict'
Don't understand what's the problem.不明白有什么问题。
The autogenerated hash method isn't safe, since it tries to hash the unhashable attributes signature
, primary_key
, and indexed
.自动生成的散列方法并不安全,因为它试图散列不可散列的属性
signature
、 primary_key
和indexed
。 You need to define your own __hash__
method that ignores those attributes.您需要定义自己的
__hash__
方法来忽略这些属性。 One possibility is一种可能性是
def __hash__(self):
return hash((self.name, self.primary_key))
Both self.name
and self.primary_key
are immutable, so a tuple containing those values is also immutable and thus hashable. self.name
和self.primary_key
都是不可变的,所以包含这些值的元组也是不可变的,因此是可散列的。
An alternative to defining this method explicitly would be to use the field
function to turn off the mutable fields for hashing purposes.显式定义此方法的另一种方法是使用
field
函数关闭可变字段以进行哈希处理。
@dataclass(frozen=True, eq=True)
class Table:
name: str
signature: Dict[str, Type[DBType]] = field(compare=False)
prinmary_key: str
foreign_keys: Dict[str, Type[ForeignKey]] = field(compare=False)
indexed: List[str] = field(compare=False)
field
has a hash
parameter whose default value is the value of compare
, and the documentation discourages using a different value for hash
. field
有一个hash
参数,其默认值是compare
的值,文档不鼓励对hash
使用不同的值。 (Probably to ensure that equal items hash identically.) It's unlikely that you really want to use these three fields for the purposes of comparing two tables, so you this should be OK. (可能是为了确保相同的项目散列相同。)您不太可能真的想使用这三个字段来比较两个表,所以您应该可以。
I would consult the documentation rather than relying on my relatively uninformed summary of it.我会查阅文档,而不是依赖于我相对不知情的总结。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.