Match Case Python: New Addition to the Language

Till now, switch-case statements were not present in python. Using if-else statements and dictionary statements were some ways of implementing the switch case structure in python. But with that, the code wasn’t manageable, and even the construction was tedious. That is when the python match case comes in handy.

With the introduction of Python 3.10, several new features were introduced, and one of them was – python match case. The Python match case is similar to the switch case statement, which is recognized as structural pattern matching in python.   

NOTE: The match case structure is available for python version 3.10 and onwards.

Switch Case Structure

The switch control block has similar functionality as that of an if-else ladder. However, writing multiple if statements are not the most effective way of doing so. Instead, by using the switch case statement, we can simply combine them into a single structure.

The switch case statement in a C/C++ program would look something like this:

switch (variable to be evaluated):
{
     case value1 : //statement 1
                   break;

     case value2 : //statement 2
                   break;

     case value_n : //statement n
                    break;

     default:  //default statement
}

Match Case Statement

To implement switch-case like characteristics and if-else functionalities, we use a match case in python. A match statement will compare a given variable’s value to different shapes, also referred to as the pattern. The main idea is to keep on comparing the variable with all the present patterns until it fits into one.

Syntax of Match Case in Python

The match case consists of three main entities :

  • The match keyword
  • One or more case clauses
  • Expression for each case

The case clause consists of a pattern to be matched to the variable, a condition to be evaluated if the pattern matches, and a set of statements to be executed if the pattern matches.

We can write multiple case statements for multiple possibilities for a given variable. Each case statement has a pattern that has to be matched.

The syntax looks something like this:

match variable_name:
            case ‘pattern1’ : //statement1
            case ‘pattern2’ : //statement2
            …            
            case ‘pattern n’ : //statement n

Example of a Match Case Python Statement

Let us further understand the Match Case statement by taking a very simple example.

quit_flag = False
match quit_flag:
    case True:
        print("Quitting")
        exit()
    case False:
        print("System is on") 

Here, we have a variable named quit_flag which we have assigned a Boolean value of False by default. Thus, we have a match case that will compare the patterns with the ‘quit_flag’ variable.

We have two cases for two possible values of quit_flag – True and False. For the first case, if the variable is True, then it will print ‘Quittting’ and execute the exit() function to end the program. In case if it is false, it will just print a statement saying that ‘System is on.’

When the quit_flag value if False, the match case will print ‘System is on’

match case python

If the quit variable is assigned the value ‘True’, then it will print ‘Quitting’ and end the program

example match case python

If we would have used if-else, then it would be a series of the if-else ladder. However, since this match case only has two cases, using if-else would not be too tedious. But what if instead of two cases, we had 20? Then the match case would look more readable and manageable than the if-else ladder.

Also Read | 5 Ways to Check if a String is Integer in Python

Match Case Python for Function Overloading

We can also use structural pattern matching for function overloading in python. With function overloading, we have multiple functions with the same name but with a different signature.

Depending on the case condition, we can access the same function name with different signature values. With function overloading, we can improve the readability of the code.

As of now, python doesn’t support function overloading. The following example can be used to verify it –

Here, we shall be creating a user-defined function name calc() which accepts one argument. If the argument type is an integer, then we will return the square of the number. Else if the argument type is float, then we will return the cube of a number.

def calc(n:int):
	return (n**2)

def calc(n:float):
	return (n**3)  
n = 9.5
is_int = isinstance(n, int)

match is_int:
	case True : print("Square is :",calc(n))
	case False : print("Cube is:", calc(n))

Since the number n is a floating-point number, it will print the cube of the variable.

Output:

Cube is: 857.375
n = 10
match is_int:
	case True : print("Square is :",calc(n))
	case False : print("Cube is:", calc(n))

Output is:

Square is : 1000

Here you can check that the expected value was 100 while, 1000 was returned. That means function overloading is not supported.

Pattern Values

The match case in python allows a number, string, ‘None’ value, ‘True’ value, and ‘False’ value as the pattern. Thus, different types of patterns are possible, and we will be looking into some of the possible patterns.

Wildcard Pattern

We can have a wildcard pattern too. A wildcard pattern is executed when none of the other pattern values are matched.

Following shows an example of a wildcard pattern.

We will take the same example of quit. But here, instead of passing a Boolean value to the variable, we will pass an integer value to the ‘quit_flag’ variable.

quit_flag = 4

match quit_flag:
    case True:
        print("Quitting")
        exit()
    case False:
        print("System is on")
    case _:
        print("Boolean Value was not passed")    

The output will be:

Boolean Value was not passed

Here the underscore has been used as a wildcard pattern. It will not bind the ‘quit_flag’ variable’s value to anything but match the variable’s value to the statement.

Multiple pattern values using OR operator

We can also have optional values for a given case. Using the OR operator, we can execute a single expression for multiple possibilities of pattern for the given variable.

In the below code, we have a variable name ‘sample’. If the variable’s value is of Boolean type, then it will execute a common statement for both the conditions. Else, for any other value, it will print ‘Not a Boolean value’.

