简体   繁体   English

NamedTuples,Hashable和Python

[英]NamedTuples, Hashable and Python

Consider the following code: 考虑以下代码:

#!/usr/bin/env python3.7

from typing import NamedTuple, Set

class Person(NamedTuple):
    name: str
    fred: Set[str]


p = Person("Phil", set())
print(p)

my_dict = {}
my_dict[p] = 10


print(my_dict)

which produces this error 产生这个错误

Traceback (most recent call last):
  File "./temp.py", line 14, in <module>
    my_dict[p] = 10
TypeError: unhashable type: 'set'

In this case, it's sample code, and I have simplified it lots, so its quite easy to see where the error comes from. 在这种情况下,它是示例代码,并且我对其进行了大量简化,因此很容易看出错误的出处。 typed.NamedTuple obviousl calculates its hash based on all of its instances variables and one of them is a set. typed.NamedTuple显然基于其所有实例变量来计算其哈希,其中一个是集合。 When I discovered this, however, it was painful to track down. 但是,当我发现这一点时,很难找到答案。

So, my question is, why is the error message showing this? 所以,我的问题是,为什么错误消息显示此信息? Should it not be TypeError: unhashable type: 'Person' . 它应该不是TypeError: unhashable type: 'Person' And why is the traceback not coming from the bowels of python somewhere where the error actually is. 以及为什么回溯不是来自错误实际所在的python的肠道。

NamedTuple is based on the tuple class. NamedTuple基于tuple类。 See collections.namedtuple() 参见collections.namedtuple()

The hash of a tuple is the combined hash of all the elements. tuple的哈希是所有元素的组合哈希。 See tupleobject.c 参见tupleobject.c

Since set is unhashable it is not possible to hash a tuple or NamedTuple containing a set . 由于set是不可哈希的,因此无NamedTuple包含settupleNamedTuple

And since the hashing of a set is implemented in C you don't see the traceback 而且由于集合的哈希是在C中实现的,因此您看不到追溯

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

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