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
Direct Download
Read full article as PDF:
Price $2.95
News
-
The 14" Pinebook Pro Linux Laptop is Shipping
After a considerable delay, the 14" version of the Pinebook Pro laptop is, once again, available for purchase.
-
OpenMandriva Lx ROME Technical Preview Released
OpenMandriva’s rolling release distribution technical preview has been released for testing purposes and adds some of the latest/greatest software into the mix.
-
Linux Mint 21 is Now Available
The latest iteration of Linux Mint, codenamed Vanessa, has been released with a new upgrade tool and other fantastic features.
-
Firefox Adds Long-Anticipated Feature
Firefox 103 has arrived and it now includes a feature users have long awaited…sort of.
-
System76 Refreshes Their Popular Oryx Pro Laptop with a New CPU
The System76 Oryx Pro laptop has been relaunched with a 12th Gen CPU and more powerful graphics options.
-
Elive Has Released a New Beta
The Elive team is proud to announce the latest beta version (3.8.30) of its Enlightenment-centric Linux distribution.
-
Rocky Linux 9 Has Arrived
The latest iteration of Rocky Linux is now available and includes a host of new features and support for new architecture.
-
Slimbook Executive Linux Ultrabook Upgrading Their CPUs
The Spanish-based company, Slimbook, has made available their next generation Slimbook Executive Linux ultrabooks with a 12th Gen Intel Alder Lake CPU.
-
Fedora Linux is Coming to the Raspberry Pi 4
Thanks to significant work in the upstream, the upcoming release of Fedora 37 will introduce support for the Raspberry Pi 4.
-
New Linux Ultrabook from TUXEDO Computers
TUXEDO Computers has released a new 15" Ultrabook running Linux.