How best to write this try/except block?

Roy Smith roy at panix.com
Wed Apr 3 18:32:37 EST 2002


Michael Hudson <mwh at python.net> wrote:
> try:
>     value = d[key]
> except KeyError:
>     foo = otherStuff(key)
> else:
>     foo = stuff(value)

Duh.  Been writing 4 Python for 4 years now, and while I'm sure I once knew 
that try blocks could have else clauses, I had just plain forgotten I ever 
knew it.  It's exactly what I was looking for.

Well, almost.  It's slightly annoying that the main flow of control is 
broken into two pieces; one in the try clause, the other in the else 
clause.  But it's a lot better than the alternatives I had come up with.



More information about the Python-list mailing list