A "scopeguard" for Python

Mike Kent mrmakent at gmail.com
Thu Mar 4 21:48:30 CET 2010

On Mar 3, 10:56 am, "Alf P. Steinbach" <al... at start.no> wrote:
> * Mike Kent:
> > What's the compelling use case for this vs. a simple try/finally?
> if you thought about it you would mean a simple "try/else". "finally" is always
> executed. which is incorrect for cleanup
> by the way, that's one advantage:
> a "with Cleanup" is difficult to get wrong, while a "try" is easy to get wrong,
> as you did here
>    ---
> another general advantage is as for the 'with' statement generally
> >    original_dir = os.getcwd()
> >    try:
> >        os.chdir(somewhere)
> >        # Do other stuff
> also, the "do other stuff" can be a lot of code
> and also, with more than one action the try-else introduces a lot of nesting
> >    finally:
> >        os.chdir(original_dir)
> >        # Do other cleanup
> cheers & hth.,
> - alf

Wrong?  In what way is my example wrong?  It cleanly makes sure that
the current working directory is the same after the try/finally as it
was before it.  Suboptimal, perhaps, in that the chdir in the finally
part is always executed, even if the chdir in the try part failed to
change the working directory.

That is a clear advantage to the code you presented, in that you have
the ability to register an 'undo' function only if the 'do' code
succeeded.  Your code also avoids a problem with many nested try/
finally blocks.  But for the simple chdir example you gave, I think
'wrong' isn't the word you were looking for regarding the try/finally
example I gave.

Anyway, I'll keep your code in mind the next time I want to avoid a
bunch of nested try/finally blocks.

More information about the Python-list mailing list