[Python-ideas] Match statement brainstorm

Greg Ewing greg.ewing at canterbury.ac.nz
Tue May 24 19:03:13 EDT 2016

Michael Selik wrote:
> Which is unreadable: ``if/elif`` keywords or ``?=`` operator?

The whole thing.

> If it's 
> the latter, please don't get hung up on that, as I intended that as a 
> placeholder for whatever operator or keyword is best.

Syntax is an important part of readability, though.
Any alternative syntax for the same semantics would have
to be evaluated for readability on its own merits.

> My main point is 
> that switch/case/matching is semantically identical to if/elif, so why 
> use something different?

But then you say

 > No, using the assign-if-can operator would be syntax error outside of an
 > if/elif, the reverse of how an assign operator is a syntax error inside
 > an if/elif.

So what you're proposing is *not* semantically equivalent
to composing the existing if/elif with a new pattern matching
assignment, which means re-using the existing keywords for
it is misleading.

> The exception-catching expression is not meant to be available in 
> any other context. However, exception-catching is an essential feature 
> to matching via destructuring. I believe it's unavoidable, though 
> *which* exceptions are suppressed could be made more clear.

Perhaps I can elaborate on that a bit. In Guido's original
proposal, you would say something like

    case Foo(a=x, b=y):

to match something of class Foo having attributes a and b.
Implementing that would involve using hasattr() on the
object being matched, or something equivalent. That catches
AttributeError, but only on the particular operation of
testing for the attribute.

Now with your

    x, y ?= arg.a, arg.b

my assumption was that there was nothing special about
the right hand side, so the implementation would have to
just evaluate all of it and catch any AttribteErrors,
KeyErrors, IndexErrors, etc. emanating from it, which is
much looser and prone to catching too much.

But if the right hand side is special, all bets are off
and you'll have to explain exactly what would be allowed
and how to interpret it.


More information about the Python-ideas mailing list