[Python-Dev] return type of __complex__

Steven D'Aprano steve at pearwood.info
Sun Oct 21 02:04:54 CEST 2012


On 20/10/12 01:13, Nick Coghlan wrote:
> On Fri, Oct 19, 2012 at 11:08 PM, Antonio Cuni<anto.cuni at gmail.com>  wrote:
>> Is that the real intended behavior?
>
> Given the way complex numbers interact with floats generally,
> returning a complex number with no imaginary component as a floating
> point value seems legitimate


Surely the intention is for __complex__ to return a complex number? That
is, that it is desirable to have the invariant:

isinstance(x.__complex__(), complex)

?

We expect that __int__ returns an int, and raise an exception if it
doesn't, even in the case that the value returned is numerically integral:

py> class X:
...     def __int__(self):
...             return 2.0
...
py> x = X()
py> int(x)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: __int__ returned non-int (type float)


Conceptually, I see returning a float when you expect a complex as
equally dubious as returning an integral float when you expect an int.
I think there is something dirty about a __complex__ that returns a
non-complex. Why would you deliberately do such a thing? If a class
does so, that's surely indicative of a bug, so the earlier it gets
caught, the better.



> and the checks in cmath overly strict.
>
> Otherwise you would get redundancy like:
>
>      def __complex__(self):
>          return complex(value)
> or
>
>      def __complex__(self):
>          return value + 0j


For the record, I think Nick is referring to the fact that the complex
constructor will fall back on __float__ if __complex__ does not exist,
adding 0j to x.__float__.

I don't see this as a problem. So what if people write redundant code?
It still works. And when they learn better, they can write better code.



-- 
Steven


More information about the Python-Dev mailing list