-
-
Notifications
You must be signed in to change notification settings - Fork 33
For SC consideration: PEP 642, Explicit Patterns for Structured Pattern Matching #43
Copy link
Copy link
Closed
Description
The version being submitted is the 3rd posted version.
Now that I've submitted it, I'll still make changes in response to SC feedback, and fix any notable flaws that come up in community review, but it won't see the kinds of major design changes that happened between v1/v2/v3
The PEP itself contains a list of major changes relative to PEP 634, so I won't repeat that here.
Instead I'll summarise the parts that I consider most important:
- ensuring that all "binding to the right" operations use the
askeyword. This drove changes to both mapping patterns and class patterns. - explicitly qualifying both name bindings and value constraints with
as,==, oris. This change is the one that makes it possible to make pattern matching available to users without having to resolve the thorny questions of what bare names and attribute references should do by default. It also opens up the possibility of potentially adding more value constraint options later (likein,is not, and!=) if those operations seem sufficiently compelling to be worth adding. - explicitly decoupling sequence pattern matching from iterable unpacking. The change to require qualification of name binding operations already breaks the alignment between the two, and that created an opportunity to simplify the grammar by only allowing square bracket based sequence patterns and eliminating both open sequence patterns and parenthesis based sequence patterns
- changing class patterns to draw more of their syntactic inspiration from mapping patterns rather than from class instantiation
- explicitly representing patterns in the AST, rather than treating patterns as pseudo-expressions all the way through to the code generation layer. Skipping this step makes the code fragile and hard to follow, as there isn't actually any point in the AST that accepts both expressions and patterns, but with pattern parsing reusing expression nodes, you can't tell from just looking at the AST which nodes expect subexpressions and which expect subpatterns. Even if PEP 634's surface syntax ends up being accepted over this PEP, the explicit AST change should still be made to the implementation before it is merged.
And quote the example match statement from the abstract:
port = DEFAULT_PORT
match expr:
case [as host, as port]:
pass
case {"host" as host, "port" as port}:
pass
case {"host" as host}:
pass
case object{.host as host, .port as port}:
pass
case object{.host as host}:
pass
case str{} as addr:
host, __, optional_port = addr.partition(":")
if optional_port:
port = optional_port
case __ as m:
raise TypeError(f"Unknown address format: {m!r:.200}")
port = int(port)
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels