Types that define `__eq__` are unhashable?

后端 未结 4 1664
青春惊慌失措
青春惊慌失措 2020-11-27 05:05

I had a strange bug when porting a feature to the Python 3.1 fork of my program. I narrowed it down to the following hypothesis:

In contrast to Python 2.x, in Python

4条回答
  •  暖寄归人
    2020-11-27 05:51

    Yes, if you define __eq__, the default __hash__ (namely, hashing the address of the object in memory) goes away. This is important because hashing needs to be consistent with equality: equal objects need to hash the same.

    The solution is simple: just define __hash__ along with defining __eq__.

提交回复
热议问题