Deviopath › Python

Log Steps with a Context Manager

Medium · Context Managers

A with block runs setup code before the block and cleanup code after it, even if the block raises. With @contextlib.contextmanager, the code before yield is the setup and the code after it is the cleanup. Wrap the yield in try/except to see errors from the block, and re-raise them with a bare raise so they are not swallowed.

Write step(log, name) as a context manager:

- On entry, append "start <name>" to log. - If the block finishes normally, append "end <name>". - If the block raises, append "fail <name>: <ExceptionType>" (for example "fail save: ValueError") and re-raise the exception.

The driver run_steps is already written: it runs each step, makes some of them fail, and catches the error outside your with block.

Next: Spiral Order of a Matrix