The new Python match


© Lead Image © saracorso,

© Lead Image © saracorso,

Article from Issue 249/2021

Exploring the new Python match statement, Python's implementation of switch/case.

If you've decided to learn Python [1] and have any experience with other programming languages, you'll quickly notice that the ubiquitous switch statement is nowhere to be found. Soon, though, that will no longer be the case (sort of). Python 3.10 is slated to be released in October 2021 and includes the new match command [2] [3].


The function of switch is akin to trying to find a particular office in an office building. As you walk down the hallway, you look at each door to see if it displays the number or name in which you are interested. When you find it, you stop searching and go inside. In C (and indeed many other languages) switch allows you to compare a value against a set of others (Listing 1).

Listing 1

switch and case in C

01 x=3
02 switch ( x )
03 {
04   case 1:
05   {
06     printf ( "x is 1" );
07   }
08   break;
09   case 2:
10   {
11     printf ( "x is 2" );
12   }
13   break;
14   case 3: printf ( "x is 3" );
15   break;
16   default: printf ( "x is not an expected value" );
17 }

The switch starts the compare operation, with the value you want to check passed in. The sets of curly braces then contain your case statements.

Each case is a value against which to check, so in this example, case 1: says "if the value is 1, run this block of code." The program steps through each case statement until it finds a match and then runs the code inside that block. Here, I've only put in a single print statement, but the code block can contain as many statements as you want. When the program encounters a break, it exits the switch statement, and the program moves on to whatever follows the switch block.

You'll also notice default: near the bottom of the example, which runs if none of the other case statements match. Although not required, if default is not there and no case matches the switch value, your program will move on to whatever follows the switch statement without running anything for that block.

Python match

Until now, Python didn't really have a counterpart to the switch statement, so you had to employ a string of if and elif statements:

x = 3
if x == 1:
  print ( "1" )
elif x == 2:
  print ( "2" )
elif x == 3:
  print ( "3" )
  print ( "Not 1, 2, or 3" )

The same code with match is:

x = 3
match x:
  case ( 1 ):
    print ( "1" )
  case ( 2 ):
    print ( "2" )
  case ( 3 ):
    print ( "3" )
  case _:
    print ( "Not 1, 2 or 3" )

The match x says "here's the value to find." Unlike C, the initial value passed in is not in parentheses, just the case values for comparison. Like anything else in Python, code indented under the case is the block that will be executed, and once a block is executed, the match happens without the need for a break statement.

The case _ statement is Python's default case, and if used, it must be the last case to appear in the match. If none of the other case blocks execute, the case _ block executes before the match completes.

But Wait, There's More!

These examples just scratch the surface of what match can do: It also can check variable types, shapes, and variable definitions. The example in Listing 2 [4] converts two- and three-dimensional points.

Listing 2

01 class Point3D:
02    x = 0
03    y = 0
04    z = 0
05    __match_args__ = ( "x" , "y" , "z" )
07    def __init__ ( self , x , y , z ):
08       self.x = x
09       self.y = y
10       self.z = z
12    def print ( self ):
13       print ( "3D Point ( {0} , {1} , {2} )".format ( self.x , self.y , self.z ) )
15 class Point2D:
16    x = 0
17    y = 0
18    __match_args__ = ( "x" , "y" )
20    def __init__ ( self , x=None , y=None ):
21       self.x = x
22       self.y = y
24 def make3Dpoint ( pt ):
25    match pt:
26       case ( x , y ):
27          return Point3D ( x , y , 0 )
28       case ( x , y , z ):
29          return Point3D ( x , y , z )
30       case Point2D ( x , y ):
31          return Point3D ( x , y , 0 )
32       case Point3D ( _ , _ , _ ):
33          return pt
35 pointList = list()
36 pointList.append ( ( 2 , 3 ) )
37 pointList.append ( ( 2 , 3 , 4 ) )
38 pointList.append ( Point2D ( 2 , 3 ) )
39 pointList.append ( Point3D ( 2 , 3 , 4 ) )
41 for pt in pointList:
42    threeD = make3Dpoint ( pt )
43    threeD.print()

The two classes Point3D and Point2D define three- and two-dimensional points, respectively. The 3D example defines x, y, and z, and the __init__ function accepts these arguments and assigns the incoming variables to their class equivalents.

The __match_args__ in lines 5 and 18 are part of the new proposal. Usually, it will be generated automatically, but because I'm working with an alpha release (see the"Alpha Version" box), I had to define it myself. Here, match finds positional arguments for comparison. Line 5 proposes a tuple of strings that line up with the argument names that __init__ is collecting. Point2D is identical, except all references to z have been removed, and it does not have a print method.

Alpha Version

The examples in this article are based on an alpha release of Python [5]. I specifically installed this version to work with the new match syntax, but it should not be used in production. If you want to install an alpha version for testing on Ubuntu, use the following steps (for other versions, consult your package manager):

sudo add-apt-repository §§ ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.10

When you add the repository, you'll be prompted for your password. The update command updates the package list and includes options from the Python repository added in the previous line. Answer Yes to the final command and the alpha version is installed.

You can find the new version of Python by typing whereis python3.10. I did not add the alpha version to my path, so I had to run it directly with /usr/bin/python3.10.

Alpha versions change daily, might not be fully functional, and could have features changed or removed completely before release, so code at your own risk.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • CardStock

    CardStock provides a simple development environment for building a Python graphical application.

  • Hidden Meaning: Working with Microformats

    Programs aren’t as smart as humans when it comes to interpreting the meaning of web information. If you want to maximize your search rank, you might want to dress up your HTML documents with microformats and microdata.

  • Practical Python in Linux

    We’ll introduce you to Python, an easy-to-learn scripting language, and also help you get started creating your own practical Python scripts.

  • Treasure Hunt

    A geolocation guessing game based on the popular Wordle evaluates a player's guesses based on the distance from and direction to the target location. Mike Schilli turns this concept into a desktop game in Go using the photos from his private collection.

  • Calculating Probability

    To tackle mathematical problems with conditional probabilities, math buffs rely on Bayes' formula or discrete distributions, generated by short Perl scripts.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More