__eq__ and __ne__ are implemented incorrectly throughout the entire google-cloud-* code base. I encountered this issue when trying to compare a google.cloud.datastore.Key instance to unittest.mock.ANY.
When implementing custom equality in Python (2 or 3), it should be written like this:
classA:
def__eq__(self, other):
ifnotisinstance(other, A):
# Delegate comparison to the other instance's __eq__.returnNotImplemented# Whatever logic applies to equality of instances of A can be added here.
...
def__ne__(self, other):
# By using the == operator, the returned NotImplemented is handled correctly.returnnotself==other
Throughout the entire code base of this repository, equality is implemented like this:
classA:
def__eq__(self, other):
ifnotisinstance(other, A):
# Other instances are never equal.returnFalse# Whatever logic applies to equality of instances of A can be added here.
...
def__ne__(self, other):
# By negating the return value, NotImplemented is treated as False.returnnotself.__eq__(other)
As a result gcloud instances can never equal entities of other classes if they are the first object in the comparison. This is not an issue for most cases, but there are cases where this is an issue. Also this behaviour is simply incorrect.
The __ne__ implementation works, because __eq__ is implemented incorrectly. The boolean value of NotImplemented is True.
>>>notNotImplementedFalse
This is typically an issue when unittesting.
>>>fromunittest.mockimportANY>>>>>>fromgoogle.cloud.datastoreimportClient>>>>>>>>>client=Client()
>>>key=client.key('foo')
>>>key==ANY# Expected TrueFalse>>>ANY==keyTrue>>>key!=ANY# Expected FalseTrue>>>ANY!=keyFalse>>>
__eq__and__ne__are implemented incorrectly throughout the entiregoogle-cloud-*code base. I encountered this issue when trying to compare agoogle.cloud.datastore.Keyinstance tounittest.mock.ANY.When implementing custom equality in Python (2 or 3), it should be written like this:
Throughout the entire code base of this repository, equality is implemented like this:
As a result gcloud instances can never equal entities of other classes if they are the first object in the comparison. This is not an issue for most cases, but there are cases where this is an issue. Also this behaviour is simply incorrect.
The
__ne__implementation works, because__eq__is implemented incorrectly. The boolean value ofNotImplementedisTrue.This is typically an issue when unittesting.