← 中文资源

简体中文版本

上下文管理器资源生命周期

用 contextmanager 生成器包裹获取与释放:异常也触发清理,计时与连接池借还的样板代码集中到一处。

阅读英文原文

运行结果

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

using conn-2
pool after: ['conn-1', 'conn-2']
batch: 10.2ms

实现说明

底层就是函数 timed_section、pooled_connection。 失败路径是显式的——守卫条件成立就抛出 RuntimeError。 入参 pool 会被原地修改——调用方若要保留原值需先拷贝。

使用要点

  • 守卫 not pool 一旦成立就走提前的 raise,把后续流程挡掉。
  • 每一步打印都带着自己的标签:using、pool after:。
  • pool 是原地修改,传进去的值之后就不一样了。
  • 把 timed_section 当作 API:导入它,其余代码可以忽略。

常见问题

timed_section 会修改传入的参数吗?

会——pool 被原地修改。调用方需要保留原值时请先拷贝。

输入不合法时代码会怎么表现?

校验先行——RuntimeError 标记失败(位于 not pool),不会先做一半再失败。

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 全部导入都来自标准库:time、contextlib。 文件在加载时定义 timed_section、pooled_connection。

主签名形如 def timed_section(label: str)

核心语句

def pooled_connection(pool: list, label: str):
    """借还式资源管理:异常时也会归还连接。"""
    if not pool:
        raise RuntimeError("pool exhausted")
    conn = pool.pop()
    try:
        yield conn
    finally:
        pool.append(conn)  # finally 保证归还,等价于 try/finally 样板
with pooled_connection(pool, "job-a") as conn:
    print("using", conn)
    time.sleep(0.01)
def timed_section(label: str):
    """计时上下文:无论成功或异常都输出耗时。"""
    start = time.perf_counter()
    try:
        yield label
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed * 1000:.1f}ms")

代码示例

import time
from contextlib import contextmanager


@contextmanager
def timed_section(label: str):
    """计时上下文:无论成功或异常都输出耗时。"""
    start = time.perf_counter()
    try:
        yield label
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed * 1000:.1f}ms")


@contextmanager
def pooled_connection(pool: list, label: str):
    """借还式资源管理:异常时也会归还连接。"""
    if not pool:
        raise RuntimeError("pool exhausted")
    conn = pool.pop()
    try:
        yield conn
    finally:
        pool.append(conn)  # finally 保证归还,等价于 try/finally 样板


with timed_section("batch"):
    pool = ["conn-1", "conn-2"]
    with pooled_connection(pool, "job-a") as conn:
        print("using", conn)
        time.sleep(0.01)
    print("pool after:", pool)