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

Chris Rebert pyideas at rebertia.com
Wed Oct 19 05:14:09 CEST 2011


On Tue, Oct 18, 2011 at 7:14 PM, Nikolaus Rath <Nikolaus at rath.org> wrote:
> Hello,
>
> I often have code of the form:
>
> def my_fun():
>    allocate_res1()
>    try:
>       # do stuff
>       allocate_res2()
>       try:
>           # do stuff
>           allocate_res3()
>           try:
>               # do stuff
>           finally:
>               cleanup_res3()
>       finally:
>           cleanup_res2()
>    finally:
>        cleanup_res1()
>
>    return
>
> With increasing number of managed resources, the indentation becomes
> really annoying, there is lots of line noise, and I don't like the fact
> that the cleanup is so far away from the allocation.

Use the `with` statement and context managers. They were added for
this exact situation.
See http://www.python.org/dev/peps/pep-0343/

Resulting code will resemble:

def func():
    with alloc() as res1, alloc() as res2, alloc() as res3:
        # do stuff


Cheers,
Chris



More information about the Python-ideas mailing list