PEP 622 – Structural Pattern Matching | peps.python.org
PEP 622 – Structural Pattern Matching PEP 622 – Structural Pattern Matching Author : Brandt Bucher <brandt at python.org>, Daniel F Moisset <dfmoisset at gmail.com>, Tobias Kohn <kohnt at tobiaskohn.ch>, Ivan Levkivskyi <levkivskyi at gmail.com>, Guido van Rossum <guido at python.org>, Talin <viridia at gmail.com> BDFL-Delegate : Discussions-To : Python-Dev list Status : Superseded Type : Standards Track Created : 23-Jun-2020 Python-Version : 3.10 Post-History : 23-Jun-2020, 08-Jul-2020 Superseded-By : 634 Table of Contents Abstract Patterns and shapes Syntax Motivation Overview Pattern, a new syntactic construct, and destructuring Matching process Rationale and Goals Syntax and Semantics Patterns The match statement Match semantics Allowed patterns Literal Patterns Capture Patterns Wildcard Pattern Constant Value Patterns Sequence Patterns Mapping Patterns Class Patterns Combining multiple patterns (OR patterns) Guards Walrus patterns Runtime specification The Match Protocol Overlapping sub-patterns Special attribute __match_args__ Exceptions and side effects The standard library Static checkers specification Exhaustiveness checks Sealed classes as algebraic data types Type erasure Note about constants Precise type checking of star matches Performance Considerations Backwards Compatibility Impacts on third-party tools Reference Implementation Example Code Rejected Ideas Don’t do this, pattern matching is hard to learn Don’t do this, use existing method dispatching mechanisms Allow more flexible assignment targets instead Make it an expression Use a hard keyword Use as or | instead of case for case clauses Use a flat indentation scheme Alternatives for constant value pattern Disallow float literals in patterns Range matching patterns Use dispatch dict semantics for matches Use continue and break in case clauses.
AND ( & ) patterns Negative match patterns Check exhaustiveness at runtime Type annotations for pattern variables Allow *rest in class patterns Disallow _.a in constant value patterns Use some other token as wildcard Use some other syntax instead of | for OR patterns Add an else clause Deferred Ideas One-off syntax variant Other pattern-based constructions Algebraic matching of repeated names Custom matching protocol Parameterized Matching Syntax Pattern Utility Library Acknowledgments Version History References Appendix A – Full Grammar Copyright Abstract This PEP proposes to add a pattern matching statement to Python, inspired by similar syntax found in Scala, Erlang, and other languages.
Patterns and shapes The pattern syntax builds on Python’s existing syntax for sequence unpacking (e.g., a, b = value ). A match statement compares a value (the subject ) to several different shapes (the patterns ) until a shape fits. Each pattern describes the type and structure of the accepted values as well as the variables where to capture its contents. Patterns can specify the shape to be: a sequence to be unpacked, as already mentioned a mapping with specific keys an instance of a given class with (optionally) specific attributes a specific value a wildcard Patterns can be composed in several ways.
Syntax Syntactically, a match statement contains: a subject expression one or more case clauses Each case clause specifies: a pattern (the overall shape to be matched) an optional “guard” (a condition to be checked if the pattern matches) a code block to be executed if the case clause is selected Motivation The rest of the PEP: motivates why we believe pattern matching makes a good addition to Python explains our design choices contains a precise syntactic and runtime specification gives guidance for static type checkers (and one small addition to the typing module) discusses the main objections and alternatives that have been brought up during extensive discussion of the proposal, both within the group of authors and in the python-dev community Finally, we discuss some possible extensions that might be considered in the future, once the community has ample experience with the currently proposed syntax and semantics.
Overview Patterns are a new syntactical category with their own rules and special cases. Patterns mix input (given values) and output (captured variables) in novel ways. They may take a little time to use effectively. The authors have provided a brief introduction to the basic concepts here. Note that this section is not intended to be complete or entirely accurate. Pattern, a new syntactic construct, and destructuring A new syntactic construct called pattern is introduced in this PEP.
Syntactically, patterns look like a subset of expressions. The following are examples of patterns: [first, second, *rest] Point2d(x, 0) {"name": "Bruce", "age": age} 42 The above expressions may look like examples of object construction with a constructor which takes some values as parameters and builds an object from those components. When viewed as a pattern, the above patterns mean the inverse operation of construction, which we call destructuring .
Destructuring takes a subject value and extracts its components. The syntactic similarity between object construction and destructuring is intentional. It also follows the existing Pythonic style of contexts which makes assignment targets (write contexts) look like expressions (read contexts). Pattern matching never creates objects. This is in the same way that [a, b] = my_list doesn’t create a new [a, b] list, nor reads the values of a and b .
Matching process During this matching process, the structure of the pattern may not fit the subject, and matching fails . For example, matching the pattern Point2d(x, 0) to the subject Point2d(3, 0) successfully matches. The match also binds the pattern’s free variable x to the subject’s value 3 . As another example, if the subject is [3, 0] , the match fails because the subject’s type list is not the pattern’s Point2d .
As a third example, if the subject is Point2d(3, 7) , the match fails because the subject’s second coordinate 7 is not the same as the pattern’s 0 . The match statement tries to match a single subject to each of the patterns in its case clauses. At the first successful match to a pattern in a case clause: the variables in the pattern are assigned, and a corresponding block is executed. Each case clause can also specify an optional boolean condition, known as a guard .
Let’s look at a more detailed example of a match statement. The match statement is used within a function to define the building of 3D points. In this example, the function can accept as input any of the following: tuple with 2 elements, tuple with 3 elements, an existing Point2d object or an existing Point3d object: def make_point_3d ( pt ): match pt : case ( x , y ): return Point3d ( x , y , 0 ) case ( x , y , z ): return Point3d ( x , y , z ) case Point2d ( x , y ): return Point3d ( x , y , 0 ) case Point3d ( _ , _ , _ ): return pt case _ : raise TypeError ( "not a point we support" ) Without pattern matching, this function’s implementation would require several isinstance() checks, one or two len() calls, and a more convoluted control flow.
The match example version and the traditional Python version without match translate into similar code under the hood. With familiarity of pattern matching, a user reading this function using match will likely find this version clearer than the traditional approach. Rationale and Goals Python programs frequently need to handle data which varies in type, presence of attributes/keys, or number of elements. Typical examples are operating on nodes of a mixed structure like an AST, handling UI events of different types, processing structured input (like structured files or network messages), or “parsing” arguments for a function that can accept different combinations of types and numbers of parameters.
In fact, the classic ‘visitor’ pattern is an example of this, done in an OOP style – but matching makes it much l
The rest of this page is on the live site.