Structural Pattern Matching in Python 3.10 !!
As a Data Engineer, the most fascinating update introduced in Python 3.10 is Structural Pattern Matching, a very powerful feature for complex data comparison and processing. This will add case
statement that we all know from other programming languages like c#. We all know how to use case
statement, but considering that this is Python - it's not just plain switch/case syntax, but it also adds some powerful features along with it that we should explore.
A simple match-case reduces the complexity created by if-elif-else ladder. For example:
(PS- Python 3.10, being a beta release, is not easily available in Jupyter notebook, hence we will be using IDLE as of now) :
Look at the same piece of logic using match-case in Python 3.10 :
Another thing to notice, is the usage of |
which makes it possible to combine multiple literals using |
(or) operator :
But the new pattern matching also brings some extra features, such as matching of complex patterns :
The best feature (kept aside for the climax :P), not only allows us to perform the same match-case logic, but based on whether the structure of our comparison object matches a given pattern.
In the following snippet, we are going to match the patterns of two dictionaries :
Closing Thoughts : The final stable Python 3.10 release in expected somewhere around October 2021. Till the time, the official change release page can be checked time to time for any additions (mostly bug fixes).
Thank You !