osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Python-Dev] Definition of equality check behavior


On 05/07/2019 02:05 PM, Jordan Adler wrote:

> Specifically, a comparison between a primitive (int, str, float were
>  tested) and an object of a different type always return False,
>  instead of raising a NotImplementedError.  Consider `1 == '1'` as a
>  test case.

If the object of a different type doesn't support comparing to an int, str, or float then False is the correct answer.  On the other hand, if the object of a different type wants to compare equal to, say, ints then it will have to supply its own __eq__ method to return False/True as appropriate.


> Should the data model be adjusted to declare that primitive types are
>  expected to fallback to False

No, because they aren't.

> or should the cpython primitive type's __eq__ implementation fallback
>  to raise NotImplementedError?

No, because raising an error is not appropriate.  Did you mean `return NotImplemented`?  Because empirical evidence suggests that they do:

-------
class MyCustomInt():
     def __init__(self, value):
         self.value = value
     def __eq__(self, other):
         if isinstance(other, int):
             return self.value == other
         else:
             return NotImplemented
     def __ne__(self, other):
         if isinstance(other, int):
             return self.value != other
         else:
             return NotImplemented

core_int = 7
my_int = MyCustomInt(7)

print(core_int == my_int)  # True
print(my_int == core_int)  # True
-------

If the core types were not returning NotImplemented then the above would be False on the `core_int == my_int` line.

Hopefully this is clearer now?

--
~Ethan~