switch()alikes in Python
There’s a fun thread over here about the different idioms
people use to approximate C switch in Python (which has no
equivalent keyword). I love the delicious functional-programming flavor
of the author’s original suggestion:
ref="http://simon.incutio.com/archive/2004/05/07/switch">
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
However, I frequently need a little more oomph than you can fit
in Python’s anemic lambda construct. I find myself using
the following idiom, which allows me to do tricky C switch
things like fall through from one case to another:
for value in [value]:
if value == 'a':
result = x * 5
break
if value == 'b':
result = x + 7
break
if value == 'c':
result = x - 2
break
# default
result = x
break
OK, that first line is a little contrived, but there’s typically something more complex than [value] up there on the first line. I’m often testing the result of a more complex expression (like switch(expr) in C) so it’s useful to capture that computation once.
It doesn’t quite fall through like C switch (the test you fall into still has to succeed). But, hey, it does use the break keyword.