Python Snippet

Custom Context Manager via contextlib

Difficulty: Medium

`@contextlib.contextmanager` turns a generator into a context manager: code before the `yield` is the setup, the yielded value is bound by `as`, and code after the `yield` is the teardown. It removes most of the class boilerplate when you do not need shared state. This entry covers the basic pattern, exception handling with try/finally, and `contextlib.suppress` as a one-liner.

Code Snippets
/

Custom Context Manager via contextlib

Custom Context Manager via contextlib

`@contextlib.contextmanager` turns a generator into a context manager: code before the `yield` is the setup, the yielded value is bound by `as`, and code after the `yield` is the teardown. It removes most of the class boilerplate when you do not need shared state. This entry covers the basic pattern, exception handling with try/finally, and `contextlib.suppress` as a one-liner.

Python
Medium
3 snippets
py-context-managers
py-decorators
py-standard-library

967 views

17

The generator runs once: code before yield is the __enter__ body, the yielded object is bound by as, and code after yield is the __exit__ body. Wrapping the post-yield code in try / finally is mandatory when teardown must run on exceptions too: without it, an exception from the body skips the cleanup. The decorator handles the boilerplate of building a class with __enter__ and __exit__, so the implementation reads top-to-bottom like normal code. Use this pattern for stateless, run-once setup-and-teardown helpers.