Andrew Bennetts andrew-CCXH/aKPDeEYtQj7fl1lsA@public.gmane.org writes:
On Tue, Oct 18, 2011 at 10:14:56PM -0400, 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?
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.
Thoughts?
Best,
-Nikolaus