On 19 October 2011 14:54, Nikolaus Rath
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... Paul.