Open In App

Python Match-Case Statement

Last Updated : 26 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python is under constant development and it didn’t have a match statement till python < 3.10. Python match statements were introduced in python 3.10 and it is providing a great user experience, good readability, and cleanliness in the code which was not the case with clumsy Python if elif else ladder statements. 

What is a ‘match-case’ statement?

For developers coming from languages like C/C++ or Java know that there was a conditional statement known as Switch Case. This Match-Case is the Switch Case of Python which was introduced in Python 3.10. Here we have to first pass a parameter then try to check with which case the parameter is getting satisfied. If we find a match we will do something and if there is no match at all we will do something else.

Pseudocode for Python match-case Statement

The match statement is initialized with the match keyword creating a block and taking a parameter ( here the name is also a parameter ) and then steps down to the various cases using the case keyword and the pattern, for the pattern to match the parameter. The ” _  ” is the wildcard character which is run when nothing is matched.

Python3




parameter = "Geeksforgeeks"
 
match parameter:
   
    case first  :
        do_something(first)
     
    case second :
          do_something(second)
         
    case third :
        do_something(third)
        .............
        ............
    case n :
        do_something(n)
    case _  :
          nothing_matched_function()
           


Python match case statement

The match statement checks for the username and checks for the database access permission.

Python3




def provideAccess(user):
    return {
        "username": user,
        "password": "admin"
    }
 
 
def runMatch():
    user = str(input("Write your username -: "))
 
    # match statement starts here .
    match user:
        case "Om":
            print("Om do not have access  to the database \
            only for the api code.")
        case "Vishal":
            print(
                "Vishal do not have access to the database , \
                only for the frontend code.")
 
        case "Rishabh":
            print("Rishabh have the access to the database")
            print(provideAccess("Rishabh"))
 
        case _:
            print("You do not have any access to the code")
 
 
if __name__ == "__main__":
    for _ in range(3):
        runMatch()


Output:

Providing database access to the user using a match statement

Use of Python OR in match statement

The pipe operator for the match statement. Match statements were meant to be for only matching the patterns and specific keywords or parameters. But you can use pipe operator for or statement in match statement. We simplify the above code with the pipe operator. 

Python3




def provideAccess(user) :
    return {
        "username" : user ,
        "password" : "admin"
    }
 
     
def runMatch()  :
    user = str(input("Write your username -: "))
 
    # match statement
    match user : 
        case "Om" "Vishal"  :
            print("You are not allowed to access the database !")
         
        case "Rishabh" :
            print("You are allowed to access the database !")
            data =  provideAccess("Rishabh")
            print(data)
        case _ :
            print("You are not a company memeber , you are not \
            allowed to access the code !")
 
if __name__ == "__main__"
    for _ in range(2) :
        runMatch()


Output:

Using pipe operator for or clause. 

Use of Python If in match statement

We also can use the Python If condition which is basically the if statements for pattern matching. When a case is matched then we move to the guard condition ( basically the if condition ) and if the condition for the if statement turns out to be true, then we select the block else we do not select the block.

Here, in this example, it checks the case for the match statement. If the case is Rishabh it checks then for the allowedDataBaseUsers list for Rishabh to exist in it. If he is there is the condition for the guard statement is the truth then it will choose this block and move to its part below and provide it access to the database.

Python3




def provideAccess(user):
    return {
        "username": user,
        "password": "admin"
    }
 
def runMatch():
    user = str(input("Write your username -: "))
    allowedDataBaseUsers = ["Rishabh"]
    match user:
        case "Rishabh" if user in allowedDataBaseUsers:
            print("You are allowed to access the database !")
            data = provideAccess("Rishabh")
            print(data)
        case _:
            print("You are not a company memeber , \
            you are not  allowed to access the code !")
 
 
if __name__ == "__main__":
    for _ in range(2):
        runMatch()


Output:

Match statement done using guards. 

Match the Sequence Pattern

Here, we will see how to match the sequence in the match statement. This is quite easy and the same as matching the strings and integers also we can use positional arguments for checking the list.

The first case just matches a list with a single character in it that is “a”. The second case matches the first character with a and then *other_items as the other items in the list. The * character is used to get all the other values and other_items variables and all other arguments that are passed to the list. Hence the first character is matched with a and the rest of them are left out, and In the third case, the last character is checked, is it d? And the ones in front are ignored or are taken in the first_items  named variable. 

Python3




def runMatch(data_input):
    match data_input:
        case["a"]:
            print("The list only contains a and is just a single list")
 
        case["a", *other_items]:
            print(f"The 'a' is the first element\
            and {other_items} are the rest  of the elements !")
 
        case[*first_items, "d"] | (*first_items, "d"):
            print(f"The 'd' is the last item and\
            {first_items} are the previous elements before it !")
 
        case  _:
            print("No case matches with this one !")
 
 
