X-Pender X-Pender - 1 year ago 75
Python Question

Switch in Python

I have tried making a switch like statement in python, instead of having a lot of if statements.

The code looks like this:

def findStuff(cds):
for i in range(0, len(cds), 3):
result = {
a[2][0]==1: c=i+1,
a[2][1]==1: c=i+2,
a[2][2]==1: c=i+3,
a[1]==1: L.append((cds[i:i+3], a[0], c))
return L

My problem is, that this does not work. (Works with if statements, but this would in my opinion be more pretty).

I have found some examples of switches in Python, and they follow this structure. Can anyone help me?

Answer Source

(a) I fail to see what is wrong with if...elif...else

(b) I assume that python does not have a switch statement for the same reason that Smalltalk doesn't: it's almost completely redundant, and in the case where you want to switch on types, you can add an appropriate method to your classes; and likewise switching on values should be largely redundant.

Note: I am informed in the comments that whatever Guido's reason for not creating a switch in the first place, PEPs to have it added were rejected on the basis that support for adding such a statement is extremely limited. See: http://www.python.org/dev/peps/pep-3103/

(c) If you really need switching behaviour, use a hashtable (dict) to store callables. The structure is:

switch_dict = {
    Foo: self.doFoo,
    Bar: self.doBar,

func = switch_dict[switch_var]
result = func() # or if they take args, pass args
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download