[Python-ideas] syntax to continue into the next subsequent except block
Steven D'Aprano
steve at pearwood.info
Mon Sep 17 06:49:42 CEST 2012
On 17/09/12 10:11, Greg Ewing wrote:
> Guido van Rossum wrote:
>> The suggestion to add ad-hoc "if <condition>" clauses to random parts
>> of the syntax doesn't appeal to me at all.
>
> I wouldn't call it a random part of the syntax. This is
> not like the proposals to add if-clauses to while loops,
> for loops, etc -- they would just be minor syntactic sugar.
> This proposal addresses something that is quite awkward to
> express using existing constructs.
I don't think it is quite awkward. Instead of the proposed:
try:
something()
except ValueError as ex if condition(ex):
spam()
except ValueError:
# if not condition, fall through to the next except block
ham()
this can be easily written as:
try:
something()
except ValueError as ex:
if condition(ex):
spam()
else:
ham()
which costs you an indent level, which is not a big deal. (If your
code is so deeply nested that it is a big deal, it is already in
desperate need of refactoring.)
Instead of the original proposal to add a "continue" statement to
skip to the next except block:
try:
something()
except HTTPError as ex:
if condition(ex): continue # skip to the next except clause
spam()
except URLError as ex:
ham()
we can do:
try:
something()
except (HTTPError, URLError) as ex:
# Technically, we don't even need to list HTTPError, since it
# is a subclass it will be caught by URLError too.
if type(ex) is URLError or condition(ex):
ham()
else:
spam()
Have I missed any suggested use-cases?
I don't think any of the existing solutions are that awkward or
unpleasant to require new syntax. They're actually quite
straightforward.
--
Steven
More information about the Python-ideas
mailing list