[Python-ideas] Avoiding nested for try..finally: atexit for functions?

Andrew Bennetts andrew at bemusement.org
Wed Oct 19 06:02:14 CEST 2011


On Tue, Oct 18, 2011 at 10:14:56PM -0400, Nikolaus Rath wrote:
[...]
> I would much rather have something like this:
> 
> def my_fun():
>     allocate_res1()
>     atreturn.register(cleanup_res1)
>     # do stuff
>     allocate_res2()
>     atreturn.register(cleanup_res2)
>     # do stuff
>     allocate_res3()
>     atreturn.register(cleanup_res3)
>     # do stuff
>     return
> 
> Has the idea of implementing such "on return" handlers ever come up?
> Maybe there is some tricky way to do this with function decorators?

The "with" statement is a good answer.  If for some reason you need to
be compatible with version of Python so old it doesn't have it, then try
the bzrlib.cleanup module in bzr.  It implements the sort of API you
describe above.

And there are times when an API like that might be nicer to use anyway,
e.g. when you have conditional allocations like:

def foo():
    res1 = allocate_res1()
    add_cleanup(res1.release)
    ...
    if cond:
        res2 = allocate_res2()
        add_cleanup(res2.release)
    res3 = allocate_res3()
    add_cleanup(res3.release)
    ...
    do_stuff()

And avoiding the cascading indents of multiple with statements can be
nice too.

-Andrew.




More information about the Python-ideas mailing list