[Tutor] using exceptions to implement case/switch?

Kent Johnson kent_johnson at skillsoft.com
Fri Oct 15 19:22:30 CEST 2004

A simple way to do this is to use a dictionary as a dispatcher:
dispatch = {
   curses.KEY_F1 : process_keyF1,   # Note - no parentheses here, this is a 
reference to the fn, not a call
   curses.KEY_F2 : process_keyF2,
   curses.KEY_F3 : process_keyF3,
   curses.KEY_F4 : process_keyF4,

         while True:
                 c = win.getch()
                 if ascii.isprint(c) : return c
                 fn = dispatch.get(c, curses.beep)


At 09:56 AM 10/15/2004 -0700, Bill Campbell wrote:
>I'm looking for feedback on the pros and cons of using exceptions to
>implement constructions similar to the C switch or other language's case
>I'm in the process of converting bunch of C code that makes extensive use
>of switch() statements.  In particular I'm doing a python curses
>implementation where it's parsing keys as they are pressed with different
>case parts when special keys are hit.  Rather than doing this with a set of
>``if'' statements, this could be done using exceptions, perhaps as in the
>code below.
># start
>import curses
>import curses.ascii as ascii
>keyf1 = 'key F1 pressed'
>keyf2 = 'key F2 pressed'
>keyf3 = 'key F3 pressed'
>keyf4 = 'key F4 pressed'
># ...
>def getchar(win):
>         '''Get printable character from curses window'''
>         while True:
>                 c = win.getch()
>                 if ascii.isprint(c) : return c
>                 if c == curses.KEY_F1 : raise keyf1
>                 if c == curses.KEY_F2 : raise keyf2
>                 if c == curses.KEY_F3 : raise keyf3
>                 if c == curses.KEY_F4 : raise keyf4
>                 curses.beep()
>win = something_to_initialize_curses_window()
>while True:
>         try:
>                 c = getchar(win)
>         except keyf1:
>                 process_keyF1()
>         except (keyf2, keyf3):
>                 process_keyf2andf3()
>         except keyf4:
>                 process keyf4()
>         # ...
>INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
>UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
>FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
>URL: http://www.celestial.com/
>``I have no reason to suppose that he, who would take away my Liberty, would
>not when he had me in his Power, take away everything else.''  John Locke
>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list