
On Mon, 30 Mar 2020 23:27:19 +0200 Jimmy Thrasibule <jimmy.thrasibule@gmail.com> wrote:
Now imagine that in my `try .. except` block I have some heavy setup to do before `do_something_sensitive()` and some heavy cleanup when the exception occurs.
I'd like my context manager to do the preparation work, execute the body, and cleanup. Or execute my else block only if there is no exception.
Is there already a way to accomplish this in Python or can this be a nice to have?
Perhaps you could use try/finally: try: prepare() do_something_sensitive() finally: cleanup() Whether the call to prepare goes inside or outside the try block depends on many things, mostly its coupling to the cleanup procedure (e.g., do they need to share objects? is cleanup idempotennt?). HTH, Dan -- “Atoms are not things.” – Werner Heisenberg Dan Sommers, http://www.tombstonezero.net/dan