[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Tue Feb 18 22:46:08 CET 2014


On Wed, Feb 19, 2014 at 8:38 AM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> What *might* be useful is to allow the exception type to
> be omitted, and have it default to LookupError. Then the
> most common anticipated use cases would be very concise:
>
>    things[i] except: default_value

While that does seem very tempting, I'm strongly against having a
dramatic-yet-likely-unnoticed difference between these two:

_ = things[i] except: default_value

and

try:
    _ = things[i]
except:
    _ = default_value

By your suggestion, the first one is equivalent to:

_ = things[i] except LookupError: default_value

But by current rules of Python, the second is equivalent to:

_ = things[i] except BaseException: default_value

and that's really REALLY bad to do unexpectedly. Suppose the lookup
into things[i] takes a long time (maybe the system's low on memory and
has to page stuff back in), and the user hits Ctrl-C while it's doing
it. Catching BaseException means getting back the default_value there;
catching LookupError means having KeyboardInterrupt propagate upward.
Same goes for typoing 'things', or any other sort of error. I want to
be able to explain the exception-expression in terms of a
similarly-spelled exception-statement, which means that every piece of
common syntax should have parallel semantics - just as lambda and def
do. That means having a bare except either cause an error, or do the
same thing a bare except does in the statement form.

ChrisA


More information about the Python-ideas mailing list