[Python-Dev] Semantics of int(), index() (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Tue Apr 2 02:44:48 CEST 2013


On Mon, Apr 1, 2013 at 12:28 AM, Mark Dickinson <dickinsm at gmail.com> wrote:

As written, intcheck 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:

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 | Brisbane, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20130402/685d93af/attachment.html>



More information about the Python-Dev mailing list