[Python-ideas] Match statement brainstorm

Sven R. Kunze srkunze at mail.de
Thu May 19 18:34:31 EDT 2016

On 19.05.2016 16:46, Ian Kelly wrote:
> On Wed, May 18, 2016 at 10:15 PM, Guido van Rossum <guido at python.org> wrote:
>> I guess the tuple structure matching idea is fairly easy to grasp.

That's true. So, I would love to have more capabilities baked into tuple 
structure matching.

>> The attribute idea would be similar to a duck-type check, though more
>> emphasizing data attributes. It would be nice if we could write a
>> match that said "if it has attributes x and y, assign those to local
>> variables p and q, and ignore other attributes". Strawman syntax could
>> be like this:
>> 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')

However, combining this (the tuple structure matching) with a 
switch-case statement is quite some change to my taste especially 
regarding Python's history with the switch-case statement.

Maybe, that is not necessary and we can introduce more features to tuple 
structure matching like Erlang has without introducing switch-case. I 
think it's more powerful and flexible on its own.

> That the first case would match attributes and not named items seems
> surprising to me. That is, just by looking at it I would have expected
> it to match {'x': 1, 'y': 2}. This feels more in line with the way
> that keyword arguments work, and more consistent with the second case
> in that both would be matching contents of collections.

Maybe, here the .x and .y syntax, which has been proposed previously 
(another with-statement enhancement proposal), could come in handy. This 
would definitely refer to attribute matching. Matching via quotation 
marks (" or ') would rather hint at dictionary keys.


More information about the Python-ideas mailing list