How to Write a Switch Case in Python

Python introduced a new feature called the Match case that introduced a switch case behavior to Python code since version 3.10.6 - let's talk about it.

How to Write a Switch Case in Python
Photo by Hitesh Choudhary / Unsplash

You'll be surprised how many people are looking for a Switch Case implementation in Python. I've been writing Python code for about five years and have never felt that not having it was a dealbreaker in any way.

Since version 3.10.6, Python has added a new feature called Match Case. It offers a very similar behavior to traditional switch case implementations. I published a demonstration video on my Oren Codes YouTube channel. You can check it out here or read below it if you prefer the written version:

Oren Codes YouTube Channel

Why do we need it?

Let's say you are contacting a server. And you have prepared paths of action whether the response is successful or not. But there are multiple possible errors, and you must address them.

So, here's how that could be achieved without a match case:

status_code = response.status_code

if status_code == 200:
    ...
elif status_code == 400:
    ...
elif status_code == 422:
    ...
else:
    ...

So, for any response you check, you will have to go through this entire if block, and it's also not aesthetically pleasing to the eye. With a match, you'll get to exactly where you need to be within the code with fewer if statements.

Match Case Example

Here's a very simplistic example of how the feature works:

status_code = response.status_code

match status_code:
    case 200:
    	...
    case 400:
    	...
    case 422:
    	...
    case _:
        raise Exception("Error occurred when contacting server")

You take a variable you want to check. It could also be a complex object, not just a number or string. Then you pose cases and what happens if they match. Remember that this feature is only available on Python 3.10.6 and up.

The downside of using match cases is that you'll see their potential everywhere now, and sometimes using them would be wrong. There are cases when you want a finer control on the flow of things, and using a match case takes that control away from you, unlike the control given by aptly placed if statements.

Overall, it's pretty simple, right? Let me know if you have any questions in the comments below!

And if you want to read more about it, you can check out the official documentation.

Check out other Python tutorials right here.

Subscribe to Oren Codes

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe