[Python-ideas] Match statement brainstorm

Nick Coghlan ncoghlan at gmail.com
Tue May 24 00:35:51 EDT 2016

On 24 May 2016 at 13:43, Guido van Rossum <guido at python.org> wrote:
> On Mon, May 23, 2016 at 7:57 PM, Michael Selik <michael.selik at gmail.com> wrote:
>> 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
> conditionalisms.

I don't think we've ever considered it specifically in the context of
a "maybe-assign" expression, though.

While such a conditional assignment syntax does sound appealing as a
way to do runtime pattern matching, one key concern I'd have with it
would be how it's defined in the case of a "can't fail" assignment to
a single variable:

    if x ?= re.match(pattern, text):
        # Can x be None here?

    while x ?= expr():
        # Can x be any non-truthy expression here?

Assuming binding to a name was a "can't fail" operation that always
returned either "True" or the LHS as a tuple (so assigning to a single
name resulted in a 1-tuple, while only a failed assignment resulted in
an empty tuple), then the correct spelling for those operations would

    if x ?= re.match(pattern, text) and x is not None:
        # x is definitely not None here

    while x ?= expr() and x:
        # x is always truthy

The other tricky problem would be defining precisely how exception
handling worked on the RHS. For iterable unpacking, clearly the
TypeError from the implicit iter() call would be suppressed (if
thrown), as would errors related to mismatches between the number of
items and the number of unpacking targets, but catching arbitrary
AttributeErrors from the RHS to support conditional attribute based
destructuring assignment would be problematic. That suggests to me
that some kind of explicit syntax for attribute based destructuring
may still be needed to avoid overbroad suppression of exceptions.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list