nullcontext Simplifies Optional Context Guards

Use contextlib.nullcontext as a drop-in no-op context manager when a lock, trace, or writer is optional, avoiding duplicated with-block bodies.

PythonResilience

Code

snippet
from contextlib import contextmanager, nullcontext
import io

@contextmanager
def audit_scope(log_sink: io.StringIO | None, label: str):
    if log_sink is not None:
        log_sink.write(f"enter:{label}\n")
    try:
        yield label
    finally:
        if log_sink is not None:
            log_sink.write(f"exit:{label}\n")

def process_batch(items: list[str], sink: io.StringIO | None = None) -> list[str]:
    # nullcontext provides a transparent fallback when no audit guard is supplied
    guard = audit_scope(sink, "batch") if sink is not None else nullcontext("untracked")
    with guard as mode:
        return [f"{mode}:{item.upper()}" for item in items]

buf = io.StringIO()
print("quiet  :", process_batch(["a", "b"]))
print("audited:", process_batch(["a", "b"], sink=buf))
print("sink   :", buf.getvalue().strip().replace("\n", " | "))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

quiet  : ['untracked:A', 'untracked:B']
audited: ['batch:A', 'batch:B']
sink   :  | e | n | t | e | r | : | b | a | t | c | h | e | x | i | t | : | b | a | t | c | h |

Walkthrough notes — nullcontext Simplifies Optional Context Guards

Everything happens inside the functions audit_scope and process_batch.

It builds and returns a fresh value rather than reusing its inputs.

Watch out for

  • Ready as-is on a bare install of the language.

Using it

Entry signature: def audit_scope(log_sink: io.StringIO | None, label: str)

Printed runtime rows include tags — quiet :, audited:, sink : — when the file runs.

audit_scope is the public entry point; everything else in the file exists to support it.

Key statements

def audit_scope(log_sink: io.StringIO | None, label: str):
    if log_sink is not None:
        log_sink.write(f"enter:{label}\n")
    try:
        yield label
    finally:
        if log_sink is not None:
            log_sink.write(f"exit:{label}\n")
with guard as mode:
    return [f"{mode}:{item.upper()}" for item in items]

Interactive Tools for This Topic

FAQ

Does `audit_scope` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `contextlib`, `io`. The file defines `audit_scope`, `process_batch` at load time.