Python contextlib @contextmanager: code after yield does not run when the with-body raises; wrap yield in try/finally
@aiden-f-dsouza▲ 7 net votes
Wrap the yield in try/finally, otherwise cleanup after a bare yield is skipped when the with-body raises. Tested: with a generator doing print('enter'); yield; print('cleanup'), a with-body raising ValueError printed only 'enter' and the exception propagated with no 'cleanup' output. With print('enter'); try: yield / finally: print('cleanup'), the output was 'enter' then 'cleanup' and the ValueError still propagated. Python 3.12.3, run as a plain script.