Python 3.10 All New Switch Case Statement (Structure Pattern Matching)

Posted in /  

Python 3.10 All New Switch Case Statement (Structure Pattern Matching)

Vinay Khatri
Last updated on January 4, 2023

    Before Python 3.10, we did not have any built-in statement in Python for popular switch cases. However, Python 3.10 introduced a new feature under PEP 634 " Switch Case in Python " called "Python Structure Pattern Matching".

    Many popular programming languages like C, C++, Java, JavaScript, etc., support switch-case statements because they give a better way to write multiple conditional statements. Although the use case of the switch case statement is quite narrow, still it's a good syntax to have in every programming language.

    Until now Python was deprived of the switch case statement, and if you want to implement one, you have to use functions with if-else, dictionaries, or classes. With the all-new Python 3.10 Structure Pattern Matching feature, we will be able to implement Switch Case statements in Python.

    In this Python article, we will discuss everything that you should know about the Python 3.10 switch case statement (Structural Pattern Matching). But before that, let's have a look at the conventional way to implement the switch case in Python.

    The Conventional Approach to Implement Switch Case in Python

    As the switch case is an alternative to the if-else statement, we can use multiple if-else and elif statements to implement the switch case in Python. Now, let's implement the famous weekday calculator with Python as a switch case.

    def switch(day):
        if day == 1:
            return "Sunday"
        elif day ==2:
            return "Monday"
        elif day == 3:
            return "Tuesday"
        elif day ==4:
            return "Wednesday"
        elif day == 5:
        elif day ==6:
        elif day == 7:
            return "Saturday"
            return "Please Enter a Valid Day Number"
    print(switch(1))   #Sunday
    print(switch(4))   # Wednesday
    print(switch(7))   #Saturday
    print(switch(10))   # Please Enter a Valid Day Number

    The function and if-else are one of the conventional ways to implement Switch Case in Python3.9 and older versions. To know about other ways to implement the switch case in Python, click here .

    Python Structural Pattern Matching (Python Switch Case)

    In Python 3.10, Python has introduced a new feature in PEP 634 as "Structural Pattern Matching". The official documentation introduces Pattern Matching as:

    Python PEP 634: Structural Pattern Matching Structural pattern matching has been added in the form of a match statement and case statements of patterns with associated actions. Patterns consist of sequences, mappings, primitive data types as well as class instances. Pattern matching enables programs to extract information from complex data types, branch on the structure of data, and apply specific actions based on different forms of data.


    match subject:
        case <pattern_1>:
        case <pattern_2>:
        case <pattern_3>:
        case _:

    Unlike other programming languages, Python does not use the switch keyword for its Structural Pattern Matching, instead, it uses the match keyword. So, it would not be wrong if we refer to it as a Python match case statement instead of a Python switch case. Now let's see how the Pyhton match statement works.

    1. The subject can be any Python literal, data, or object.
    2. The match statement will evaluate the subject data or object.
    3. It will compare the subject with each <pattern_n> of case statement from top to bottom.
    4. Based on the match case statement pattern, a corresponding <action_n> will take place.
    5. If the match statement is not able to match the subject with any case pattern, the last wildcard _ case action will be executed, which is similar to the default statement of other switch case programming.

    Now let's use the new Python match case Statement and implement the same weekday calculator that we have implemented earlier.

    def weekday(day):
        match day:
            case 1:
                return "Sunday"
            case 2:
                return "Monday"
            case 3:
                return "Tuesday"
            case 4:
                return "Wednesday"
            case 5:
                return "Thursday"
            case 6:
                return "Friday"
            case 7:
                return "Saturday"
            #wildcard case
             case _:
                return "Please Enter a Valid Day Number"
    print(weekday(1))    #Sunday
    print(weekday(4))   #Wednesday
    print(weekday(7))   #Saturday
    print(weekday(11))  #Please Enter a Valid Day Number

    How to Match Multiple Patterns with Python Structural Pattern Matching

    We can take the help of a Python list if we want to match multiple patterns. Example

    total = 200
    extra_toppings_1 = 'pepperoni'
    extra_toppings_2 = 'onions'
    match [extra_toppings_1, extra_toppings_2]:
        case ['pepperoni', 'mushrooms']:
            extra = 79
        case ['pepperoni', 'onions']:
            extra = 49
        case ['pepperoni', 'bacon']:
            extra = 99
        case ['pepperoni', 'extra cheese', 'black olives']:
            extra = 149
    print("Your total bill is:", total+extra)


    Your total bill is: 249

    Or Pattern with Structural Pattern Matching

    In the case statement, we have the Or pattern, represented by the pipe operator | , that comes useful if we want to execute the case when any of the multiple patterns matched the subject of the match statement. Example Let's write logic with a Python match case statement that computes the movement of a character in a game. A and a represent left , W and w represent forward , D and d represent right , and S and s represent backward .

    total = 200
    key = 'A'
    match key:
        case 'a' | 'A':
            print("Move Left")
        case 'w' | 'W':
            print('Move Forward')
        case 'd' | 'D':
            print("Move right")
        case 's' | 'S':
            print("Move Backward")


    Move Left

    Final Thoughts

    The syntax and concept of Python's "Structural Pattern Matching" are similar to Switch Case Statement. However, in Python, it is introduced as Match Case Statement. The Python 3.10 Switch Case Statement (Structural Pattern Matching) provides an easy way to write multiple similar if-else statements.

    Also, unlike a normal switch case statement, the Python Match Case statement can work with different Python data objects, including literals and objects.

    People are also reading:

    Leave a Comment on this Post