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.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?Beginner