By  Serdar Yegulalp

How to use structural pattern matching in Python

submited by
Style Pass
2021-08-05 16:00:07

By Serdar Yegulalp

Senior Writer, InfoWorld |

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.

Leave a Comment