Python etc / contextlib.nullcontext

Published: 01 October 2020, 18:00

Context manager contextlib.nullcontext is helpful when a block of code not always should be executed in a context.

A good example is a function that works with a database. If a session is passed, the function will use it. Otherwise, it creates a new session, and does it in a context to guarantee fallback logic to be executed:

from contextlib import nullcontext

def get_user(id, session=None):
    if session:
        context = nullcontext(session)
    else:
        context = create_session()
    with context as session:
        ...

Another example is optional suppressing errors:

from contextlib import suppress

def do_something(silent=False):
    if silent:
        context = suppress(FileNotFoundError)
    else:
        context = nullcontext()
    with context:
        ...

It was added in Python 3.7. For earlier Python versions DIY:

from contextlib import contextmanager

@contextmanager
def nullcontext(value=None):
    yield value

Another option is to use ExitStack.