[Python-ideas] Match statement brainstorm

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


On 24 May 2016 at 14:31, Michael Selik <michael.selik at gmail.com> wrote:
> On Tue, May 24, 2016 at 2:08 AM 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.
>
>
> Which is unreadable: ``if/elif`` keywords or ``?=`` operator? 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. My main point is that
> switch/case/matching is semantically identical to if/elif, so why use
> something different?

For me, it's the use of operators (punctuation) plus the fact that the
overall layout doesn't in any way imply to me "I'm looking at *this*
expression. Let's try a sequence of matches..."

The key distinguishing feature for me of a switch/match statement is
that it organises the "flow" of the statement differently from
if/elif. The if/elif chain says "try this, then that, now something
else". There's no implication that the tests are all looking at the
same subject - to spot that, you need to be able to see (from the
layout of the tests) the actual subject item on each line, and the ?=
operator syntax obscures that because "arg" is used differently in
each test.

With a switch statement, however, the subject is stated once, at the
top of the statement. The checks are then listed one after the other,
and they are all by definition checks against the subject expression.
And in fact, for me that's the distinguishing feature of a switch
statement - that it's a series of tests against a single implied
subject. That's also (I suspect) why it's hard to come up with a good
syntax for tests - Python doesn't really do "implied subjects"
anywhere else (explicit is better than implicit and all that).

IMO, "Series of tests against a single expression" is a common enough
pattern to be worth exploring in spite of the fact that it runs
counter to EIBTI. But you may need to be Dutch to understand why :-)

Paul


More information about the Python-ideas mailing list