# [Python-ideas] Match statement brainstorm

Paul Moore p.f.moore at gmail.com
Thu May 26 15:15:57 EDT 2016

```On 26 May 2016 at 19:21, Nikolaus Rath <Nikolaus at rath.org> wrote:
> I think all the ideas with "as" are difficult to read. I think its much
> better to embed the target variables in the pattern - we just need a way
> to mark them as such.
>
> Mathematica has the same problem and solves it with a trailing _, but we
> can't do that because our variables names may contain them. But maybe we
> could use \$? Most people already strongly associate this with variables.
>
> Example:
>
> given foo
>    case (x,y):
>        # matches if foo == (x,y)
>    case (x, \$y):
>        # matches if len(foo) == 2 and foo[0] == x,
>        # and assigns y = foo[1]
>    case {'bar': \$x, y: \$z}:
>        # matches if foo is a map that has 'bar' and y keys
>        # and assigns x = foo['bar'], z = foo[y]
>    case \$x.bar:
>        # matches if hasattr(foo, 'bar') and assigns x = foo

That's quite a nice idea.I'm not sure whether it feels pythonic to me,
though - I'd be very interested to see whether Guido loves or hates
this.

The "case \$x.bar" example is a bit unfortunate - ideally, after
testing for existence of the attribute, you would want to be able to
name the value of the attribute, not the containing object. Of course
you can access the attribute as x.bar, but that costs an additional
lookup - hardly the end of the world, but not ideal.

Oh, and "given...case" is a pretty nice keyword pair, too. Not a
disastrous clash with a common variable name (like match) and no
pre-existing connotations (like switch). I think it's been mentioned
as a possibility earlier in the thread, but seemed to get lost in the
noise.

Paul
```