How best to write this try/except block?

Chris Liechti cliechti at gmx.net
Wed Apr 3 14:14:19 EST 2002


roy at panix.com (Roy Smith) wrote in news:a8fba8$ln8$1 at panix2.panix.com:
> 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:

if d.has_key(key):
     foo = stuff(d[key])
else:
     foo = otherStuff(key)

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list