Nick Coghlan added the comment:

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)

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue19927>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to