Switch Case in Python 3.10 (Structural Pattern Matching)

Posted in

Switch Case in Python 3.10 (Structural Pattern Matching)
vinaykhatri

Vinay Khatri
Last updated on December 10, 2024

    Before Python 3.10, we had no built-in statement for switch cases in Python. However, version 3.10 introduced a new feature – ' Python Structural Pattern Matching ' under PEP 634 . This is equivalent to the switch statement in other programming languages.

    Many popular programming languages, like C, C++, Java, JavaScript, etc., support a switch case, which gives a better way to write multiple conditional statements. Although its use case is quite narrow, it's still an excellent syntax in every programming language. It is the most common feature, and Python did not offer it till version 3.10.

    Guido Van Rossum, the creator of Python, released the first documentation highlighting the new switch statement in 2020. However, it was renamed to Structural Pattern Matching in PEP 634.

    Earlier, if you wished to implement the switch-case statement in Python , you had to use expressions with if-else, dictionaries, or classes. With the all-new Python 3.10 Structural Pattern Matching feature, we can implement a switch case in Python easily.

    This article will discuss everything you should know about the Python 3.10 switch case statement (Structural Pattern Matching). But first, let us briefly understand what a switch-case statement is.

    What is a Switch-Case Statement?

    A switch-case statement in computer programming is a control flow statement that evaluates the given expression and executes the code block with the value matching the result of the expression.

    Features

    • The switch statement is a multi-way branch statement.
    • Its primary use is to execute different actions based on different cases or conditions.
    • It is an excellent alternative to lengthy if-else statements .
    • You can quickly transfer the program control to any part of the code.

    Advantages

    • Easy to debug.
    • Improves code readability; makes it easy for anyone to read the code.
    • Easy to maintain.
    • It simplifies verifying all values that must undergo checking.

    The Need for a Switch-Case Statement

    A switch case comes in handy when you want to execute a particular code block depending on a certain situation. If the given condition is not satisfied, it skips and does not execute those code blocks.

    If we follow the same process manually, it takes too much time, and the complexity of the code increases. Hence, a switch case is the best tool to check a variable against multiple values and execute a code block based on the result.

    Let's look at the conventional way to implement the switch case in Python before we move on to Structural Pattern Matching.

    The Conventional Approach to Implement Switch Case in Python (Before Version 3.10)

    One approach to implement the switch statement in Python was using multiple if-else and elif statements and the switch function. Here is an example of this conventional approach:

    Let's implement the famous weekday calculator with Python as a switch case.

    Example

    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:
    return "Thursday"
    
    elif day ==6:
    return "Friday"
    
    elif day == 7:
    return "Saturday"
    
    else:
    return "Please Enter a Valid Day Number"
    
    
    print(switch(1)) 
    print(switch(4))
    print(switch(7)) 
    print(switch(10))

    Output

    Sunday
    Wednesday
    Saturday 
    Please Enter a Valid Day Number

    Python Structural Pattern Matching (Switch Case)

    As mentioned earlier, structural pattern matching is a new feature for implementing the switch case. It uses two keywords – match and case. We can define several cases or conditions using the case keyword. When the value of the match equals any case’s value, we will execute the corresponding code block.

    Syntax

    match subject:
        case <pattern_1>:
        <action_1>
    
        case <pattern_2>:
        <action_2>
    
        case <pattern_3>:
        <action_3>
    
        case _:
        <action_wildcard>

    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 to refer to it as a Python match case statement instead of a Python switch case.

    Now, let's see how the Python 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 the case statement from top to bottom.
    4. Based on the match case statement pattern, a corresponding <action_n> will occur.
    5. If the match statement cannot match the subject with any case pattern, the last wildcard _ case action will be executed, similar to the default statement in the switch case programming.

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

    Example

    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))
    print(weekday(4)) 
    print(weekday(7))
    print(weekday(11))

    Output

    Sunday
    Wednesday
    Saturday 
    Please Enter a Valid Day Number

    How to Match Multiple Patterns with Python Structural Pattern Matching?

    A Python list comes in handy to match multiple patterns with Python structural pattern matching.

    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)

    Output

    Your total bill is: 249

    The Or Pattern with Structural Pattern Matching

    In the case statement, we have the Or pattern, represented by the pipe operator |, which comes in handy if we want to execute the case when any of the multiple patterns equals 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. Consider 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")

    Output

    Move Left

    Other Conventional Approaches to Implement a Switch Case in Python

    Besides the if-elif statements, two other approaches to implementing a switch in Python are the dictionary and class. Let us understand both these methods in detail below.

    • Dictionary

    A dictionary is a Python data structure that stores data in the form of keys and values. When we use it to implement a switch case, the key-value pairs act as cases in a switch statement.

    Learn more about Python Dictionary here .

    Example

    def violet():
       return "violet"
    
    def indigo():
       return "indigo"
    
    def blue():
       return "blue"
    
    def green():
       return "green"
    
    def yellow():
       return "yellow"
    
    def orange():
       return "orange"
    
    def red():
       return "red"
    
    def default():
       return "Incorrect color of a rainbow"
    
    switcher = {
    
    1: violet,
    2: indigo,
    3: blue,
    4: green,
    5: yellow,
    6: orange,
    7: red
    }
    
    def switch(rainbowcolors):
        return switcher.get(rainbowcolors, default)()
    
    print(switch(3))
    print(switch(5))
    

    Output

    blue
    yellow
    • Classes

    A class is an object constructor containing all methods and properties. It serves as a blueprint for creating objects.

    Example:

    class PythonSwitch:
    
    def color(self, rainbowcolors):
    
    default = "Incorrect day"
    
    return getattr(self, 'case_' + str(rainbowcolors), lambda: default)()
    
       def case_1(self):
       return "violet"
    
       def case_2(self):
       return "indigo"
    
       def case_3(self):
       return "blue"
    
       def case_4(self):
       return "green"
    
       def case_5(self):
       return "yellow"
    
       def case_6(self):
       return "orange"
    
       def case_7(self):
       return "red"
    
    my_switch = PythonSwitch()
    
    print (my_switch.color(1))
    print (my_switch.color(3))
    

    Output

    violet
    blue
    

    Final Thoughts

    Python's Structural Pattern Matching syntax and concept are similar to the switch case statement. However, in Python, it is introduced as a Match Case Statement. It 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.

    We hope this article has helped you understand a switch case in Python. If you have any doubts, let us know in the comments.

    People are also reading:

    Leave a Comment on this Post

    0 Comments