How to write your own context manager in Python

Learn how to write your own context manager in Python with the contextlib.contextmanager decorator


Learn how to write your own contextmanager in Python with the contextlib.contextmanager decorator.

Context managers are great for resource management. They allow us to allocate and release resources precisely, and make sure to properly free up the resources in case of exceptions. A well-known example is the with open() statemtent:

with open('notes.txt', 'w') as f:
    f.write('some todo...')

An easy way to implement our own context manager is by using the contextlib.contextmanager decorator.

To apply this, decorate a function with @contextmanager and then implement the following:

  • Use a try-finally block
  • The try block must yield the resource using the yield keyword
  • The finally block is used to free up the resource

Here's an abstract example for this:

from contextlib import contextmanager

@contextmanager
def managed_resource(*args, **kwargs):
    # Code to acquire resource, e.g.:
    resource = acquire_resource(*args, **kwargs)
    try:
        yield resource
    finally:
        # Code to release resource, e.g.:
        release_resource(resource)


# Use it:
with managed_resource(timeout=3600) as resource:
    # do something

Here's another example for our own context manager to handle file opening and closing:

from contextlib import contextmanager

@contextmanager
def open_managed_file(filename):
    f = open(filename, 'w')
    try:
        yield f
    finally:
        f.close()

with open_managed_file('notes.txt') as f:
    f.write('some todo...')

Another different approach is to write a context manager class. You can learn more about context managers and how to do this in this article.


FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