[Python-ideas] Yet another sum function (fractions.sum)
Stephen J. Turnbull
stephen at xemacs.org
Wed Aug 21 19:32:06 CEST 2013
random832 at fastmail.us writes:
> On Wed, Aug 21, 2013, at 10:45, Stephen J. Turnbull wrote:
> > random832 at fastmail.us writes:
> >
> > > Why exactly is an exception reasonable? If you don't want complex
> > > numbers, don't take square roots of negative numbers. If you can't
> > > handle complex numbers, you'll get an exception down the line anyway.
> >
> > That's precisely why you want an exception: to terminate the
> > computation as soon as the unexpected condition can be detected.
>
> Isn't that unpythonic? I mean, it's like doing type checking
No, it's not, and it's not. In Python, turning 1 into 1 + 0j is a
type conversion[1]:
>>> 1 is 1 + 0j
False
>>> 1 is 1
True
Adding 1 + 0j to 1 requires type checking of the arguments, and a
decision about the type of the result. The same is true here;
behavior on taking square root is part of the *implementation* of a
type, and a negativity check needs to be made before taking the square
root. This is *not* the same thing as EAFP vs. LBYL in application
programming. Rather, this is the low-level implementation that makes
EAFP safe in Python.
> Also, not wanting complex numbers seems to me like not wanting
> negative numbers, but we don't have a positive-subtract function
> that raises an exception if a<b.
That's a good analogy, and it would be a killer analogy if this were
FORTRAN-dev. But it's not good enough on python-dev. On the
pragmatic side, I've been using math, including some pretty advanced
analysis, in my research for 30 years ... but I've yet to meet an
honest complex number in the wild, only in math textbooks and in
programs that use the "computational formula" to compute standard
deviation. I doubt that the applications where it is natural to
expect a complex number as the value of square root come anywhere near
a majority.
On the theory side, in fact Python doesn't have an unsigned numerical
type. So there is no type change when subtracting a larger number
from a smaller number. However, to take the square root of a negative
float you need a type change to complex. So your analogy actually is
nonsense in the context of Python: they're not alike at all!
Note that *none* of the above shows that an exception is TOOWTDI. It
just shows that it's plausible for Python to raise an exception when a
program tries to take the square root of a negative number.
What *would* be unpythonic is if the implementation of the float type
tried to guess whether the user wants an exception or a complex number
in this case.
Steve
Footnotes:
[1] Connoisseurs of the CPython implementation will recognize that
this example is perhaps a bit specious, since the implementation of 1
as a singleton is an optimization, not part of the defined semantics.
But I think it serves to make my point.
More information about the Python-ideas
mailing list