How to Write a Python Switch Statement

I’ll admit, I don’t use switch statements very often when programming. When I do, it has always been in Javascript. So when I found myself wanting to use a Python switch statement recently, I discovered that the switch/case statement doesn’t exist in the language.

The Python Switch in a Nutshell

If you don’t want to read a long article, here are the basics on how to implement a switch statement in Python. You simply need to create a Python Dictionary (otherwise referred to as an associative array) where the key is your case choice and the value is what gets returned. Then call the dictionary get() method to return the value based on the case.

Here’s what the Pythonic switch-like statement looks like:

def switch(arg):
switchy_thing = {
"case 1": "something",
"case 2": "something else",
"case 3": "something big",
"case 4": "something bigger" ,
"case 5": "something huge!!",
"case 6": "Some really ginormous thing!!!"
}
return switchy_thing.get(arg, "Nothing")

print switch("case 4") #prints "something bigger"

Let’s take a closer look at what’s happening here. Inside the switch function, Switchy_thing is a dictionary containing six “case” statements. These are actually just key/value pairs. After the dictionary is defined, we call the built-in get() method in order to get the value we want out of the dictionary.

The get() method takes in two parameters. The first parameter is the name of the key with the value you are trying to have returned. The second parameter is the default value that get() will return if the key you passed doesn’t exist. This is analogous to the default statement inside of the switch statements of some languages. If our example above called switchy_thing.get(“case 10”, “Nothing”) , it would return “Nothing” since there is no key called “case_10.

dictionary.get(key[, value]) 

As an alternative to using dictionary.get(), you can retrieve a key’s value using square bracket notation with the dictionary name. In our example, to get “case 6” we would write switchy_thing[“case 6”] which would return “Some really ginormous thing!!!”. The problem with doing it this way is there’s no default value failover. If you call switchy_thing[“case 10”] you will get an error.

Here’s how an actual switch statement works in JavaScript:

let someVariable = 5;

switch(someVariable){
case 1:
Some code block...;
break;
case 2:
Some code block...;
break;
case 3:
Some code block...;
break;
case 4:
Some code block...;
break;
case 5:
console.log("case 5 was selected");
break;
case 6:
Some code block...;
break;
default:
"A bad value was entered";
}

//logs "case 5 was selected"

If you’re a JavaScript developer like me, you’ll recognize the code example above. There are several similarities between the JavaScript switch and our Python implementation. First, both look like key value pair constructs.

Both are wrapped in curly braces and separate the cases/keys from the return value with a semi colon. Both have a default value (if you use the get method with the Python implementation).

There are also some differences. The JavaScript default is contained in the body of the switch statement while we’re sort of hacking it in there with Python’s get(). Also, you’ll notice that there’s a break statement in each of the JavaScript case statements that are not present in our Python code. JavaScript doesn’t just jump out of the switch statement when a case is found true. Without the break keyword, control of the switch statement will simply fall through to the next case. It will keep doing this until it hits a break or gets to the default. For example, you could write this in JavaScript:

function pennyWise(year){
switch(year){
case "1858":
console.log("flying eagle cent");
break;
case "1877":
console.log("indian head cent");
break;
case "1910":
case "1934":
case "1977":
case "present":
console.log("Lincoln penny");
break;
default:
"A bad value was entered";
}

pennyWise("1877"); //logs "indian head cent"
pennyWise("1934"); //logs "Lincoln penny"
pennyWise("present"); //logs "Lincoln penny"

We don’t need a break statement in our Python switch because by its nature it only allows a single decision to be made. This is a good thing unless for some reason you rely on this kind of multiple-case behavior.

Come to think of it you can sort of implement the above multiple-case behavior in Python but with an, if statement and the keyword or. You could write:

def switch(val):
if val == 0:
print "you printed zero"
elif val == 1 or val == 2 or val ==3 or val == 4:
print "you printed something between 1 and 4"
else:
print "You don't know how to count"

When do you want to use a switch-like statement in Python?

The case (this pun was stumbled upon and intentionally left in) for using a dictionary/switch statement rather than an if-else is really all about clean looking code and having to write less of it. There might be an argument where one or the other performs better with huge data sets but most of us won’t have to deal with data of that magnitude.

If you do happen to be a big data junkie, all I’ll say is that … it probably still doesn’t matter. It’s not worth worrying about unless your code is slowing to a crawl. Even then it might not be your branching logic that’s at fault. In situations like this, you’ll want to profile your code and try to figure out exactly where the blockage is.

So basically, you’ll use the switch-like statement whenever you feel like it. A good rule of thumb is to use it when you have more than ten if-elif blocks. Even then, it’s just for human readability optimization rather than computer performance optimization.

Why is there no switch statement in Python?

My use case that prompted this post wasn’t that exciting or important. I probably could have just used a slightly larger than usual if/elif statement to do the work. But I hate not knowing how to do something or why something is missing. So I set out to research the mysteriously missing Python switch.

Turns out, it’s not that mysterious after all. Guido van Rossum and the Python team have never put it in the language. They didn’t think it was necessary. In fact, in the official documentation, there’s really no reason given. It basically tells the reader to deal with it and use if/elif/else statements where you just keep adding elifs for each case you want to include.

The docs go on to say that if you have a lot of cases to choose from you can set up a dictionary mapping to emulate a switch. Oh, hey, that’s what were doing in this article!

None of this is to say that no one wants a switch-case statement in Python. There have been a couple of proposals put before the Python team with solutions to a supposed problem. But each time switch comes up it gets rejected. It’s unlikely to ever become a part of the language.

Conclusion

While Python doesn’t have a native switch implementation, it’s fairly easy to emulate the functionality using dictionaries and its built-in get() method. Or, instead of trying to patch together a switch, you can just use if – elif – elif … until you’ve listed all of your cases. Then you can use the else clause as your default value. There’s really no performance advantage to either one for most programmers. But once you get more than, say, 10 elifs, your code can start to look a little messy. At that point, you might consider the dictionary/switch syntax. Beyond that it doesn’t really matter.

Leave a Comment

Your email address will not be published. Required fields are marked *