|
|
Log in / Subscribe / Register

"Structural pattern matching" for Python, part 1

"Structural pattern matching" for Python, part 1

Posted Aug 5, 2020 18:43 UTC (Wed) by pj (subscriber, #4506)
Parent article: "Structural pattern matching" for Python, part 1

Yeah, I'm pretty 'sounds okay, but details need work' on this.

The auto-destructuring that confuses assigning a variable with use of variables and forces the use of a leading dot on existing variables is just bad. I like the proposed 'into' syntax much better, though I'd spell it 'as' since that spelling is used by both except clauses and context managers, so there's precedent and familiarity.

Also, how about 'default:' instead of 'else:' for the fall-through case name? `case _` I think is too tied to wildcards, when what you've got is really a pile of expressions, not patterns, and `else` _does_ seem like it should go on the `match` block instead of in the list of cases - but `default` is clearly a case and not part of the match block.

Sums up to the following, which I think is concise but still legible:

match get_point() as p:
    case Point(p.x, 0):
        print("y is zero")
    case Point(0, p.y):
        print("x is zero")
    case Point(0, 0):
        print("origin")
    default:
        print("No zeroes")
and
match get_shape() as s:
    case Line(s.start, s.end) if s.start == s.end:
        print(f"Zero length line at {s.x}, {s.y}")


to post comments

"Structural pattern matching" for Python, part 1

Posted Aug 6, 2020 8:46 UTC (Thu) by Karellen (subscriber, #67644) [Link] (1 responses)

I like it, but couldn't you just use as assignment expression and do:

match p := get_point():

The advantage of case (x, y): is that it will match any tuple and allow you to access the members as x and y, whereas doesn't your syntax only allow you to access structures whose members are already called x and y? Feel like I'm missing something here...

"Structural pattern matching" for Python, part 1

Posted Aug 7, 2020 21:25 UTC (Fri) by NYKevin (subscriber, #129325) [Link]

I interpreted it differently. My understanding of pj's comment was that "p" is not the point you matched against (because then you would just write p = get_point() and skip the entire match statement altogether). Rather, "p" is a generic object whose attributes are populated by the matcher. You could just as easily write "p.foo" and "p.bar" and it would work exactly the same.

Another way to think about it: "p." is a prefix meaning "capture a variable here." If a variable is not prefixed, then it's used as a comparison instead.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds