[Python-ideas] PEP-3151 pattern-matching

MRAB python at mrabarnett.plus.com
Sat Apr 9 01:29:45 CEST 2011


On 08/04/2011 18:56, Guido van Rossum wrote:
> On Fri, Apr 8, 2011 at 10:52 AM, Mike Graham<mikegraham at gmail.com>  wrote:
>> On Fri, Apr 8, 2011 at 1:11 PM, Guido van Rossum<guido at python.org>  wrote:
>>> With apologies for not reading the PEP or this thread in full, some comments:
>>>
>>> - I really like the syntax "except<exc>  [as<var>] [if<test>]:".
>>> This addresses a pretty common use case in my experience. I don't care
>>> for the alternate proposed syntax that started this thread. I'm not
>>> sure that the 'if' subclause makes sense without the 'as' subclause,
>>> since most likely you'd want to refer to the caught exception. I note
>>> that it is more powerful than putting "if not<test>: raise" in the
>>> body of the except-clause, because it will allow subsequent except
>>> clauses to match still. I also note that it is a much "cleaner" change
>>> than (again) reorganizing the exception hierarchy, since there is no
>>> backward compatibility to consider.
>>
>> Of course, multiple cases can currently be handled by an if statement
>>
>> except Foo as e:
>>     if e.bar == baz:
>>         ...
>>     elif e.bar == qux:
>>         ...
>>     else:
>>         raise
>>
>> This code isn't so bad: it's not hard to understand, it's an existing
>> pattern, it uses general, powerful constructs.
>
> The problem (as I tried to say, but apparently not clearly enough) is
> that if there's a later more general except clause on the same block
> it won't work. E.g.
>
> except Foo as e:
>    <code as above>
> except Exception:
>    <log traceback>
>
> The 'raise' in your code above does not transfer control to the
> "except Exception:" clause. The current solution is either to have two
> nested try/except blocks, or duplicate the logging code; neither is
> great.
>
[snip]
Unless you have something like "continue except", which means "continue
checking the following 'except' clauses".



More information about the Python-ideas mailing list