Vedang Manerikar

My corner on the internet.

Switch Statements in Python

Today I went through some old Python code and noticed this pattern through out:

messy-ifs.py
1
2
3
4
5
6
7
8
9
10
response, data = somefunc()
if response == "this":
do_this_with(data)
elif response == "that":
do_that_with(data)
elif response == "huh":
duh(data)
# lots more elifs.
else:
prevent_horrible_crash(data)

This code should ideally have been a switch-case, but Python does not support a switch statement. Proponents of OOP believe that switch is bad - second only to goto. This is not strictly true - both goto and switch can be used elegantly and with great effect. Goto, for example, is great for undoing stacked changes and switch’s fall-through behavior allows nicely for ‘do things according to the stage I’m at’. However, if you’re doing OOP, consider using polymorphism instead.