How best to write this try/except block?

Roy Smith roy at panix.com
Wed Apr 3 11:40:40 EST 2002


I've got a dictionary d, which may or may not have a value I'm looking
for.  If it does, I want to do a few things.  If it doesn't, I want to
do a few other things.  I could write:

try:
    value = d[key]
    foo = stuff (value)
except KeyError:
    foo = otherStuff (key)

which is fine as long as I can guarantee (hint: I can't) that stuff()
doesn't raise a KeyError.  The alternative would be something like:

foundIt = 0
try:
    value = d[key]
    foundIt = 1
except KeyError:
       foo = otherStuff (key)

if (foundIt):
   foo = stuff (value)

but that's exceptionally ugly.  Any suggestions for how better to
write this?




More information about the Python-list mailing list