The new Python match
Diversions
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
-
Thousands of Linux Servers Infected with Stealth Malware Since 2021
Perfctl is capable of remaining undetected, which makes it dangerous and hard to mitigate.
-
Halcyon Creates Anti-Ransomware Protection for Linux
As more Linux systems are targeted by ransomware, Halcyon is stepping up its protection.
-
Valve and Arch Linux Announce Collaboration
Valve and Arch have come together for two projects that will have a serious impact on the Linux distribution.
-
Hacker Successfully Runs Linux on a CPU from the Early ‘70s
From the office of "Look what I can do," Dmitry Grinberg was able to get Linux running on a processor that was created in 1971.
-
OSI and LPI Form Strategic Alliance
With a goal of strengthening Linux and open source communities, this new alliance aims to nurture the growth of more highly skilled professionals.
-
Fedora 41 Beta Available with Some Interesting Additions
If you're a Fedora fan, you'll be excited to hear the beta version of the latest release is now available for testing and includes plenty of updates.
-
AlmaLinux Unveils New Hardware Certification Process
The AlmaLinux Hardware Certification Program run by the Certification Special Interest Group (SIG) aims to ensure seamless compatibility between AlmaLinux and a wide range of hardware configurations.
-
Wind River Introduces eLxr Pro Linux Solution
eLxr Pro offers an end-to-end Linux solution backed by expert commercial support.
-
Juno Tab 3 Launches with Ubuntu 24.04
Anyone looking for a full-blown Linux tablet need look no further. Juno has released the Tab 3.
-
New KDE Slimbook Plasma Available for Preorder
Powered by an AMD Ryzen CPU, the latest KDE Slimbook laptop is powerful enough for local AI tasks.