[Tutor] using exceptions to implement case/switch?

Alan Gauld alan.gauld at freenet.co.uk
Sat Oct 16 00:58:15 CEST 2004


> 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.

But you are using if statement anyway - the worst of both worlds.

The normal way would be a chain of elif statement.

> if ascii.isprint(c) : return c
> if c == curses.KEY_F1 : raise keyf1

  if c == curses.KEY_F1: process_keyF1()
  elif c == curses.KEY_F2: process_keyF2()


Or more efficiently still, put the key/functon pairs in
a dictionary:

keys = { curses.KEY_F1: process_keyF1,
         curses.KEY_F2: process_keyF2,
         ...
}

# code as before until:
if ascii.isprint(c) : return c
try: keys[c]()
except KeyError: print 'No such key'


HTH,

Alan G.



More information about the Tutor mailing list