Skip to content

Commit

Permalink
Fix default Object __eq__ and __ne__
Browse files Browse the repository at this point in the history
- For objects which don’t override __eq__ and __ne__, they should
return True/False respectively when comparing an object against itself,
and otherwise NotImplemented instead of False.
  • Loading branch information
cflee committed Mar 9, 2017
1 parent e89d822 commit 0245ad9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion python/common/org/python/types/Object.java
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,11 @@ public org.python.Object __le__(org.python.Object other) {
args = {"other"}
)
public org.python.Object __eq__(org.python.Object other) {
return new org.python.types.Bool(System.identityHashCode(this) == System.identityHashCode(other));
if (this == other) {
return new org.python.types.Bool(true);
} else {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
}

@org.python.Method(
Expand Down
27 changes: 27 additions & 0 deletions tests/structures/test_comparisons.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,33 @@ def test_ne(self):
print('False')
""")

def test_eq_empty_class(self):
self.assertCodeExecution("""
class A:
pass
x = A()
y = A()
# fallback to object identity
print(x == x)
print(x == y)
print(x.__eq__(x))
print(x.__eq__(y))
print(y.__eq__(x))
""")

def test_ne_empty_class(self):
self.assertCodeExecution("""
class A:
pass
x = A()
y = A()
print(x != x)
print(x != y)
print(x.__ne__(x))
print(x.__ne__(y))
print(y.__ne__(x))
""")

# next few tests from cpython's Lib/test/test_compare.py @ v3.6.0
def test_comparisons(self):
self.assertCodeExecution("""
Expand Down

0 comments on commit 0245ad9

Please sign in to comment.