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

Mark Shannon mark at hotpy.org
Tue Apr 2 10:33:21 CEST 2013



On 02/04/13 01:44, Nick Coghlan wrote:
> On Mon, Apr 1, 2013 at 12:28 AM, Mark Dickinson <dickinsm at gmail.com
> <mailto:dickinsm at gmail.com>> wrote:
>
>     As written, int_check would do the wrong thing for bools, too:  I
>     definitely want int(True) to be 1, not True.
>
>     For (2) and (4), it's not so clear.  Are there use-cases for an
>     __index__ return value that's not directly of type int?  I can't
>     think of any offhand.
>
>
> int() and operator.index() are both type coercion calls to produce true
> Python integers - they will never return a subclass, and this is both
> deliberate and consistent with all the other builtin types that accept
> an instance of themselves as input to the constructor. Passing a
> subclass instance to the base class constructor is the way you convert a
> subclass to an ordinary instance of the base class:

Unfortunately, that is not true :(

 >>> class Int(int):
...     def __int__(self):
...         return self
...
 >>> type(int(Int()))
<class '__main__.Int'>

Hence my original question: what *should* the semantics be?

>
>  >>> for base in (str, bytes, bytearray, int, float, complex, dict,
> tuple, list, set, frozenset):
> ...     class subclass(base): pass
> ...     print("'type(base(subclass()))' is", type(base(subclass())))
> ...
> 'type(base(subclass()))' is <class 'str'>
> 'type(base(subclass()))' is <class 'bytes'>
> 'type(base(subclass()))' is <class 'bytearray'>
> 'type(base(subclass()))' is <class 'int'>
> 'type(base(subclass()))' is <class 'float'>
> 'type(base(subclass()))' is <class 'complex'>
> 'type(base(subclass()))' is <class 'dict'>
> 'type(base(subclass()))' is <class 'tuple'>
> 'type(base(subclass()))' is <class 'list'>
> 'type(base(subclass()))' is <class 'set'>
> 'type(base(subclass()))' is <class 'frozenset'>
>
> 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.
>
> If the language and library reference aren't clear on this, it's a
> documentation issue.
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   | ncoghlan at gmail.com <mailto:ncoghlan at gmail.com>   |
> Brisbane, Australia


More information about the Python-Dev mailing list