views:

142

answers:

3

Possible Duplicate:
Replacements for switch statement in python?

I'm making a little console based application in Python and I wanted to use a Switch statement to handle the users choice of a menu selection.

What do you vets suggest I use. Thanks!

+11  A: 

There are two choices, first is the standard if ... elif ... chain. The other is a dictionary mapping selections to callables (of functions are a subset). Depends on exactly what you're doing which one is the better idea.

elif chain

 selection = get_input()
 if selection == 'option1':
      handle_option1()
 elif selection == 'option2':
      handle_option2()
 elif selection == 'option3':
      some = code + that
      [does(something) for something in range(0, 3)]
 else:
      I_dont_understand_you()

dictionary:

 # Somewhere in your program setup...
 def handle_option3():
    some = code + that
    [does(something) for something in range(0, 3)]

 seldict = {
    'option1': handle_option1,
    'option2': handle_option2,
    'option3': handle_option3
 }

 # later on
 selection = get_input()
 callable = seldict.get(selection)
 if callable is None:
      I_dont_understand_you()
 else:
      callable()
Omnifarious
Can you give a simple example of how to use Dictionary mapping? Space_Cowboy's example isn't quite clear.
Serg
@sergio: suppose you have functions `opener` and `closer`, say to open and close a window. Then to call one of them based on a string, do `switcher = {"open": opener, "close": closer}` so that you have the actual functions in a `dict`. Then you can do `switcher[choice]()`.
katrielalex
+6  A: 

Use a dictionary to map input to functions.

switchdict = { "inputA":AHandler, "inputB":BHandler}

Where the handlers can be any callable. Then you use it like this:

switchdict[input]()
Space_C0wb0y
+1, Nice and elegant :)
Andrew Sledge
+4  A: 

Dispatch tables, or rather dictionaries.

You map keys aka. values of the menu selection to functions performing said choices:

def AddRecordHandler():
        print("added")
def DeleteRecordHandler():
        print("deleted")
def CreateDatabaseHandler():
        print("done")
def FlushToDiskHandler():
        print("i feel flushed")
def SearchHandler():
        print("not found")
def CleanupAndQuit():
        print("byez")

menuchoices = {'a':AddRecordHandler, 'd':DeleteRecordHandler, 'c':CreateDatabaseHandler, 'f':FlushToDiskHandler, 's':SearchHandler, 'q':CleanupAndQuit}
ret = menuchoices[input()]()
if ret is None:
    print("Something went wrong! Call the police!")
menuchoices['q']()

Remember to validate your input! :)

Michael Foukarakis
That code is so sexy I want to give it lingerie and have it pose on Playboy. +1
Serg
(1) Btw, `the_input in menu_choices` is a cheap validation that's guaranteed to be in synch with the actual choices. (2) All the example handlers return `None`, so don't bother the police after runnig the example ;) (3) As always, use `raw_input` instead of `input` in Python 2.
delnan