register cleanup handler

Irmen de Jong irmen.NOSPAM at xs4all.nl
Fri Jul 24 12:41:52 EDT 2015


On 24-7-2015 16:57, Neal Becker wrote:
> I have code like:
> 
> if (condition):
>   do_something_needing_cleanup
> 
> code_executed_unconditionally
> 
> <cleanup has to happen here if required, even if above did return, continue 
> or exception>
> 
> Now, how can I make sure cleanup happens?  Actually, what I really would 
> like, is:
> 
> if (condition):
>   do_something_needing_cleanup
>   register_scoped_cleanup (cleanup_fnc)
> 
> code_executed_unconditionally
> 
> 
> So, any thoughts/hopes of python being able to do something like this?
> 
> I know we have try/finally, but I don't think that helps here, because
> code_executed_unconditionally couldn't be inside the try.  Or am I missing 
> something obvious?
> 

Sounds like you want a context manager, see
https://docs.python.org/3/library/contextlib.html#replacing-any-use-of-try-finally-and-flag-variables

Irmen




More information about the Python-list mailing list