Why does Python return True
when I compare int
and float
objects which have the same value?
For example:
>&
It's not as simple as a type conversion.
10 == 10.0
delegates to the arguments' __eq__
methods, trying (10).__eq__(10.0)
first, and then (10.0).__eq__(10)
if the first call returns NotImplemented
. It makes no attempt to convert types. (Technically, the method lookup uses a special routine that bypasses instance __dict__
entries and __getattribute__
/__getattr__
overrides, so it's not quite equivalent to calling the methods yourself.)
int.__eq__
has no idea how to handle a float:
>>> (10).__eq__(10.0)
NotImplemented
but float.__eq__
knows how to handle ints:
>>> (10.0).__eq__(10)
True
float.__eq__
isn't just performing a cast internally, either. It has over 100 lines of code to handle float/int comparison without the rounding error an unchecked cast could introduce. (Some of that could be simplified if the C-level comparison routine didn't also have to handle >
, >=
, <
, and <=
.)