Structural Pattern Matching in Python 3.10 !!

shoaib akhtar
3 min readJun 16, 2021

--

Source : https://www.python.org/community/logos/

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) :

if-elif-else Ladder (Python 3.9)

Look at the same piece of logic using match-case in Python 3.10 :

match-case (Python 3.10)

Another thing to notice, is the usage of | which makes it possible to combine multiple literals using | (or) operator :

match-case with multiple literals (Python 3.10)

But the new pattern matching also brings some extra features, such as matching of complex patterns :

Complex pattern matching (Python 3.10)

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 :

Structural Pattern Matching (Python 3.10)

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 !

Source : https://unsplash.com/photos/fvpgfw3IF1w?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink

--

--