try: finally: question

Peter Hansen peter at engcorp.com
Wed Jul 7 19:44:10 CEST 2004


djw wrote:

> Peter Hansen wrote:
>>Hmm... Also, I think it really *is* unusual (as in, "not usual"
>>meaning not really common) to nest try blocks.  
> 
> I am suprised that what I am trying to accomplish is unusual. Basically, I
> want to acquire some resource/object (that requires cleanup). 

It *is* unusual, in the way I mean, because relatively little code
is involved with resource cleanup when it's required (in Python,
anyway), and relatively little resource cleanup is required when
programming, in general.

> This seems like a really normal bit of code to me. 

Maybe I'm drawing too fine a line here.  I'm using "usual" and
"unusual" in the sense of "frequently occurring or not", rather than
in the sense of "normal or really weird".

It's very normal.  It's just not so frequently occurring that
the nested finally/except should be seen as a major roadblock.
Not that one example tells much about the general case, but: I
just wrote a little inventory-tracking application, very small.
It has one finally (for a database commit), and two excepts
(basically around things that could have been if/thens but
are slightly cleaner as exception handling code).  None of
these cases required bringing in a nested try.  I think that's
the "usual" pattern.

If you find yourself needing to write such things very often,
I think you're probably not writing your code in a very modular
way, as it would then be more reusable and therefore require
being written much less often...

-Peter



More information about the Python-list mailing list