Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's an alternative to if/elif statements in Python? [duplicate]

Tags:

python

My code currently looks something like this:

if option1:
    ...
elif option2:
    ...
elif option3:
    ....

so on so forth. And while I'm not displeased with it, I was wondering if there was a better alternative in python. My script is a console based script where I'm using argparser to fetch for what the user needs.

like image 754
Stupid.Fat.Cat Avatar asked Jul 26 '13 12:07

Stupid.Fat.Cat


1 Answers

If 'option' can contain 'one', 'two', or 'three', you could do

def handle_one():
  do_stuff

def handle_two():
  do_stuff

def handle_three():
  do_stuff


{'one': handle_one, 
 'two': handle_two, 
 'three': handle_three}[option]()
like image 110
Fredrik Håård Avatar answered Sep 19 '22 02:09

Fredrik Håård