Switch statement comes to Python
in Python 3.10
No 15.
You are probably familiar with the switch statement found in C-like languages such as C, C++, C# and Java. The Java version below is typical:
int tval =12;
switch (tval) {
case 2: System.out.println("two");
break;
case 3:
case 12:
System.out.println("3 or 12");
break;
default:
System.out.println("all the rest");
break;
}
Until recently, Python programmers had to write a lot of if statements or try to approximate the switch statement using a dictionary. But, beginning in Python 3.10 (releasing in October, 2021) you can use Python’s new match statement to carry out switch-like functions and a lot more. Match will match simple values, strings and pretty complex patterns. Here’s the above program converted to Python.
tval = 12
match tval:
case 2: # if 2
print("two")
case 3 | 12: # 3 or 12
print("3 or 12")
case _: # anything else
print('all the rest')Note that unlike Java, there are no braces, and you don’t need to end each case with a break statement. You can OR together several values in a single case statement, and the underscore is used in place of default to provide a case for any values that don’t match anything else.
In the same way, but unlike most other languages, you can also match strings:
name = 'fred'
match name:
case 'sam':
print('sam')
case 'fred':
print('fred')
case 'sally':
print('sally forth')Pattern Matching
The match statement can match more complex patterns pretty easily. The descriptions of the patterns must be made up of fixed values, not variables, however.
Let’s consider a simple Point class with internal x and y variables:
class Point:
def __init__(self, x, y):
self.x = x
self.y = yYou can match Points value patterns using an expression that looks much like a constructor:
def location(point):
match point:
case Point(x=0, y=0):
print("Point is at the origin.")
case Point(x=0, y=y):
print(f"Y={y} and the point is on the y-axis.")
case Point(x=x, y=0):
print(f"X={x} and the point is on the x-axis.")
case Point():
print("The point is located somewhere else.")
case _:
print("Not a point")
So, we can create a point and see how it matches:
p = Point(100, 0)
location(p)The resulting match is to the pattern “x=x, y=0” and the program prints out
X=100 and the point is on the x-axis.
This example is drawn from the tutorial on the match statement in the Python 3.10 documentation. You can also look at the extended tutorial in the PEP 636 document.
To try out this new method, you need to download the most recent alpha version of Python 3.10 here.
All code can be downloaded from GitHub under jameswcooper/newsletter.
Subscribe to this newsletter so you don’t miss a single Monday’s issue!
