[Python-ideas] PEP-3151 pattern-matching
Mike Graham
mikegraham at gmail.com
Fri Apr 8 19:52:18 CEST 2011
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.
I think the main opposition is "People aren't currently doing this!"
The problem is, introducing the "except...if" syntax doesn't actually
make anyone do it either. I understand that adding syntax can be seen
as a nudge, but I'm skeptical that it's a strong enough one to justify
the cost.
> - Quite independently, I think it is time that we started documenting
> which exceptions are raised from standard APIs. The trick is to avoid
> overdocumenting: there is no point in documenting that everything can
> raise MemoryError or that passing in wildly invalid arguments can
> raise TypeError or AttributeError (and pretty much anything else). But
> the variety of exceptions that may be raised by something like
> urlopen, depending on which layer of the network and I/O stacks
> detects a problem are worth documenting. Maybe this example could even
> be a starting point for a rationalization of some of the exceptions
> involved. (And if we find there are legitimate situations where a
> networking or I/O problem raises a "generic" error such as TypeError
> or AttributeError, those are probably bugs that should be fixed in the
> code.)
I couldn't agree more with this.
Mike
More information about the Python-ideas
mailing list