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

Rémi Lapeyre report at bugs.python.org
Mon May 6 10:11:13 EDT 2019


Rémi Lapeyre <remi.lapeyre at henki.fr> added the comment:

Hi Cheryl,

thanks for the ping.

I wasn't sure my patch was correct but reading typeobject.c:add_operators(), it is actually more straight-forward than I thought.


Serhiy Storchaka: This is indeed a duplicate of issue20092. I believe the solution proposed by Nick Coghlan is better than the one of Amitava Bhattacharyya, "adding a call to `nb_index` (if that slot exists) in `_PyLong_FromNbInt`" though.


One thing to note regarding the proposed patch: the following stops to work and raises a RecursionError since __index__ == __int__:

        class MyInt(int):
            def __index__(self):
                return int(self) + 1

I changed test_int_subclass_with_index() as `int(self) + 1` is the same thing as `self + 1` for int subclasses. I don't think this sort of code should appear in the wild but if you think it is important not to break compatibility here, I think I could check for number subclasses before overriding __index__.

----------

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


More information about the Python-bugs-list mailing list