lisa.utils.destroyablecontextmanager#
- lisa.utils.destroyablecontextmanager(f)[source]#
Similar to
contextlib.contextmanager()but treats all cases ofyieldas an exception.This forces the user to handle them as such, and makes it more apparent that the
finallyclause intry/yield/finallyalso catches the case where the context manager is simply destroyed.The user can handle
ContextManagerExitto run cleanup code regardless of exceptions but not when context manager is simply destroyed without calling__exit__()(standard behavior of context manager not created withcontextlib.contextmanager()).Handling exceptions is achieved by handling
ContextManagerExcep, with the original exception stored in theeattribute.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.