Python Glossary Русский

Python 3.7+contextlibterm

contextlib.nullcontext

no-op

A do-nothing placeholder context manager. Useful when a context manager is only sometimes needed (Python 3.7+).

Syntax

contextlib.nullcontext(enter_result=None)

The point is to avoid duplicating the same block in both branches of an if/else when the manager is only sometimes needed. Common trap: by default the as-variable is None, so if the body expects a real object (a file, say) pass it via enter_result. Since Python 3.10 it also works as an async context manager.

Examples

from contextlib import nullcontext
with nullcontext('value') as v:
    print(v) # → 'value'
from contextlib import nullcontext
def process(cm=None):
    with cm or nullcontext():
        return 42
print(process())  # → 42
print(process(nullcontext()))  # → 42

See also

Open in the full glossarydocs.python.orgReport an inaccuracy