[Python-Dev] Definition of equality check behavior (original) (raw)
Steven D'Aprano steve at pearwood.info
Tue May 7 19:17:24 EDT 2019
- Previous message (by thread): [Python-Dev] Definition of equality check behavior
- Next message (by thread): [Python-Dev] Definition of equality check behavior
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
- 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
- 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.
- 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 "", line 1, in File "", line 3, in eq NotImplementedError
Hope this helps.
-- Steven
- Previous message (by thread): [Python-Dev] Definition of equality check behavior
- Next message (by thread): [Python-Dev] Definition of equality check behavior
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]