Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Python perform type conversion when comparing int and float?

Why does Python return True when I compare int and float objects which have the same value?

For example:

>>> 5*2 == 5.0*2.0
True
like image 709
gaurav Avatar asked Sep 28 '18 14:09

gaurav


2 Answers

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 <=.)

like image 147
chepner Avatar answered Sep 24 '22 01:09

chepner


Objects of different types, except different numeric types, never compare equal.

And:

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. Comparisons between numbers of mixed type use the same rule.

https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex

The comparison logic is implemented by each type's __eq__ method. And the standard numeric types are implemented in a way that they support comparisons (and arithmetic operations) among each other. Python as a language never does implicit type conversion (like Javascript's == operator would do implicit type juggling).

like image 39
deceze Avatar answered Sep 22 '22 01:09

deceze