[Python-ideas] Yet another sum function (fractions.sum)

Andrew Barnert abarnert at yahoo.com
Wed Aug 21 18:43:03 CEST 2013


On Aug 21, 2013, at 9:19, random832 at fastmail.us wrote:

> 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 isn't like type checking. That's the whole point of EAFP--and really, the whole point of exceptions. You write the natural code you would write without checking any preconditions, and then you wrap it in a try/except to deal with any exceptions that arise when the preconditions have turned out to be invalid.

You could make a parallel argument about dict.__getitem__, which I think is more obviously wrong. Why should it return an exception instead of returning some "undefined" value like JavaScript? For that matter, why should any function raise an exception; even open could be changed to return a file object that can be checked for validity instead of raising on file not found, like C returning a -1 fd (or NULL FILE*).

There's no simple rule that says which things should be pre-checked, which should be handled with exceptions, and which should allow you to propagate errors as far as possible with out-of-range values. That's why language design is an art, with tradeoffs requiring judgment calls.

> 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.

Sure, there's a judgment call there. There's a cost in having two functions (a more complex language), but a cost in not doing so (not being able to express positive-only computations as easily). But the fact that a judgment call is required doesn't mean a language designer throws up his hands and says "I guess I'll just have one number type to avoid all these problems," it means that he uses his judgment for each case. It turns out that people very often want to do real-only computation--much more often than they want to do positive-only--so the parallel question can have a different answer in the two cases. (And of course integer-only computation falls somewhere between those two extremes.)



More information about the Python-ideas mailing list