Pythonic way to implement switch/case statements

Programmers familiar with languages like C/C++/Pascal often find puzzling the lack of a switch
/case
statement in Python, like the following one (C):
switch(x) {
case 1: y = 'a'; break;
case 2: do_something(); break;
default: panic();
}
The most straightforward way to do this in Python would be to use a sequence of nested if
:
if x == 1:
y = 'a'
elif x == 2:
do_something()
else:
panic()
A better way to do this in Python is to use a dictionary. Here is an example:
city = raw_input("Enter the city you want to visit: ")
known_cities = {"Paris": "France",
"Rome": "Italy",
"Madrid": "Spain"}
try:
print "The city you chose is in ", known_cities[city]
except KeyError:
print "I've never heard of ", city
If the actions you must perform are quite different depending on the value of x
, then the value associated with each key can be a function:
def connect_to_db():
print "I am going to connect to the DB"
def disconnect_from_db():
print "I am going to disconnect myself from the DB"
available_actions = {"connect": connect_to_db,
"disconnect": disconnect_from_db}
action = raw_input("What should I do now? ")
try:
available_actions[action]()
except KeyError:
print "Unrecognized command ", action
A clever way to avoid the explicit catch to KeyError
is to query the dictionary using get
and passing a null function as the default argument:
available_actions.get(action, lambda: None)()
This replaces the try
…except
construct in the previous example.
Ex: http://codingstyleguide.com/style/id/...
Why use get and a dummy function as default value? This will just hide bugs in case you provide unsupported values. Might be useful in rare occasions but most of the time you want to be informed if you provide an invalid value.
Refactoring: the dictionay variable should be inlined