[Python-Dev] Definition of equality check behavior

Steven D'Aprano steve at pearwood.info
Tue May 7 19:17:24 EDT 2019


On Tue, May 07, 2019 at 05:05:57PM -0400, 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.

I think you may be labouring under a few misapprehensions here.

1. Comparisons between builtins such as ints and objects of different 
types do not always return False:

py> class X:
...     def __eq__(self, other):
...             return True
...
py> 123 == X()
True

You don't need a custom class to demonstrate this fact, you just need 
values which actually are equal:

py> 123 == 1.23e2  # int compared to float
True


2. Comparisons are not supposed to raise NotImplementedError as part of 
the core data model, they are supposed to return (not raise) 
NotImplemented. Note that NotImplementedError is a completely different 
thing).

As the documentation you linked to says:

    A rich comparison method may return the singleton NotImplemented 
    if it does not implement the operation for a given pair of 
    arguments.



3. Equality does not suppress exceptions and lead to silent failure:

py> class Y:
...     def __eq__(self, other):
...             raise NotImplementedError
...
py> 123 == Y()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __eq__
NotImplementedError


Hope this helps.



-- 
Steven


More information about the Python-Dev mailing list