Codectionary / Developer documentation / Python

Custom Context Managers

contextmanager turns a generator function into a with-statement resource manager. Code before yield sets up the resource and finally performs cleanup even after a body exception. Run as a Python 3.11+ script.

Syntax

@contextmanager
def resource():
    try: yield value
    finally: cleanup()

Examples

Custom Context Managers

Run as a Python 3.11+ script.

from contextlib import contextmanager
@contextmanager
def session():
    print("open")
    try:
        yield {"ready": True}
    finally:
        print("close")
with session() as state:
    print(state["ready"])
  1. Expected output: open True close
  2. yield provides the value bound by as. The finally block runs when the with block exits, including exceptional exits.

Best practices

  • Yield exactly once in a contextmanager generator.
  • Place cleanup in finally and avoid swallowing exceptions unintentionally.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading