12

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!

Community
  • 1
  • 1
  • Duplicate of all of these: http://stackoverflow.com/search?q=%5Bpython%5D+switch. – S.Lott Oct 20 '10 at 14:24
  • See also question [switch case in python doesn't work; need another pattern](http://stackoverflow.com/questions/3886641/switch-case-in-python-doesnt-work-need-another-pattern/3893242#3893242). – martineau Oct 20 '10 at 14:24
  • Since Python 3.10 there is a new `match/case` syntax called "Structural Pattern Matching". – Robson Apr 27 '21 at 10:08

3 Answers3

13

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()
Scott Griffiths
  • 21,438
  • 8
  • 55
  • 85
Omnifarious
  • 54,333
  • 19
  • 131
  • 194
  • Can you give a simple example of how to use Dictionary mapping? Space_Cowboy's example isn't quite clear. –  Oct 20 '10 at 14:01
  • 1
    @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]()`. – Katriel Oct 20 '10 at 14:07
9

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]()
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
9

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!")
menuchoices['q']()

Remember to validate your input! :)

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
  • 3
    That code is so sexy I want to give it lingerie and have it pose on Playboy. +1 –  Oct 20 '10 at 14:14
  • (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. –  Oct 20 '10 at 14:16