Skip to content

__eq__ and __ne__ are implemented incorrectly for all classes #3455

Description

@remcohaszing

__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>>>

Metadata

Metadata

Labels

api: coretype: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions