How best to write this try/except block?
Fredrik Lundh
fredrik at pythonware.com
Wed Apr 3 12:30:41 EST 2002
Roy Smith wrote:
> 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)
try:
value = d[key]
except KeyError:
foo = otherStuff(key)
else:
# found value, do stuff
foo = stuff(value)
> 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?
by following the Python style guide? ;-)
</F>
More information about the Python-list
mailing list