Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dictionaries for conditional execution instead of if..elif [closed]

Say you have something like below:

def case_A():
   print 'A'

def case_B():
   print 'B'

def case_generic():
   print 'some generic case'

And value is defined and has some value in it

Do you see any scenario(s) where you wouldn't want to apply the pattern below:

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

instead of the standard:

if value == "A":
   case_A()

elif value == "B":
   case_B()

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

else:
   case_generic()

To me the first case looks way more compact and easy to manage, albeit with a slight increase in memory. Alternatively, do you see any ways of improving the above or using a better way alltogether?

like image 382
gts Avatar asked Jan 18 '26 23:01

gts


2 Answers

you could do :

v.get(value, case_generic)()
like image 143
dugres Avatar answered Jan 20 '26 11:01

dugres


EAFP (it's easier to ask for forgiveness than permission) is a common coding style in Python due to its emphasis on conciseness and readability and can result in fast, efficient, and readable code. In other languages, using exceptions as control flow as opposed to truly exceptional reasons is frowned upon (see Joshua Bloch, Effective Java, Item 57).

But you don't want to have a generic except clause, because this swallows any type of possible exception that could occur in the execution of the code. Rather, you want to be very explicit in the exception you're catching which makes it very clear to any reader that you're checking for keys:

try:
    v[value]()
except KeyError: # Key doesn't exist in dictionary
    case_generic()
like image 21
jayelm Avatar answered Jan 20 '26 12:01

jayelm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!