[Python-ideas] Match statement brainstorm

Michael Selik michael.selik at gmail.com
Mon May 23 22:57:39 EDT 2016

On Mon, May 23, 2016 at 8:23 PM Guido van Rossum <guido at python.org> wrote:

> No, what I'm saying is that seeing it as sugar for exception handing
> is the wrong way to look at it.

Ok, let me refocus on the idea of assign-if-you-can during matching, not
just sugar for try/except.

The matching features of equality, inequality, predicates, and subtype are
already available via if/elif. The matching features of destructuring,
assignment, and post-assignment guards need new syntax. The other proposals
in this thread suggest a new keyword or keyword pair like switch/case.
Instead, why not extend if/elif with a new operator?

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

A major advantage to merging these new matching features with the existing
if/elif is that refactoring gets much easier. One could insert a single
elif block near the top of the chain using the new assign-if-you-can
operator/keyword, without needing to change any of the existing elif

Otherwise, I could imagine someone waffling back and forth between
switch/case and if/elif as they add and remove cases. What would be the
style recommendation if you have 5 boring cases that are all easy to read
via if/elif?

The disadvantage would be that the new syntax wouldn't stand out as much as
it would with, say, switch/case, and someone might not notice its usage. I
think a good choice of operator/keyword mitigates this. A keyword like
``as`` would stand out due to syntax highlighting. An operator like ``?=``
looks different enough and many similar-looking operators, like ``/=``
would be illegal.

Operator precedence would affect the beauty of the code. Giving ``?=`` the
same precedence as ``==`` seems best for post-assignment guards.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160524/10998da2/attachment.html>

More information about the Python-ideas mailing list