[Python-ideas] except expression
Greg Ewing
greg.ewing at canterbury.ac.nz
Sun Feb 16 00:17:47 CET 2014
Steven D'Aprano wrote:
> This suggests that perhaps the parentheses aren't needed unless you have
> multiple except parts:
>
> things[i] (except IndexError, KeyError as exc: exc.args)
> things[i] except IndexError, KeyError as exc: exc.args
Possibly not even necessary when there are multiple except
clauses, if you don't require a comma between them:
things[i] except IndexError: 42 except KeyError: 17
Parsing may be easier without the parens as well, since
otherwise it looks like a function call when you hit
the '(' until you see the 'except' after it. (I *think*
that Python's parser could be made to handle that, but
I'd have to experiment to find out for sure.)
> Here is a torture-test for the syntax: can we combine it with an
> if-expression? I think we can, although you may need parentheses to
> disambiguate the expression:
>
> something(x) (except TypeError: a if condition else b)
The paren-less version of this would be
something(x) except TypeError: a if condition else b
the interpretation of which would depend on what relative
precedence we decide on between 'except' and 'if'.
Parens can still be used to clarify, though:
(something(x) except TypeError: a) if condition else b
something(x) except TypeError: (a if condition else b)
> This does look a tiny bit like a function call, especially if you delete
> the space between the leading expression and the opening bracket:
>
> # ugly, don't do this
> things[i](except IndexError: 42)
Yes, that's why I'm leaning towards the paren-less version.
--
Greg
More information about the Python-ideas
mailing list