Using dictionaries for conditional execution instead of if..elif

Say you have something like below:

def case_A():
   print 'A'

def case_B():
   print 'B'

def case_generic():
   print 'some generic case'

And is valuedefined and has some meaning in it

You see scenarios in which you would not want to apply the template below:

v = {"A":case_A, "B":case_B}
try:
   v[value]()
except:
   case_generic()

instead of standard:

if value == "A":
   case_A()

elif value == "B":
   case_B()

...place n more if cases here...

else:
   case_generic()

For me, the first case looks more compact and easy to manage, although with a slight increase in memory. Alternatively, do you see any ways to improve the above, or use the best way alltogether?

+3
source share
3 answers

You can do:

v.get(value, case_generic)()
+5
source

I do not see any problems with this method, but it can be improved with defaultdict:

v = defaultdict(lambda: case_generic)
v.update({"A": case_A, "B": case_B})

v['A']() # 'A'
v['B']() # 'B'
v['K']() # 'some generic case'
+2

EAFP ( , ) - Python - , . (. , Java, 57).

except, , . , , , , :

try:
    v[value]()
except KeyError: # Key doesn't exist in dictionary
    case_generic()
+2

All Articles