Python, for all its power and popularity, has long lacked a form of flow control found in other languages—a way to take a value and match it elegantly against one of a number of possible conditions. In C and C++, it’s the switch/case construction; in Rust, it’s called “pattern matching.”
The traditional ways to do this in Python aren’t elegant. One is to write an if/elif/else chain of expressions. The other is to store values to match as keys in a dictionary, then use the values to take an action—e.g., store a function as a value and use the key or some other variable as input. In many cases this works well, but can be cumbersome to construct and maintain.After many proposals to add a switch/case-like syntax to Python failed, a recent proposal by Python language creator Guido van Rossum and a number of other contributors has been accepted for Python 3.10: structural pattern matching. Structural pattern matching not only makes it possible to perform simple switch/case style matches, but also supports a broader range of use cases.Structural pattern matching introduces the match/case statement and the pattern syntax to Python. The match/case statement follows the same basic outline as switch/case. It takes an object, tests the object against one or more match patterns, and takes an action if it finds a match.
Each case statement is followed by a pattern to match against.
In the above example we’re using simple strings as our match targets, but more complex matches are possible. In fact, the chief use case for structural pattern matching is to match patterns of types, rather than patterns of values.
Python performs matches by going through the list of cases from top to bottom. On the first match, Python executes the statements in the corresponding case block, then skips to the end of the match block and continues with the rest of the program. There is no “fall-through” between cases, but it’s possible to design your logic to handle multiple possible cases in a single case block. (More on this later.)