if __name__ == "__main__":
    runMatch(["a"])
    runMatch(("a", "b"))
    runMatch(["a", "b", "c", "d"])
    runMatch(["b", "c", "d"])


Output:

Using sequence matching in match statements.

Use of Python Class in match statement

We can also use Python classes to match using the Python match statements. This will make the code very much clean,  neat, and more importantly easily readable.

The first thought after seeing the match statement would be that the Programmer and Person inside the match statement would create an instance of the respective classes, but it is not the case. It will check for the instance with the given values. So the case Programmer(“Om”, language = “Python”, framework = “Django”)  will not create an instance but will check that the object passed whose name is instance is a  real instance of the Programmer class, then it will check for the name that is  “Om”, language that is “Python” and then framework that is “Django”. This way we can check for the values in the instance of any class.

Python3




from dataclasses import dataclass
 
@dataclass
class Person:
    name: str
    age: int
    salary: int
 
 
@dataclass
class Programmer:
    name: str
    language: str
    framework: str
 
 
def runMatch(instance):
    match instance:
        case Programmer("Om", language="Python",
                        framework="Django"):
            print("He is Om and he is a Python programmer and \
            uses Django Framework!")
 
        case Programmer("Rishabh", "C++"):
            print("He is Rishabh and is a C++ programmer !")
 
        case Person("Vishal", age=5, salary=100):
            print("He is vishal and he is a kid !")
 
        case Programmer(name, language, framework):
            print(f"He is programmer , his name is {name} ,\
            he works in {language} and uses {framework} !")
 
        case Person():
            print("He  is just a person !")
 
        case _:
            print("This person is nothiing !")
 
 
if __name__ == "__main__":
    programmer1 = Programmer("Om", "Python", "Django")
    programmer2 = Programmer("Rishabh", "C++", None)
    programmer3 = Programmer("Sankalp", "Javascript", "React")
    person1 = Person("Vishal", 5, 100)
    runMatch(programmer1)
    runMatch(programmer2)
    runMatch(person1)
    runMatch(programmer3)


Output:

 

Use of Python Dictionary in match statement

The first case here matches the key and the value for the dictionary, just one value and dictionary. The second case matches for multiple keys, the keys and values must reside in the dictionary, if there is any misplaced value or any key which does not exist and does not match the actual dictionary and value, this case will be discarded, and For the third case, we just checked that there key named name, language, and framework, and their respective variables were created with the same name, you can change them easily, not an issue, just make them look like the keys I  took the same name. 

Python3




def runMatch(dictionary):
    match dictionary:
        case {"name": "Om"}:
            print("This matches only for one key ,\
            that is if they key exists with  the pair \
            value then this block will be selected !")
 
        case {"framework": "Django", "language": "Python"}:
            print("This one matches multiple keys and values . !")
 
        case {"name": name, "language": language,
              "framework": framework}:
            print(f"The person's name is {name}  , \
            the language he uses is {language}\
            and the framework he uses is {framework} !")
 
        case _:
            print("Matches anything !")
 
 
if __name__ == "__main__":
    a = {
        "name": "Om",
        "language": "Python",
        "framework": "Django",
    }
    runMatch(a)
    a["name"] = "Rishabh"
    runMatch(a)
    a["language"] = "C++"
    runMatch(a)


Output:

Dictionary mapping

Python Match Case Statement FAQ:

Q: What is the match-case statement in Python?

A: The match-case statement, also known as pattern matching, is a feature introduced in Python 3.10. It provides a concise and expressive way to perform pattern matching on data structures, such as tuples, lists, and classes. It allows you to match the value of an expression against a series of patterns and execute the corresponding block of code for the matched pattern.

Q: How does the match-case statement differ from if-elif-else statements?

A: The match-case statement is a more powerful and expressive construct compared to if-elif-else statements. While if-elif-else statements rely on boolean expressions, match-case statements can match patterns based on the structure and value of the data. Match-case statements provide a more structured and readable way to handle multiple conditions and perform different actions based on those conditions.

Q: What are the benefits of using the match-case statement?

A: The match-case statement offers several benefits, including:

  • Conciseness: Match-case statements allow you to express complex branching logic in a concise and readable manner.
  • Readability: Pattern matching makes the code more readable and self-explanatory, as it closely resembles the problem domain.
  • Safety: Match-case statements provide exhaustive pattern matching, ensuring that all possible cases are handled.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads