[Python-ideas] except expression

Paul Moore p.f.moore at gmail.com
Tue Feb 18 15:07:43 CET 2014


On 18 February 2014 13:37, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, Feb 19, 2014 at 12:00 AM, Paul Moore <p.f.moore at gmail.com> wrote:
>> On 18 February 2014 12:49, MRAB <python at mrabarnett.plus.com> wrote:
>>>> I really think that this proposal needs to focus on the short, simple
>>>> use cases and *not* worry about too much generality. For example:
>>>>
>>>>     sum(x[3] except 0 for x in list_of_tuples)
>>>>
>>> Shouldn't that be:
>>>
>>>
>>>     sum(x[3] except: 0 for x in list_of_tuples)
>>>
>>> (colon added)?
>>
>> Only if you feel that a colon is necessary for the syntax. I don't :-)
>
> The colon is necessary if the new syntax should allow the
> specification of the exception. If it's always equivalent to a bare
> except that doesn't capture the exception object, then it'd be
> unnecessary.

Well, yes and no. There are only 2 out of the 10 syntaxes originally
proposed in the PEP at the start of this thread that use a colon. I've
already pointed out that I don't like a colon, so assume I said
"except return 0" if you must :-)

> Personally, I don't want to create a special syntax that does
> something that's strongly discouraged. I'm open to argument that the
> expression-except should accept just a single except clause; I'm open
> to argument that it shouldn't be able to capture (due to complications
> of creating sub-scopes), though that's more a nod to
> implementation/specification difficulty than any conceptual dislike of
> the syntax (it's clean, it's consistent, it's sometimes useful); but I
> don't want to narrow this down to always having to catch everything.

That's a fair point, certainly, and probably worth capturing
explicitly in the PEP if it's not already there. I could argue that
"bare except" is more acceptable in an *expression* context because
expressions should never be so complex that the reasons why it's bad
in a statement context actually apply. But I'd only be playing devil's
advocate by doing so. My main point here was to force attention back
onto the *real* use cases which (as I see it) are very simple
exception handling for a simple subexpression embedded in a compound
expression. Examples of how you could catch 3 different exceptions,
use exception data, etc, are to my mind missing the point. At that
stage, factor out the expression and use try/except *statements* and a
temporary variable.

Also, "expr except fallback" is a very simple case of a keyword-based
binary operation. So (ignoring the bare except issue) it's much less
controversial. It's only when you need to specify the exception type
that you get into ternary (and n-ary) territory, where there's a lot
less consistency or prior art to base design decisions on. Hence all
the multiple syntax proposals, fun debates and controversy ;-)

Paul


More information about the Python-ideas mailing list