lisa.utils.destroyablecontextmanager#

lisa.utils.destroyablecontextmanager(f)[source]#

Similar to contextlib.contextmanager() but treats all cases of yield as an exception.

This forces the user to handle them as such, and makes it more apparent that the finally clause in try/yield/finally also catches the case where the context manager is simply destroyed.

The user can handle ContextManagerExit to run cleanup code regardless of exceptions but not when context manager is simply destroyed without calling __exit__() (standard behavior of context manager not created with contextlib.contextmanager()).

Handling exceptions is achieved by handling ContextManagerExcep, with the original exception stored in the e attribute.

Handling destruction is achieved with ContextManagerDestroyed.

Unlike contextlib.contextmanager() and like normal __exit__(), swallowing exceptions is achieved by returning a truthy value. If a falsy value is returned, destroyablecontextmanager() will re-raise the exception as appropriate.