How to use structural pattern matching in Python
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.
Author: . [Source Link (*), InfoWorld]