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

Jacob Holm jh at improva.dk
Wed Oct 19 16:03:31 CEST 2011


On 2011-10-19 04:14, 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?
> 
> 


How about a not-so-tricky solution using context managers?  Something
like (untested):

import contextlib

@contextlib.contextmanager
def atwithexit():
    handlers = []
    try:
        yield handlers.append
    finally:
        for h in reversed(handlers):
            h()


def my_fun():
    with atwithexit() as atreturn:
        allocate_res1()
        atreturn(cleanup_res1)
        # do stuff
        allocate_res2()
        atreturn(cleanup_res2)
        # do stuff
        allocate_res3()
        atreturn(cleanup_res3)
        # do stuff
        return


HTH

 - Jacob





More information about the Python-ideas mailing list