[docs] [issue17576] PyNumber_Index() is not int-subclass friendly (or operator.index() docos lie)

STINNER Victor report at bugs.python.org
Tue Aug 13 10:26:25 EDT 2019


STINNER Victor <vstinner at redhat.com> added the comment:

It started to write a new issue, but then I found this issue issue (created in 2013!) which is still open. So let me write my comment here instead.

The code to convert a number to an integer is quite complex in Python. There are *many* ways to do that and each way has subtle behavior differences (ex: __index__ vs __int__). Python tolerates some behavior which lead to even more confusion. For example, some functions explicitly reject the float type but accept Decimal:

* bpo-20861
* bpo-35707

PyLong_Long(obj) calls type(obj).__index__() if it's defined, but it accepts subtypes of int, not only exactly the int type (type(x) == int). This feature is deprecated since Python 3.3 (released in 2012), since this change:

commit 31a655411a79b00517cdcd0a2752824d183db792
Author: Serhiy Storchaka <storchaka at gmail.com>
Date:   Wed Dec 11 21:07:54 2013 +0200

    Issue #17576: Deprecation warning emitted now when __int__() or __index__()
    return not int instance.  Introduced _PyLong_FromNbInt() and refactored
    PyLong_As*() functions.

I propose to now fail with an exception if __int__() or __index__() return type is not exactly int.

Note: My notes on Python numbers: https://pythondev.readthedocs.io/numbers.html

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue17576>
_______________________________________


More information about the docs mailing list