[Python-Dev] PEP 463: Exception-catching expressions
Eric Snow
ericsnowcurrently at gmail.com
Sat Feb 22 03:49:20 CET 2014
On Fri, Feb 21, 2014 at 7:07 PM, Victor Stinner
<victor.stinner at gmail.com> wrote:
>> Consider this example of a two-level cache::
>> for key in sequence:
>> x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key)))
>> # do something with x
>
> ... but I don't like when it is used to build complex expressions.
This is true of any expression syntax, not just this proposal--though
some expression syntax is more apt to be abused than others: you won't
see many multiline int literals! ;)
>
> At the first read, I'm unable to understand this long expression. At
> the second read, I'm still unable to see which instruction will be
> executed first: lvl1[key] or lvl2[key]?
>
> The advantage of the current syntax is that the control flow is
> obvious, from the top to the bottom:
>
> # start
> try:
> x = lvl1[key] # first instruction
> except KeyError:
> try:
> x = lvl2[key]
> except KeyError:
> x = f(key) # latest instruction
> # end
>
> Thanks to Python indentation, it's easier to see the control flow.
>
> After having read a lot of code last 10 years, I now try to follow
> this rule: one instruction per line.
+1
>
> For example, I don't like "if ((res = func()) == NULL)" in the C
> language, I always split it into two lines. A drawback of writing more
> than one instruction is that it's hard to debug instruction per
> instruction (in pdb/gdb). Think for example of "if ((res = func()) ==
> NULL)": if you execute step by step, how do you know which instruction
> is currently executed?
So true.
>
> You should maybe write your example differently:
>
> x = (lvl1[key]
> except KeyError: (lvl2[key]
> except KeyError: f(key)))
>
> It looks like the classic try/except syntax.
+1
-eric
More information about the Python-Dev
mailing list