[Tutor] Try/Except, A better way?

Charlie Clark charlie@begeistert.org
Fri Mar 21 19:35:02 2003


On 2003-03-22 at 00:39:04 [+0100], tutor-request@python.org wrote:
> I currently use a few Try/Except clauses in my programming and was hoping 
> to find a better way to do certain things.

Jeff has already pointed out the importance of defining specific exceptions 
to raise and check for. I'm surprised he didn't mention dispatching 
dictionaries at the same time as he's expert at it and dispatching is a 
good alternative to if/elif/if or try/except. In Python you can use 
dictionaries to store conditions and function calls.

>>> d = {'a': print "a", 'b': print "b"}
>>> d = {'a': print_a, 'b': print_b}
>>> d['a']
<function print_a at 0x8003ac2c>
>>> d['a']()

Sorry for the over-simplification but others are better at this than I. You 
can use it like this, however assuming "x" is your condition

try d[x]():
	pass
except KeyError:
	print "forgot about this one"

It makes your code shorter and easier to maintain and once easier to 
understand it, once you've got it. Personally I'm still learning 
dispatching thanx to this list.

Charlie