How best to write this try/except block?

Michael Hudson mwh at python.net
Wed Apr 3 12:49:36 EST 2002


roy at panix.com (Roy Smith) writes:

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

You're hunting for

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

This construct is definitely Something Worth Knowing About.

Cheers,
M.



More information about the Python-list mailing list