match-notes
September 13, 2023
1 Match (Structural Pattern Matching in Python )
1.0.1 Introduction
• It is similar to switch case in C or java but more powerful
• It can match patterns than just direct match
• It supports traditional matching to a number, string, value
• In single ‘case’ supports use of OR (|) operator to select one of the given patterns
• In ‘case’ it allows to capture input pattern in a variable. This variable can be further used in
the program
• In ‘case’ pattern captured in variable, then it can have guard condition (if condition) for error
checking
• Pattern containing multiple values like lists , tuple ,etc can be matched
• Pattern with multiple values can have variable number of values and ‘case’ can extract only
relevent values from the complete values coming in the pattern
• Patterns of custom objects can be matched
• Patterns of dictionary type can also be matched here
• Limitation : Match doesn’t support set based patterns
We will discuss each point in details
1.0.2 Similarity of match and switch case
• Syntax of mtach statement is much similar to switch case
• It has ‘match’ and ‘case’ keywords
• There is no need of ‘break’ inside match
• It has optional case with wildcard (case _:). This case can match any pattern. It should be
kept at the end.
Syntax
[ ]: match <input_pattern>:
case <pattern1>:
<statements>
case <pattern2>:
<statements>
case _: # Wildcard case
<statements>
1
Example
[ ]: match num:
case 1:
print("One")
case 2:
print("two")
case _:
print("Anything else than 1 and 2")
1.0.3 match supports traditional matching to a number, string, value
• In match simplest pattern can be of single integer , float, or string like traditional switch case
in C or java
Example
[ ]: match operation:
case "add":
print("Adding two numbers")
case "sub":
print("Subtracting two numbers")
case "mult":
print("Multiplying two numbers")
case "div":
print("Dividing two numbers")
1.0.4 Single case with OR (|)
• In match single case can check multiple patterns using OR (|). Any one of the pattern matched
then that case will be executed
Example
[ ]: match age:
case "kid":
print("Be dependent full time")
case "young" | "adult":
print("Be independent with dependence")
case "old":
print("Again dependent!")
1.0.5 Pattern containing multiple values like lists , tuple ,etc can be matched
• Match allows sequences to be taken as a pattern
• Sequence in python can be list ( like array), tuple, set, dictionary
• Each case can have different type and number of input values to be matched
• NOTE: if case has fixed values then order of values needs to be maintained!
2
Example
[ ]: itemid_list=[101,105]
match itemid_list:
case [101,105,110]:
print("Three ids discounted order")
case [101,105]:
print("Two ids Discounted order")
case _:
print("Everything else")
1.0.6 Capture input pattern in a variable
• Case can capture part of pattern in a variable
• For pattern with multiple values, multiple variables can be used
• Its like unpacking of sequence to variables ( will be explained in further topics of list and
tuples)
Example
[ ]: # vals=[0,90]
# vals=[23,0]
# vals=[90,40]
vals=[1,255,30]
# vals=[1,2,3,4,5,6]
match vals:
case [0,num2]:
print("First num is 0")
case [num1,0]:
print("Second num is 0")
case [num1, num2]:
print("Calculator Addition ", num1+num2)
case num1,num2,num3: # <-- Observe square brakets NOT given, still Works!
if (num1 < num2 < num3):
print(num3, " is highest")
if (num1 > num2 > num3):
print(num1, " is highest")
if (num1 < num2 > num3):
print(num2, " is highest")
case _:
print("Menu: 2 numbers then calculation , 3 numbers then find the highest")
Another example (from the documentation)
[ ]: # point is an (x, y) tuple
point=(0,0)
# point=(0,5)
# point=(90,0)
3
# point=(99,34)
match point:
case (0, 0):
print("Origin")
case (0, y):
print("Y=",y)
case (x, 0):
print("X=",x)
case (x, y):
print("X=",x, "Y=",y)
case _:
raise ValueError("Not a point")
1.0.7 Guard condition (if condition) for error checking
• When pattern is captured in one or more variables then we can use guard condition
• Gaurd condition means if condition
• When this condition is true ONLY then case is executed else execution goes to the next case
[ ]: # number="9890717884"
number="12.12.10.10"
match number:
case mob if (len(mob) == 10) and mob.isdigit():
print("Valid mobile no, without country code")
case mob if(len(mob) == 13) and mob[0] =='+' and mob[1:].isdigit():
print("Valid mobile no, with country code")
case ip if (len(ip)>=7)and (ip.count(".") ==3):
print("number is similar to an ip address")
case _:
print("Enter valid mobile no or ip address!")
1.0.8 ‘case’ can extract relevent values from the complete values coming in the pattern
• When sequence like list,tuple, etc is passed then relevant values can be extracted and other
values can be captured as extra
• relevant values can be – all at starting positions – all at ending positions – few at starting
and few at end positions
Example
[ ]: # message="thank you for your services!"
message="It was nice experience, thank you"
match message.split(): # get list of words from the string
case [w1,w2,*_] if (w1 =='thank') and (w2 =='you'):
print("You are welcome!, we would be happy to help futher")
case [*_,w1,w2] if (w1 =='thank') and (w2 =='you'):
print("You are welcome!, we would be happy to help futher")
case _:
4
print("we would be happy to help futher, thank you")
1.0.9 match can be used to identify type of object and find right case for it
• match can work to ientify type and according perform operation
Example
Given list of values, Take one value from list at a time if value is integer or float then add it to
total, if value is string then concat to name , else print message cannot handle value
[ ]: vals=[1,2.1,'i',3,'a',56,'cs',4.4,'d']
total=0
name=""
for value in vals:
match value:
case int() | float():
total +=value
case str():
name += value
print("total is",total)
print("name is ", name)
total is 66.5
name is iacsd
1.0.10 match can be used for custom (user defined) objects
• In python user can create classes and create custom objects -match supports patterns of such
custom objects as well
Example from the documentation
[ ]: class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# point = Point(10,10)
point = Point(10,0)
# point = Point(0,10)
# point = Point(0,0)
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print("On Y-axis, Y=",y)
5
case Point(x=x, y=0):
print("On X axis, X=",x)
case Point():
print("Somewhere else in the coordinate system")
case _:
print("Not a point")
On X axis, X= 10
1.0.11 match on patterns in dictionaries
• dictionaries have key value pairs
• match supports when getting data in key value pairs finding relevant keys and their values is
important
• Using dictionary patterns only mensioned key and values will be selected and all other ele-
ments will be neglected for case
• also we can have guard conditions here
Example
[ ]: # user_details={'name':'ravi','address':'pune','age':34}
user_details={'name':'tanvi','address':'mumbai','age':55}
match user_details:
case {'name':n,'age':a} if a > 50:
print("Important user, ",n)
case {'address':'pune'}: # all other field are not considered in comparison
print("User is from pune")
1.0.12 Limitation : Match doesn’t support set based patterns
In pattern set can’t be used. (Documentation doesn’t mension specific reason for this move)
Example ( It gives Syntax Error!!)
[ ]: set_pattern = {1,2,3}
match set_pattern:
case {1,2,3}: # Syntax error On this line!
print("Set {1,2,3} matched!")
2 Further reference
Python Enhancement proposal (PEP 636) https://peps.python.org/pep-0636/
Documentation https://docs.python.org/3/tutorial/controlflow.html
[ ]: