[Python-ideas] except expression
Rob Cliffe
rob.cliffe at btinternet.com
Mon Feb 17 15:33:34 CET 2014
On 17/02/2014 10:00, M.-A. Lemburg wrote:
> On 16.02.2014 05:04, Chris Angelico wrote:
> The colon in there breaks the basic Python concept of having
> colons end headers which start a new block of statements:
>
> http://docs.python.org/reference/compound_stmts.html
>
> I think it would be better to have the PEP focus on a solution
> that doesn't introduce more lambda like syntax to the language :-)
>
> Please also add examples where the expression notation is
> used as part of a larger expression, e.g.
>
> value = lst[2] except IndexError: 0, 1
> value = lst[2] except IndexError: 0 if x else -1
> value = lst[2] except IndexError: 0 if lst[1] except IndexError: False else -1
> value = lst[2] except IndexError: 0 + lst[0]
> d = {'a': lst[2] except IndexError: 0,
> 'b': lst[1] except IndexError: 0 if lst[0] else 1,
> 'c': lst[0],
> }
>
>
Just wanted to point out the ambiguity in some of these, at least to a
human reader.
If I am not mistaken, the proposed precedence for "except" (higher than
"lambda", lower than everything else including "if - else") means that:
The first one means
value = lst[2] except IndexError: (0,1)
not
value = (lst[2] except IndexError: 0), 1
The second means
value = lst[2] except IndexError: (0 if x else -1)
not
value = (lst[2] except IndexError: 0) if x else -1
The third means
value = lst[2] except IndexError: (0 if (lst[1] except IndexError:
False) else -1)
rather than anything else (this is getting a bit mind-boggling).
The fourth means
value = lst[2] except IndexError: (0 + lst[0])
rather than
value = (lst[2] except IndexError: 0) + lst[0]
I wonder if the actual meaning coincides in all cases with your
intention when you wrote them?
No offence intended, MAL, I'm not trying to slag you off, just pointing
out some of the issues that arise. :-)
And wondering if there is a case for "except" having a higher precedence
than "if - else". I don't have an opinion yet, I'm just thinking aloud.
The last one is I believe unambiguous except for the value associated
with the key 'b', but to my mind is another reason for not allowing
commas in the proposed "except expression" syntax - confusion with
commas as separators between dictionary literals (sorry I keep plugging
this!). There is already ISTM a clash between comma as separator
between dictionary items and between tuple elements:
>>> { 'a' : (1,3), 'b' : 2 }
{ 'a': (1, 3), 'b': 2 }
>>> { 'a' : 1,3, 'b' : 2 } # Python 2.7.3
SyntaxError: invalid syntax
so I think it would be a mistake to overload the comma further.
Best wishes,
Rob Cliffe
More information about the Python-ideas
mailing list