Structural Pattern Matching Comes to Python 3.10.0

Introduction

Python 3.10.0 is the next minor version of Python and is expected to drop on October 4, 2021. This update will bring a big addition to the core syntax: structural pattern matching, which was proposed in PEP 634.

You could say that structural pattern matching adds a sort of switch statement to Python, but that isn’t entirely accurate. Pattern matching does much more.

For instance, take an example from PEP 635. Suppose you need to check if an object x is a tuple containing host and port information for a socket connection and, optionally, a mode such as HTTP or HTTPS.

You could write something like this using an if…elif…else block:

if isinstance(x, tuple) and len(x) == 2:
    host, port = x
    mode = "http"
elif isinstance(x, tuple) and len(x) == 3:
    host, port, mode = x
else:
    # Etc…

Python’s new structural pattern matching allows you to write this more cleanly using a match statement:

match x:
    case host, port:
        mode = "http"
    case host, port, mode:
        pass
    # Etc…

match statements check that the shape of the object matches one of the cases and binds data from the object to variable names in the case expression.

Not everyone is thrilled about pattern matching, and the feature has received criticism from both within the core development team and the wider community.

In the acceptance announcement, the steering council acknowledged these concerns while also expressing their support for the proposal:

We acknowledge that Pattern Matching is an extensive change to Python
and that reaching consensus across the entire community is nearly
impossible.

Different people have reservations or concerns around different
aspects of the semantics and the syntax (as does the Steering Council).

In spite of this, after much deliberation, … we are confident that
Pattern Matching as specified in PEP 634, et al, will be a great
addition to the Python Language. (`Source <https://lwn.net/Articles/845480/>`_)

Although opinions are divided, pattern matching is coming to the next Python release.

You can learn more about how pattern matching works by reading the tutorial in PEP 636.

structural-pattern-matching

../../../_images/pattern_matching.png

https://realpython.com/python310-new-features/#structural-pattern-matching