← 中文资源

简体中文版本

用 contextlib.nullcontext 统一可选上下文分支

当锁或调试输出流可能为 None 时,用 contextlib.nullcontext 提供透明的空上下文管理器或默认返回值,避免在业务代码里重复书写两份 with 语句块。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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 |

实现说明

活动部件是函数 audit_scope、process_batch。 返回的是新建的值,不复用入参。

使用要点

  • 整个依赖故事就是语言版本本身。
  • 演示输出是带标签的(quiet :、audited:、sink :),每个操作都会留下自己的一行标注。
  • audit_scope 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

audit_scope 会修改传入的参数吗?

不会。代码构造并返回新值,入参保持原样,对共享或冻结的数据结构调用是安全的。

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 全部导入都来自标准库:contextlib、io。 文件在加载时定义 audit_scope、process_batch。

主签名形如 def audit_scope(log_sink: io.StringIO | None, label: str)

核心语句

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]

代码示例

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", " | "))