register cleanup handler

Neal Becker ndbecker2 at gmail.com
Fri Jul 24 18:01:58 CEST 2015


Laura Creighton wrote:

> In a message of Fri, 24 Jul 2015 10:57:30 -0400, Neal Becker writes:
>>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?
> 
> I think so.  Either that or I am badly misunderstanding you.  What is
> wrong with
> 
> try:
>    if (condition):
>       do_something_needing_cleanup
>    else:
>       do_something_else
>    code_executed_unconditionally
> finally:
>    do_cleanup
> 
> Laura

do_cleanup has do be done only if do_something_needing_cleanup was done 
first.

This would work, but is not very elegant.  I hope for a better way. 

need_cleanup = False
try:
   if (condition):
      do_something_needing_cleanup
      need_cleanup = True
   else:
      do_something_else
   code_executed_unconditionally
finally:
   if need_cleanup:
     do_cleanup




More information about the Python-list mailing list