A PEP 622 Playground

The purpose of this notebook is to facilitate interactive exploration of the proposed new syntax for Structural Pattern Matching in Python 3.10, as described in PEP-622.

This notebook should be run with a kernel that uses a suitable version of Python with support for this PEP's new syntax. We start by making a quick sanity check that we're running at least version 3.10 of Python, if that's not the case you need to check your runtime environment.

Note: If you are new to Jupyter Notebooks, code cells (like the one below) can be executed by typing Shift-Enter inside the cell, or by using the "play" button (right-pointing triangle in the toolbar above).

In [1]:
import sys
assert sys.version_info[:2] >= (3, 10)

With that out of the way, let's introduce a very basic example that illustrates the syntax (and whether the cell below runs cleanly will be a good test that you have the right version of Python installed).

We define a dataclass called Point, and a whereis function that matches points in different parts of the x-y plane:

In [2]:
from dataclasses import dataclass

class Point:
    x: int
    y: int

def whereis(point):
    match point:
        case Point(0, 0):
        case Point(0, y):
        case Point(x, 0):
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

With this definition we can now test various kinds of points:

In [3]:
whereis(Point(1, 0))
In [4]:
whereis(Point(0, 0))
In [5]:
Not a point

Now start playing!

You can explore these ideas further below. The examples directory contains some more sample code that you can run at the terminal (you can open a new terminal with the '+' icon or from the File menu), or you can try your own. The PEP contains full details on the syntax.

In [ ]: