[Python-Dev] int() and math.trunc don't accept objects that only define __index__

Steven D'Aprano steve at pearwood.info
Thu Mar 14 22:45:42 EDT 2019


On Wed, Mar 13, 2019 at 03:21:31AM -0700, Rémi Lapeyre wrote:

> When __index__ is defined it means that there is a lossless conversion
> to int possible. In this case, this means a lossless conversion to
> float and complex is also possible 

That's not correct:

py> n = 2**64 + 1
py> n == int(float(n))
False

Python floats (C doubles) can lose digits when converting from ints 
over 2**53 or so.


> (with the exception of overflows
> but anyone doing float(var) should expect them).

I don't. I expect float(var) to overflow to infinity, if it is going to 
overflow, and always forget that it can raise.


py> float("9e9999")
inf

py> float(str(9*10**9999))
inf

But:

py> float(9*10**9999)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float

This never fails to surprise me.




-- 
Steven


More information about the Python-Dev mailing list