[Python-ideas] Match statement brainstorm

Paul Moore p.f.moore at gmail.com
Tue May 24 04:25:02 EDT 2016


On 24 May 2016 at 07:08, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>> On Mon, May 23, 2016 at 7:57 PM, Michael Selik <michael.selik at gmail.com>
>> wrote:
>>
>>> def demo(arg):
>>>    if p, q ?= arg.x, arg.y:                        # dict structure
>>>    elif x ?= arg.x and isinstance(x, int)          # assignment + guard
>>>    elif a, b, *_ ?= arg:                           # tuple structure
>>>    elif isinstance(arg, Mapping):                  # nothing new here
>
>
> I'm unenthusiastic about this -- the above looks like
> an unreadable mess to me.

Agreed - the ?= operator looks like noise to me. One of the advantages
of a switch/case statement is that it's keyword based, which IMO is
inherently more readable.

If we keep getting sucked into comparisons with "chain of if"
constructs, maybe the problem is that the "switch" keyword is too
strongly associated with that in people's minds? Maybe we could focus
on the fact that it's matching that we're doing and make it a "match"
statement? So

    match expr:
        argspec: xxx
        argspec:
            yyy
        else:
            default

Whether we want to simply make "argspec" do standard tuple unpacking,
or something a little more complex like attribute checking, can be up
for debate. I'm inclined to start small and see if there's any value
in a simple "try various unpackings" construct first.

One big problem with this is that making "match" a keyword would be a
real pain - I bet there's lots of code that uses "match" as a
variable...

Paul


More information about the Python-ideas mailing list