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

Nikolaus Rath Nikolaus at rath.org
Wed Oct 19 16:43:19 CEST 2011


Paul Moore <p.f.moore-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org> writes:
> On 19 October 2011 14:54, Nikolaus Rath <Nikolaus-BTH8mxji4b0 at public.gmane.org> wrote:
>>> 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.
>>
>> Yes, that's sort of what I was thinking about. I think the API is still
>> more convoluted than necessary, but that's probably because it works
>> with Python 2.4.
>>
>> Having thought about this a bit more, I think it should be possible to
>> use 'with' rather than decorators to implement something like this:
>>
>> with CleanupManager() as mngr:
>>     allocate_res1()
>>     mngr.register(cleanup_res1)
>>     # do stuff
>>     allocate_res2()
>>     mngr.register(cleanup_res2)
>>     # do stuff
>>     allocate_res3()
>>     mngr.register(cleanup_res3)
>>     # do stuff
>>
>> The mngr object would just run all the registered functions when the
>> block is exited.
>
> That's probably better than my decorator suggestion, because it allows
> you to limit the scope precisely, rather than just being
> function-scope. The CleanupManager class might make a good addition to
> contextlib, in actual fact...

What would be the best way to handle errors during cleanup? Personally I
would log them with logging.exception and discard them, but using the
logging module is probably not a good option for contextlib, or is it?


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