[Python-ideas] Match statement brainstorm

Greg Ewing greg.ewing at canterbury.ac.nz
Wed May 25 01:58:17 EDT 2016


Michael Selik wrote:
> I fail to see 
> why ``case ... as ...`` would be restrictive and ``if ... ?= ...`` would 
> not. They could have the same semantics, catching either a specific set 
> of exceptions or all/most exceptions.

The difference is not which exceptions get caught,
it's the size of the region of code around which
the catching occurs.

When I see

    if x, y ?= arg.a, arg.b:
       do_stuff()

it suggests that something like this is going on:

    try:
       temp = arg.a, arg.b
    except AttributeError:
       pass
    else:
       x, y = temp
       do_stuff()

Whereas the implementation I had in mind for

    switch arg:
       case (a = x, b = y):
          do_stuff()

would be more like

    if hasattr(arg, "a") and hasattr(arg, "b"):
       x = arg.a
       y = arg.b
       do_stuff()

They're equivalent if the only things you have on
the RHS are attribute accesses, but not if the RHS
is something more complicated.

If you're intending to restrict the RHS so that
you're not allowed anything more complicated, I
think that would be weird and suprising.

Another weird and surprising thing, that applies in
either case, is that

    if x, y ?= arg.a, arg.b:
       ...

would *not* be equivalent to

    z = arg.a, arg.b
    if x, y ?= z:
       ...

With the switch/case syntax or something like it,
that issue doesn't arise.

-- 
Greg


More information about the Python-ideas mailing list