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

Nikolaus Rath Nikolaus at rath.org
Wed Oct 19 04:14:56 CEST 2011


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.

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?


Best, 

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C




More information about the Python-ideas mailing list