[Python-Dev] int() and math.trunc don't accept objects that only define __index__
Serhiy Storchaka
storchaka at gmail.com
Fri Feb 22 03:25:39 EST 2019
18.02.19 18:16, Rémi Lapeyre пише:
> The documentation mentions at
> https://docs.python.org/3/reference/datamodel.html#object.__index__
> the need to always define both __index__ and __int__:
>
> Note: In order to have a coherent integer type class, when
> __index__() is defined __int__() should also be defined, and both should
> return the same value.
>
> Nick Coghlan proposes to make __int__ defaults to __index__ when only
> the second
> is defined and asked to open a discussion on python-dev before making
> any change
> "as the closest equivalent we have to this right now is the "negative"
> derivation,
> where overriding __eq__ without overriding __hash__ implicitly marks the
> derived
> class as unhashable (look for "type->tp_hash =
> PyObject_HashNotImplemented;").".
>
>
> I think the change proposed makes more sense than the current behavior and
> volunteer to implement it if it is accepted.
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.
More information about the Python-Dev
mailing list