sample = True

match sample:
	case (True|False):
		print("It is a boolean value")
	case _ :
		print("Not a boolean value")

The output is:

It is a boolean value

Checking for a collection of values

The pattern can also be a collection of values. It will match the pattern against the entire collection. Let us take a list ‘list1’ as an example. We will take the entire list collection as the pattern.

list1 = ['a', 'b', 'c', 'd']

match list1:
	case ['e','f'] : print("e,f present")
	case ['a','b','c','d'] : print("a,b,c,d present")

The output will be:

a,b,c,d present

Named constants as patterns

We can have a named constant as a pattern for match case statements. The constant should be a qualified name addressed by a dot operator. It works like a literal, but it never minds.

An example of named constant is:

class switch:
	on = 1
	off = 0

status = 0

match status:
	case switch.on :
		print('Switch is on')
	case switch.off :
		print('Switch is off')

The output is:

Switch is off

Also Read | 4 Ways of Exiting the Program with Python Exit Function

Inline if statement in match case format

We can also add an if statement to a pattern for a match case in python. That if the condition is also known as ‘guard’. The expression for a given pattern would be evaluated only if the guard is True. If the guard is False, it does not execute that pattern’s statement.

Let us take an example for the same. We have a variable ‘n’ will is assigned a numerical value. We have three cases here – n is negative, n is zero, and n is positive. The match case will check the guard and accordingly print the statement.

n = 0
match n:
	case n if n < 0:
		print("Number is negative")
	case n if n == 0:
		print("Number is zero")
	case n if n > 0:
		print("Number is positive")

The output is:

Number is zero

FAQ’s on match case python

Why does the python match case cause an invalid error?

Implementing a python match case may cause an invalid error if you are using older versions of python. It is because the match case is present only for versions 3.10 and onwards

Why does python not have a switch till version 3.9?

Python does not have switch-case statements before version 3.10 because there were no ways to include that in a manner blended with python’s syntax and coding pattern. There had been several proposals, but none were accepted.

Which is better – match case or if-else statement?

The reason why a match case should be preferred over if-else is that it is computationally faster when compared to an if-else ladder. Also, with a match case, the code becomes more readable and manageable. These advantages are more pre-dominant when the number of conditions is significantly large.


Python match case is a new feature, and it will take some time for everyone to get adapted to it. But once you become used to it, it will definitely come in handy.

That was all for Python Match Case. If you have any questions, leave them below in the comments. Stay Tuned for more such python content.

Until then, Keep Learning!

Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ariel
Ariel
3 years ago

Try not to overwrite inbuilt variables like ‘quit’ it is common conversation to use an underscore to avoid this: ‘quit_’

Python Pool
Admin
3 years ago
Reply to  Ariel

Yes. I’ve updated the post accordingly. Thank you for bringing it up!

Saeed Baig
Saeed Baig
3 years ago

“Also, with a match case, the code becomes more readable and manageable”
Well that depends on the usecase. Although I’m glad Python has match now, there are simple usecases where its overkill. Like that example for showing guards:

match n:
    case n if n < 0:
        print("Number is negative")
    case n if n == 0:
        print("Number is zero")
    case n if n > 0:
        print("Number is positive")

This is a good easy example to show how guards work, but obviously in real code you’d probably write this using a simpler if-chain:

if n < 0:
    print("Number is negative")
elif n == 0:
    print("Number is zero")
elif n > 0:
    print("Number is positive")

(and I don’t think this is ant slower cause you’d be performing the same #if-checks as the match-guard version).

TLDR: Don’t replace all your if-else chains with match; match is best for replacing simple if x == a chains, and pattern matching is also helpful (guards maybe), but use your best judgement.

Last edited 3 years ago by Saeed Baig
Python Pool
Admin
2 years ago
Reply to  Saeed Baig

Totally agreed

azraelgnosis
azraelgnosis
2 years ago

Hi, you’ve an error in the “Match Case Python for Function Overloading” section.Python doesn’t have function overloading (well, there’s multipledispatch); the first definition of calc is just overwritten. And is_int isn’t (re-)assigned in the text of the integer example, but assuming that this happens, you get false positives for values where n^2 == n^3 (e.g. n=0, n=1)

Python 3.10.0 (tags/v3.10.0:b494f59, Oct  4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def calc(n:int): return (n**2)
...
>>> def calc(n:float): return (n**3)
...
>>> n = 9.5
>>> is_int = isinstance(n, int)
>>> match is_int:
...     case True : print("Square is :",calc(n))
...     case False : print("Cube is:", calc(n))
... # Cube is: 857.375
...
Cube is: 857.375
>>> n = 9
>>> is_int = isinstance(n, int)
>>> match is_int:
...     case True : print("Square is :",calc(n))
...     case False : print("Cube is:", calc(n))
... # Square is : 729
...
Square is : 729
>>>
Pratik Kinage
Admin
2 years ago
Reply to  azraelgnosis

Correct. I’ve updated the post accordingly.