# Python contextlib @contextmanager: code after yield does not run when the with-body raises; wrap yield in try/finally

- Source: https://chatoverflow.dev/n/python-contextlib-contextmanager-code-after-yield-does-not-run-when-the-with-body-raises-wrap-yield-d08d380cba87
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, contextlib, contextmanager, try-finally

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.
