Title: Should we define complex.__complex__ and bytes.__bytes__?
Type: Stage:
Components: Versions: Python 3.5
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: gvanrossum, mark.dickinson, serhiy.storchaka, terry.reedy
Priority: normal Keywords:

Created on 2015-05-18 21:37 by gvanrossum, last changed 2018-03-29 15:25 by mark.dickinson.

Messages (4)
msg243538 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2015-05-18 21:37
The special methods __complex__ and __bytes__ are not present on the corresponding builtin types.  Compare this to __int__ and __float__, which do exist on int and float, respectively.  Should we add the eponymous methods to complex and bytes?

(This came up in the context of PEP 484: )
msg243842 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2015-05-22 18:01
To my understanding, the presence of int.__int__ and float.__float__ are implementation issues.  I presume that float(ob) just calls ob.__float__ without slowing down for an isinstance(ob, float) check.  Ditto for int(ob).  The processing for complex(args) and bytes(args) are more complex and currently neither call an eponyous method. Would either be improved if it did?

One difference between int and complex, for instance, that might account for the internal implementation difference is that the second argument of int can only be used with a string first argument, while the second argument of complex cannot be used with a string first argument, and must support multiplication by 1j.  So int.__int__(self) does not allow a second parameter and can (and does) just return self.
msg314623 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-03-29 00:03
The difference between __complex__ and __bytes__ on one side, and __int__ and __float__ on other side is that the latter have dedicated type slots while the former are just entries in the type's dict. Thus testing and calling __int__ and __float__ is much faster.
msg314630 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2018-03-29 01:58
It's not necessary for complex() and bytes() to call the special methods if the argument's type is exactly complex or bytes (respectively) -- these cases are already taken care of by the current code.  But adding these special methods enables other code to be more regular, without having to test for the special cases.
Date User Action Args
2018-03-29 15:25:14mark.dickinsonsetnosy: + mark.dickinson
2018-03-29 01:58:59gvanrossumsetmessages: + msg314630
2018-03-29 00:04:41serhiy.storchakalinkissue33055 superseder
2018-03-29 00:03:47serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg314623
2015-05-22 18:01:12terry.reedysetnosy: + terry.reedy
messages: + msg243842
2015-05-18 21:37:35gvanrossumcreate