On Mon, 30 Mar 2020 23:27:19 +0200 Jimmy Thrasibule <jimmy.thrasib...@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 _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/DGUP3WAOVLVC74TIOCVTMKMZKORTTON3/ Code of Conduct: http://python.org/psf/codeofconduct/