Switch Statements in Python 3.10.

Python 3.10 is still in alpha, but will bring along some new exciting features. We’ll look at one of these in this article — the switch statements — officially known as Structural Pattern Matching .

Switch statements are commonly seen in most progra…

python 3.10 switch statements

Python 3.10 is still in alpha, but will bring along some new exciting features. We’ll look at one of these in this article — the switch statements — officially known as Structural Pattern Matching .

Switch statements are commonly seen in most programming languages and provide a neater way of implementing conditional logic. They come in handy when there’s a lot of conditions to evaluate.
Today we’ll see how to use them and compare the code differences with a more traditional approach.



The Old Way(s) of Implementing Conditional Operations.

The first one is your standard if-elif-else statement, and the otheris the use of dictionary key-value mappings to avoid if statements altogether.

First things first, we need some code. We’ll declare a function called get_mood(day: str) -> str that returns a string whose value depends on the input parameter. The returned value gets more exciting as we approach the weekend.
Silly little function, but will do for demonstration purposes.

Let’s implement it with a classical if methodology. Here’s the code:


def get_mood(day):
    if day == 'Monday':
        return 'Oh...'
    if day == 'Thursday':
        return 'Getting close!'
    if day == 'Friday':
        return 'Almost there!'
    if day == 'Saturday' or day == 'Sunday':
        return 'Weekend!!!'
    return 'Meh...'


print(get_mood(day='Monday'))
# Oh...
print(get_mood(day='Wednesday'))
# Meh...
print(get_mood(day='Friday'))
# Almost there!
print(get_mood(day='Sunday'))
# Weekend!!!

Nothing new or groundbreaking here. The code is simple to understand but is too verbose, especially when multiple values can satisfy a single condition.

We can “improve” or mix things up a bit by avoiding if statements altogether and writing the function in the form of key-value mappings. This also includes a try except block to set up a default return value.
Here’s the code snippet:

def get_mood(day):
    mappings = {
        'Monday': 'Oh...',
        'Thursday': 'Getting close!',
        'Friday': 'Almost there!',
        'Saturday': 'Weekend!!!',
        'Sunday': 'Weekend!!!'
    }
    try: return mappings[day]
    except KeyError: return 'Meh...'


print(get_mood(day='Monday'))
# Oh...
print(get_mood(day='Wednesday'))
# Meh...
print(get_mood(day='Friday'))
# Almost there!
print(get_mood(day='Sunday'))
# Weekend!!!

As you can see, the results are identical, but we haven’t used conditional operators. Both approaches will work fine, but what Python was always lacking was a dedicated switch statement.

Now let fix that with Python 3.10 switch statements.

According to the official documentation:

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.

For the sake of simplicity, We’ll stick to the basics today and explore everything structural pattern matching has to offer some other time.

Let’s circle back to our get_mood() function and rewrite it with a switch statement-like syntax. Unlike many other programming languages, Python uses the match keyword instead of a switch. The case keyword is identical.

Here’s the code snippet:

def get_mood(day):
    match day:
        case 'Monday':
            return 'Oh...'
        case 'Thursday':
            return 'Getting close!'
        case 'Friday':
            return 'Almost there!'
        case 'Saturday' | 'Sunday':
            return 'Weekend!!!'
        case _:
            return 'Meh...'


print(get_mood(day='Monday'))
# Oh...
print(get_mood(day='Wednesday'))
# Meh...
print(get_mood(day='Friday'))
# Almost there!
print(get_mood(day='Sunday'))
# Weekend!!!
  • Use the case keyword to evaluate for a condition (case ‘Monday’ is identical to if day == ‘Monday’)

  • Separate multiple conditions with the pipe operator — | — e.g., if two input values should result in the same return value

  • Use the underline operator — _ — to specify the default case.



Note:

  • Python 3.10 will bring many exciting features, but it’s still in alpha. Since it’s not production-ready, it might not be a good idea to install it as your default Python version.

Stay tuned to the blog to learn more.

You can connect with me on twitter @HarunMbaabu


Print Share Comment Cite Upload Translate
APA
Mwenda Harun Mbaabu | Sciencx (2024-03-29T08:02:55+00:00) » Switch Statements in Python 3.10.. Retrieved from https://www.scien.cx/2021/06/10/switch-statements-in-python-3-10/.
MLA
" » Switch Statements in Python 3.10.." Mwenda Harun Mbaabu | Sciencx - Thursday June 10, 2021, https://www.scien.cx/2021/06/10/switch-statements-in-python-3-10/
HARVARD
Mwenda Harun Mbaabu | Sciencx Thursday June 10, 2021 » Switch Statements in Python 3.10.., viewed 2024-03-29T08:02:55+00:00,<https://www.scien.cx/2021/06/10/switch-statements-in-python-3-10/>
VANCOUVER
Mwenda Harun Mbaabu | Sciencx - » Switch Statements in Python 3.10.. [Internet]. [Accessed 2024-03-29T08:02:55+00:00]. Available from: https://www.scien.cx/2021/06/10/switch-statements-in-python-3-10/
CHICAGO
" » Switch Statements in Python 3.10.." Mwenda Harun Mbaabu | Sciencx - Accessed 2024-03-29T08:02:55+00:00. https://www.scien.cx/2021/06/10/switch-statements-in-python-3-10/
IEEE
" » Switch Statements in Python 3.10.." Mwenda Harun Mbaabu | Sciencx [Online]. Available: https://www.scien.cx/2021/06/10/switch-statements-in-python-3-10/. [Accessed: 2024-03-29T08:02:55+00:00]
rf:citation
» Switch Statements in Python 3.10. | Mwenda Harun Mbaabu | Sciencx | https://www.scien.cx/2021/06/10/switch-statements-in-python-3-10/ | 2024-03-29T08:02:55+00:00
https://github.com/addpipe/simple-recorderjs-demo