1 min read

Python Contextlib Module

The contextlib module provides utilities for common tasks involving the with statement.

Importing the Module

import contextlib

contextmanager

The @contextmanager decorator is a generator-based factory for context managers. It lets you define a context manager using a simple generator function, instead of creating a class with __enter__ and __exit__ methods.

from contextlib import contextmanager

@contextmanager
def my_context():
    print("Entering")
    yield "value"
    print("Exiting")

with my_context() as val:
    print(f"Inside with {val}")
# Output:
# Entering
# Inside with value
# Exiting

closing

The closing() function returns a context manager that closes things upon completion of the block. This is useful for objects that have a close() method but don't support the context manager protocol.

from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('http://www.python.org')) as page:
    for line in page:
        print(line)
        break

suppress

suppress(*exceptions) returns a context manager that suppresses any of the specified exceptions if they occur in the body of the with statement.

from contextlib import suppress
import os

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

redirect_stdout

Context manager for temporarily redirecting sys.stdout to another file-like object.

from contextlib import redirect_stdout
import io

f = io.StringIO()
with redirect_stdout(f):
    print('foobar')

print('Got:', f.getvalue())
# Output: Got: foobar

programming/python/python