[Python-Dev] return type of complex (original) (raw)

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 "", line 1, in 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