[Python-Dev] int() and math.trunc don't accept objects that only define __index__
Nick Coghlan
ncoghlan at gmail.com
Fri Feb 22 12:09:36 EST 2019
On Fri, 22 Feb 2019 at 18:29, Serhiy Storchaka <storchaka at gmail.com> wrote:
> Should we add default implementations of __float__ and __complex__ when
> either __index__ or __int__ is defined? Currently:
>
> >>> class A:
> ... def __int__(self): return 42
> ...
> >>> int(A())
> 42
> >>> float(A())
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: float() argument must be a string or a number, not 'A'
> >>> complex(A())
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: complex() first argument must be a string or a number, not 'A'
>
> Or just document that in order to have a coherent integer type class,
> when __index__() or __int__() are defined __float__() and __complex__()
> should also be defined, and all should return equal values.
I think when __index__ is defined, it would be reasonable to have that
imply the same floating point conversion rules as are applied for
builtin ints, since the conversion is supposed to be lossless in that
case (and if it isn't lossless, that's what `__int__` is for).
However, I don't think the decision is quite as clearcut as it is for
`__index__` implying `__int__`.
Lossy conversions to int shouldn't imply anything about conversions to
real numbers or floating point values.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev
mailing list