Get Started with Python's Pattern Matching: A Comprehensive Guide
Written on
Chapter 1: Introduction to Pattern Matching
Pattern matching is an integral part of programming that we often encounter in various forms throughout our lives. It is a concept that we’ve been exposed to since childhood, from toys that fit shapes to puzzles and building blocks.
The release schedule for Python 3.10 is set for October this year (2021). Recently, on March 1, 2021, Python 3.10a6, the sixth alpha version, was released, bringing with it the exciting feature of pattern matching.
What is structural pattern matching, you may ask? It’s a novel approach for executing code based on the structure of data. Some of you might have utilized techniques like multiple dispatch or the visitor pattern in the past. While I lean towards function dispatch, pattern matching resonates more with my way of thinking. This concept has its roots in functional programming languages, with Python’s implementation heavily influenced by Scala. Although my experience with Scala is limited, I’ve found similar concepts in languages like Haskell, Erlang, and Elixir, which I have enjoyed using.
Chapter 2: The Basics of Pattern Matching
For those who are new to this concept, it’s essential to understand how pattern matching functions. You might be wondering how it differs from traditional "switch-case" statements prevalent in many C-derived languages. At first glance, it seems similar. However, the real strength of structural pattern matching comes from its ability to go beyond mere value matching. The structural aspect is akin to destructuring syntax, which is used in reverse to emulate object creation. Let’s delve into an example to illustrate this.
The first part of the example demonstrates matching a point at a specific location and extracting variables from it. The syntax allows for reconstructing the original object with the same statement, which is consistent with how destructuring works with iterables.
In a more advanced example, we can see how easily we can create a recursive function. By calling “where_is()” for all points of a triangle, we only invoke it once at the end, illustrating the power of concise and elegant parsers, making complex algorithms more readable. It may take some time to adjust to structural pattern matching, but I believe you will appreciate its elegance once you do.
To further familiarize yourself, I recommend checking out some helpful videos:
Understanding Python: Structural Pattern Matching - This video provides a detailed overview of structural pattern matching in Python.
Pattern Matching in Python? - A discussion that dives deeper into the mechanics of pattern matching in Python.
Chapter 3: Setting Up for Pattern Matching
Let’s focus on getting the alpha version set up so you can start experimenting with structural pattern matching. I use pyenv for managing multiple Python versions effortlessly. You can find installation instructions in its documentation.
After running “pyenv init,” you’ll need to ensure zlib is installed if it’s not already present. For Mac users, you can do this with “brew install zlib.” At the time of this writing, the latest version available on pyenv is still 3.10.0a5. If 3.10.0a6 is available when you check, install it with “pyenv install 3.10.0a6”. If you can’t wait to try out pattern matching, you can opt for the latest developer version with “pyenv install 3.10-dev”.
Now that you have the alpha installed, it’s time to get started. Set your local Python version with either “pyenv local 3.10-dev” or “pyenv local 3.10.0a6”. Launch the Python interpreter by using the “python” command. Congratulations!
Let’s execute a simple example.
Chapter 4: Exploring Docker for Pattern Matching
If you prefer an alternative setup, Gijs Mos (Twitter, LinkedIn) highlighted that the new alpha version is available as a Docker image. This is a great option if you wish to avoid setting up pyenv. I personally favor the Debian buster image, but various distributions can be found on Docker Hub. To start the interpreter in a container, follow the instructions provided.
Chapter 5: Addressing Common Questions
If you have any questions about pattern matching, feel free to ask! Recently, I attended a talk by Daniel Moisett (@dmoisset on Twitter) during the Python Amsterdam Meetup on March 10, 2021. He’s one of the authors behind the pattern matching PEP trilogy, and I highly recommend watching the entire talk if you're interested in a deeper understanding.
One of the questions he addressed was why pattern matching is not permitted in overloaded function definitions, which involve multiple definitions of the same function, with dispatch managed by argument patterns. His explanation made perfect sense: introducing pattern matching itself is a significant change, and it’s prudent to implement it minimally before considering additional features. While it’s not impossible to include pattern matching in function definitions later, it’s wise to wait until there’s sufficient demand.
Another intriguing question was about the absence of an “else” clause in pattern matching. The reasoning for this is that there was considerable debate about whether it should align with the match statement or the case level. The wildcard and “don’t care” patterns already provide coverage for this scenario, allowing for its omission for now, with the possibility of inclusion in future Python versions.
The Python philosophy emphasizes thoughtful feature implementation, ensuring that new additions enhance functionality without causing regret later on. The current focus is on releasing pattern matching to the community and observing its practical applications.
Chapter 6: Further Learning Resources
To further your understanding, I recommend starting with the official tutorial, PEP 636. For more detailed insights, you can explore the formal specifications in PEP 634 and the motivations behind it in PEP 635. If this article resonates well, I plan to publish a follow-up, so stay tuned for updates. There’s even a possibility of delivering a talk at a future PyCon.
If you're interested in enterprise workshops, lectures, or freelance consulting, feel free to reach out to me at Hultnér Technologies!