The new Python match
Diversions

© Lead Image © saracorso, 123rf.com
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].
Switcheroo
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" ) else: 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
example1.py
01 class Point3D: 02 x = 0 03 y = 0 04 z = 0 05 __match_args__ = ( "x" , "y" , "z" ) 06 07 def __init__ ( self , x , y , z ): 08 self.x = x 09 self.y = y 10 self.z = z 11 12 def print ( self ): 13 print ( "3D Point ( {0} , {1} , {2} )".format ( self.x , self.y , self.z ) ) 14 15 class Point2D: 16 x = 0 17 y = 0 18 __match_args__ = ( "x" , "y" ) 19 20 def __init__ ( self , x=None , y=None ): 21 self.x = x 22 self.y = y 23 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 34 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 ) ) 40 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
(incl. VAT)
Buy Linux Magazine
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.
News
-
The GNU Project Celebrates Its 40th Birthday
September 27 marks the 40th anniversary of the GNU Project, and it was celebrated with a hacker meeting in Biel/Bienne, Switzerland.
-
Linux Kernel Reducing Long-Term Support
LTS support for the Linux kernel is about to undergo some serious changes that will have a considerable impact on the future.
-
Fedora 39 Beta Now Available for Testing
For fans and users of Fedora Linux, the first beta of release 39 is now available, which is a minor upgrade but does include GNOME 45.
-
Fedora Linux 40 to Drop X11 for KDE Plasma
When Fedora 40 arrives in 2024, there will be a few big changes coming, especially for the KDE Plasma option.
-
Real-Time Ubuntu Available in AWS Marketplace
Anyone looking for a Linux distribution for real-time processing could do a whole lot worse than Real-Time Ubuntu.
-
KSMBD Finally Reaches a Stable State
For those who've been looking forward to the first release of KSMBD, after two years it's no longer considered experimental.
-
Nitrux 3.0.0 Has Been Released
The latest version of Nitrux brings plenty of innovation and fresh apps to the table.
-
Linux From Scratch 12.0 Now Available
If you're looking to roll your own Linux distribution, the latest version of Linux From Scratch is now available with plenty of updates.
-
Linux Kernel 6.5 Has Been Released
The newest Linux kernel, version 6.5, now includes initial support for two very exciting features.
-
UbuntuDDE 23.04 Now Available
A new version of the UbuntuDDE remix has finally arrived with all the updates from the Deepin desktop and everything that comes with the Ubuntu 23.04 base.