Instances as dictionary key, __hash__ and __eq__

Jean-Michel Pichavant jeanmichel at
Tue Feb 19 11:11:57 CET 2013

> > Additionally, If I'm making things much more complicated than they
> > need to be, let me know.

> You are. There are ways to achieve what you want, but it requires a
> lot more setup and discipline. The simplest way is probably to have
> a _equal_fields() method that subclasses override, returning a tuple
> of the attributes that should be hashed. Then in __hash__() and
> __eq__ you iterate over the returned tuple, get the value for each
> attribute and either hash or compare.

> Of course, you have to take into account in __eq__ that the other
> instance may not have the same attributes (e.g. self is a subclass
> that uses extra attributes in its __hash__ and __eq__).

> Tim Delaney

I will happily restrain myself to never subclass such class.



The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.

More information about the Python-list mailing list