[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Tue Feb 18 17:43:45 CET 2014


On Wed, Feb 19, 2014 at 3:25 AM, Paul Moore <p.f.moore at gmail.com> wrote:
> Explicit is better than implicit - I think this discussion has done
> its job and established that trying to assume a subset of exceptions
> to catch isn't going to work. We either allow a bare except to mean
> "catch all exceptions" (which exactly the same risks and provisos as a
> bare except *statement*) or we make the exception to catch mandatory.

Yep, agreed. I'm personally inclined to permit the bare except, and
then advise against it in PEP 8, but both halves of that are
debatable. I'm of the opinion that this would be risky:

lst[x] except: "x is out of bounds"

and would prefer the more verbose:

lst[x] except KeyError: "x is out of bounds"

but I can understand that some people will prefer the shorter form,
even though it could mask a typo in either name. It's no different
from any other uncatchable error:

if html_tag == "<scrpit>": handle_script()

Nobody expects the Python inquisition to catch that for them. A bare
except lets you sacrifice some quick-error-catching-ness for some
quick-code-typing-ness. [1]

> OTOH, there's still an argument for only allowing a single exception
> name in the syntax (an "identifier" rather than an "expression" in
> syntax terms). If you must catch multiple exceptions, give the
> relevant tuple a name.

Hmm. Would that make anything any clearer? It feels like the sorts of
crazy limitations that I've seen in some other languages, like how PHP
up until relatively recently wouldn't let you subscript an array
returned from a function without first assigning it to a variable:

$x = func()[5];

$x = func();
$x = $x[5];

One of the things I like about Python is that anything is itself,
regardless of its context. An expression yields a value, that value
can be stored, and any expression yielding the same value will be
exactly the same thing:

func = obj.method
func()
# <->
obj.method()

Contrast JavaScript, where those two are actually different.

So in exception catching, *especially* in an expression context (where
you can't assign anyway), is it really necessary to dump your two-name
tuple out into a temporary name?

[1] Now my fingers are wondering: Is there a
global-interpreter-loch-ness monster?


More information about the Python-ideas mailing list