This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ncoghlan
Recipients brett.cannon, eric.snow, larry, ncoghlan
Date 2013-12-08.06:31:35
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1386484296.54.0.215426996841.issue19927@psf.upfronthosting.co.za>
In-reply-to
Content
There can be some interesting backwards compatibility consequences when adding an __eq__ implementation to a class that was previously using the default ID based __eq__:

- it becomes unhashable (unless you also add a suitable __hash__ definition)

- subclasses with additional significant state may start comparing equal, even though their additional state is not taken into account by the new __eq__ function.

For the latter problem, you can alleviate it by comparing the instance dictionaries rather than specific attributes:

>>> class Example:
...     def __eq__(self, other):
...         return self.__class__ == other.__class__ and self.__dict__ == other.__dict__
... 
>>> a = Example()
>>> b = Example()
>>> a == b
True
>>> a.foo = 1
>>> a == b
False
>>> b.foo = 1
>>> a == b
True

(technically this can still change subclass behaviour if they're messing about with slots, but there *is* such a thing as being *too* paranoid about backwards compatibility)

The hashability problem is easy enough to handle just by mixing together the hashes of the attributes of most interest:

    def __hash__(self):
        return hash(self.name) ^ hash(self.path)
History
Date User Action Args
2013-12-08 06:31:36ncoghlansetrecipients: + ncoghlan, brett.cannon, larry, eric.snow
2013-12-08 06:31:36ncoghlansetmessageid: <1386484296.54.0.215426996841.issue19927@psf.upfronthosting.co.za>
2013-12-08 06:31:36ncoghlanlinkissue19927 messages
2013-12-08 06:31:35ncoghlancreate