DEV Community

loading...

Switch Statements in Python 3.10.

Mwenda Harun Mbaabu
Software Engineer, Data Scientist and DevRel. Building Data Science East Africa, @DSEAfrica and Lux Tech Academy, @lux_academy
・3 min read

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!!!

Enter fullscreen mode Exit fullscreen mode

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!!!
Enter fullscreen mode Exit fullscreen mode

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!!!
Enter fullscreen mode Exit fullscreen mode
  • 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

Discussion (4)

Collapse
alexmacniven profile image
Alex Macniven

Nice article, very much looking forward to seeing what 3.10 has to offer 😀

In your dictionary example, you can call .get(key, default) on a dict where default is returned if key isn’t a valid key. It’s great for when you’d otherwise need to handle KeyError

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Glad you found it helpful, and thank you for additions.

Collapse
excalizan profile image
Excalizan

Well explained, thanks bro!

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Glad you found it helpful, and thank you for feedback