You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
__eq__ and __ne__ are implemented incorrectly for all classes #3455
__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.
Activity
dhermes commentedon May 31, 2017
Thanks @remcohaszing for taking the time to report this! As of 5e86158 it seems to impact 5 subpackages:
Unfortunately, it's spread out in an ad-hoc way so fixing everything will take awhile:
lukesneeringer commentedon Aug 8, 2017
@remcohaszing Sanity check: Should the
if isinstance(other, A):actually beif not isinstance(other, A):?dhermes commentedon Aug 8, 2017
@lukesneeringer I've started to "do this right", e.g. https://github.com/GoogleCloudPlatform/google-cloud-python/blob/26214d229860c5ec128d0d767f1d302f588d49ec/bigquery/google/cloud/bigquery/schema.py#L103-L113
remcohaszing commentedon Aug 8, 2017
@lukesneeringer You're right, my mistake.
lukesneeringer commentedon Aug 8, 2017
@dhermes Should I hold off on this then? I was going to knock them all out.
dhermes commentedon Aug 8, 2017
No, go for it. I was just giving you an example of the "correct" thing.
Any time I've "done the right thing" was for new code.
lukesneeringer commentedon Aug 8, 2017
Okay, that was what I thought, but I wanted to be polite.