Python/DictAsSwitch

From ProgrammingExamples
< Python
Revision as of 00:11, 29 June 2010 by Griswolf (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

back to Python examples


In many languages, there is a switch or case statement. Python appears not to have that, so you will see a lot of if/elif/elif/.../else . There is a better way using a dict.
For concreteness, lets mimic this C code:

int count_of_bs = 0
switch(a) {
  case 'a': call_a(a); break;
  case 'b': ++count_of_bs; break
  default: call_other(a); break;
 }

Here it is in Python (with function definitions and a few quick tests)

switchExample.py

count_of_bs = 0
# these functions would have to be defined in any case.
def call_a(a):
  print 'a called with %s'%str(a)
 
def call_other(a):
  print 'otherwise, with %s'%str(a)
 
#this function is 'overhead' to make the switch statement work
def do_b(a):
  global count_of_bs
  count_of_bs += 1
 
# this is the declaration of the switch
switch = {
  'a':call_a,
  'b': do_b,
  }
# run some test cases. Note that we handle non-scalars just fine
print ('count_of_bs %s'%count_of_bs)
for tc in ['b', 'a','b','c','b','alphabet',(99,'bottles','beer'),'b']:
  # this is how you use it
  switch.get(tc,call_other)(tc)
print ('count_of_bs %s'%count_of_bs)
 
"""Output:
count_of_bs 0
a called with a
otherwise, with c
otherwise, with alphabet
otherwise, with (99, 'bottles', 'beer')
count_of_bs 4
"""

back to Python examples