Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

How do you write your own context manager?

AdvancedConceptExceptions, context managers, files & logging
Answer

The easy way is contextlib.contextmanager: code before yield is setup, after yield is teardown, and wrap the yield in try/finally so teardown runs on errors.

from contextlib import contextmanager
import os

@contextmanager
def chdir_temp(path):
    old = os.getcwd()
    os.chdir(path)
    try:
        yield path
    finally:
        os.chdir(old)

Python 3.11 ships contextlib.chdir for this exact case. For class-based managers implement __enter__ and __exit__(exc_type, exc, tb); returning True from __exit__ suppresses the exception.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging