[Python-Dev] Semantics of __int__(), __index__()

Mark Dickinson dickinsm at gmail.com
Tue Apr 2 09:18:29 CEST 2013

On Tue, Apr 2, 2013 at 8:07 AM, Mark Dickinson <dickinsm at gmail.com> wrote:

> On Tue, Apr 2, 2013 at 1:44 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> There's code in the slot wrappers so that if you return a non-int object
>> from either __int__ or __index__, then the interpreter will complain about
>> it, and if you return a subclass, it will be stripped back to just the base
>> class.
> Can you point me to that code?  All I could find was PyLong_Check calls (I
> was looking for PyLong_CheckExact).

And indeed:

iwasawa:Objects mdickinson$ /opt/local/bin/python3.3
Python 3.3.0 (default, Sep 29 2012, 08:16:19)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...     def __int__(self):
...         return True
...     def __index__(self):
...         return False
>>> a = A()
>>> int(a)
>>> import operator; operator.index(a)

Which means I have to do int(int(a)) to get the actual integer value.  Grr.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130402/c2fb85ea/attachment.html>

More information about the Python-Dev mailing list