Possible Duplicate:
Replacements for switch statement in python?
Suppose I have a list in Python:
list = (‘ADD’, ‘SUB’, ‘PUSH’, ‘POP’)
I want to run a function depending on input, and that input can be any value in the list.
Instead of writing a switch case statement for each element in list, is there a more compact way of writing it?
My reasoning is for the case of the list growing in the future.
Well, there is no switch/case statement in Python.
For a small
list, you want to useif/elif:For a larger
list, you want to make sure each case is a function (I already assumed that above, but if you had code likereturn args[0] + args[1], you’d have to change that into ado_addfunction), and create adictmapping names to functions:This works because in Python, functions are normal objects that you can pass around like any other objects. So, you can store them in a
dict, retrieve them from thedict, and still call them.By the way, this is all explained in the FAQ, along with a bit of extra fanciness.
If you have some default function you’d like to call instead of raising an error, it’s obvious how to do that with the
if/elif/elsechain, but how do you do it with thedictmap? You could do it by putting the default function into theexceptblock, but there’s an easier way: just use thedict.getmethod: