The creators of the Python language are mulling a new proposal, PEP 622, that would finally bring a pattern matching statement syntax to Python.
The new pattern matching statements would give Python programmers more expressive ways of handling structured data, without having to resort to workarounds.
Pattern matching is a common feature of many programming languages, such as
switch/case in C. It allows one of a number of possible actions to be taken based on the value of a given variable or expression. While Python has lacked a native syntax for pattern matching, it has been possible to emulate it with
if/elif/else chains or a dictionary lookup.
PEP 622 proposes a method for matching an expression against a number of kinds of patterns using a
match something: case 0 | 1 | 2: print("Small number") case  | [_]: print("A short sequence") case str() | bytes(): print("Something string-like") case _: print("Something else")
Supported pattern match types include literals, names, constant values, sequences, a mapping (basically, the presence of a key-value pair in the expression), a class, a mixture of the above, or any of those plus conditional expressions. Any matches that are ambiguous or impossible to resolve will throw an exception at runtime.
Objects can handle match tests by way of a new protocol called the
__match__ protocol. If an object implements the
__match__ method, it can be used to test if it matches a given class pattern and return an appropriate response.
PEP 622 would also allow static type checkers to verify that matches can be verified. A new
@sealed decorator for a class indicates to type checkers that any subclass of the class in question is defined in the same module as the base class.
Previous PEPs to add pattern matching — PEP 275 and PEP 3103, proposed in 2001 and 2006 respectively — were turned down due to lack of popular support. PEP 3103 was drafted by Python creator Guido van Rossum.
The new PEP, authored by van Rossum and several others, aims to provide regular expressions for object matching, rather than just a simple
if/elif/else substitute. The authors note that many aspects of this PEP were inspired by how pattern matching works in Rust and Scala.
How all this would be implemented under the hood is still up for discussion. The implementation proposed in PEP 622 would generate the same bytecode sequences as an
if/elif/else chain. Larger
switch/case blocks could become less performant depending on how much conditional logic was included in each
But the PEP makes it clear that any number of approaches and performance optimisations (e.g., memoization) are still on the table.
Even if the PEP ends up being accepted, a great deal about it might change. One issue that is likely to be challenged is the use of
case _: instead of
else: as a final catch-all clause for the
_ is used as a temporary variable in many contexts, and overriding its behaviour unilaterally could be a turnoff for developers.