[Python-ideas] Match statement brainstorm

Greg Ewing greg.ewing at canterbury.ac.nz
Thu May 19 04:20:04 EDT 2016

Guido van Rossum wrote:
> def demo(arg):
>     switch arg:
>         case (x=p, y=q): print('x=', p, 'y=', q)
>         case (a, b, *_): print('a=', a, 'b=', b)
>         else: print('Too bad')

I would also add

           case Point(x=p, y=q): print('Point: x=', p, 'y=', q)

Then if you also had

    Vector = namedtuple('x,y,z')

then this case would match a Point but not a Vector.

However, there's a problem with all this if you want to
allow matching on specific values as well as structure.
Haskell allows you to say things like

    myfunc [17, 42, x] = ...

which will only match a 3-element list whose first 2
elements are 17 and 42.

This would be fine in Python as long as the constants are
literals. But if you want to name the constants,

    Seventeen = 17
    FortyTwo = 42

       case [Seventeen, FortyTwo, x]:

it becomes ambiguous. Are the identifiers values to be
matched or names to be bound?

If we want this feature, it seems like we will need to
explicitly mark either names to be bound or expressions to
be evaluated and matched against.

At first I thought maybe a name could be enclosed in parens
to force it to be treated as an expression:

       case [(Seventeen), (FortyTwo), x]:

but that wouldn't quite be consistent with assignment
syntax, because (x) is actually valid on the left of an
assignment and is equivalent to just x.

> a= h b= o
> (Note the slightly unfortunate outcome for 'hola',

If you wanted the second case to only match the tuple,
you could write

       case tuple(a, b, *_):


More information about the Python-ideas mailing list