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
-
Canonical Bumps LTS Support to 12 years
If you're worried that your Ubuntu LTS release won't be supported long enough to last, Canonical has a surprise for you in the form of 12 years of security coverage.
-
Fedora 40 Beta Released Soon
With the official release of Fedora 40 coming in April, it's almost time to download the beta and see what's new.
-
New Pentesting Distribution to Compete with Kali Linux
SnoopGod is now available for your testing needs
-
Juno Computers Launches Another Linux Laptop
If you're looking for a powerhouse laptop that runs Ubuntu, the Juno Computers Neptune 17 v6 should be on your radar.
-
ZorinOS 17.1 Released, Includes Improved Windows App Support
If you need or desire to run Windows applications on Linux, there's one distribution intent on making that easier for you and its new release further improves that feature.
-
Linux Market Share Surpasses 4% for the First Time
Look out Windows and macOS, Linux is on the rise and has even topped ChromeOS to become the fourth most widely used OS around the globe.
-
KDE’s Plasma 6 Officially Available
KDE’s Plasma 6.0 "Megarelease" has happened, and it's brimming with new features, polish, and performance.
-
Latest Version of Tails Unleashed
Tails 6.0 is based on Debian 12 and includes GNOME 43.
-
KDE Announces New Slimbook V with Plenty of Power and KDE’s Plasma 6
If you're a fan of KDE Plasma, you'll be thrilled to hear they've announced a new Slimbook with an AMD CPU and the latest version of KDE Plasma desktop.
-
Monthly Sponsorship Includes Early Access to elementary OS 8
If you want to get a glimpse of what's in the pipeline for elementary OS 8, just set up a monthly sponsorship to help fund its continued existence.