[Python-ideas] Match statement brainstorm

Guido van Rossum guido at python.org
Mon May 23 23:43:22 EDT 2016

On Mon, May 23, 2016 at 7:57 PM, Michael Selik <michael.selik at gmail.com> wrote:
> 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
> statements.
> 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.

This idea has some clear advantages -- it's unambiguous about the
order of matching, and combines clearly with existing conditions. It
also seems like it would support "recursive" matching nicely, by
allowing you to chain additional unpacking operators. ("Recursive"
because IIUC that's what Haskell calls matches inside matches --
similar to nested tuple unpackings like (a, (b, c)) = in Python.)

The trick is to find a good syntax for the conditional assignment;
using ? has been rejected by this group in the past for other

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list