[Python-ideas] Match statement brainstorm

Nick Coghlan ncoghlan at gmail.com
Wed May 25 04:41:25 EDT 2016

On 25 May 2016 at 16:35, Michael Selik <michael.selik at gmail.com> wrote:
> On Wed, May 25, 2016 at 2:26 AM Greg Ewing <greg.ewing at canterbury.ac.nz>
> wrote:
>> My feeling is that the patterns should look like
>> constructors. The archetypal constructor for a mapping
>> object is the dict display, so a pattern that matches
>> a mapping having particular keys would be
>>     case {"x": p, "y": q}:
> This is starting to look really good to me. But if that's valid in a case
> statement, why not in a regular assignment?
>     (a, b, *rest) = sequence
>     {'x': p, 'y': q, **rest} = mapping

Aye, I'm warming to that as a syntax for item unpacking (although I'm
not sold on the "**rest" notation, since that entails doing something
like "{k: v for k, v in obj.items() if k not in explicit_keys}" to
populate it, further elevating "items()" towards the status of being a
protocol method without double-underscores)

I also agree with the principle that any prospective structural
pattern matching statement should align with assignment target

Unfortunately, we don't have anything like dictionary displays to
inform possible structures for an implied getattribute as part of
assignment to a particular target. The option I dislike least so far
is :

    (p=.x, q=.y) = obj # Attribute unpacking

Which is clearly distinct from:

    (p, q) = obj # Iterable unpacking
    {0: p, 1: q} = obj # Item unpacking
    {'x': p, 'y': q} = obj # Item unpacking

However, at this point we've strayed a *long* way from the ideal of
"executable pseudocode" :(

It would be slightly more readable if the new unpacking options used
"from" as their assignment keyword rather than the traditional "=":

    (p=.x, q=.y) from obj # Attribute unpacking
    {0: p, 1: q} from obj # Item unpacking
    {'x': p, 'y': q} from obj # Item unpacking


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

More information about the Python-ideas mailing list