On this page
contextlib.nullcontext
Prev: contextlib.ExitStack | Up: contextlib | Next: contextlib.redirect_stderr
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.nullcontext
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import nullcontext
Signature & Overview
contextlib.nullcontext(enter_result=None)
Context manager that does no additional processing.
Usage
from contextlib import nullcontext
import io
def write_report(target: io.StringIO | None) -> str:
cm = nullcontext(target) if target is not None else nullcontext(io.StringIO())
with cm as buf:
buf.write("ok")
return buf.getvalue()
assert write_report(None) == "ok"
Gotchas
- Eliminates duplicated
withbranches: Ideal when a lock, file, or transaction is optional (with (lock or nullcontext()):). - Does not close
enter_result:nullcontext(obj)simply yieldsobjand does nothing on exit.
REPL Inspect
from contextlib import nullcontext
help(nullcontext)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/ExitStack Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/redirect_stderr Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/chdir shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/closing shared tags: #contextlib, #stdlib