← 中文资源

简体中文版本

@contextmanager 包装事务提交回滚

@contextmanager 用 yield 前后两段语句描述进入与退出:正常退出提交、异常回滚并重新抛出,不需要手写 __enter__/__exit__ 类。

阅读英文原文

运行结果

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

committed: ['_begun', '_committed', 'item']
rolled back

实现说明

逻辑集中在函数 transaction里。 一次 else、RuntimeError 的 raise 写在 except 块里,因此它以那个失败先被触发为前提。 入参 store 会被原地修改——调用方若要保留原值需先拷贝。

使用要点

  • 直接运行文件,输出会带上标签,比如 rolled back、committed:——输出的每一行都能指回产生它的那次调用。
  • store 是原地修改,传进去的值之后就不一样了。
  • 值得导入的表面是 transaction;周围的辅助代码对片段是私有的。

常见问题

transaction 会修改传入的参数吗?

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

异常在什么时候抛出?

在 except 处理器内部——else、RuntimeError 只在该失败类型已被触发处理时才会抛出,没有独立的触发条件。

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 全部导入都来自标准库:contextlib。 文件在加载时定义 transaction。

签名一览:def transaction(store)

核心语句

with transaction({}) as tx:
    tx["item"] = 42
with transaction({}) as tx:
    tx["item"] = 7
    raise RuntimeError("boom")
def transaction(store):
    store["_begun"] = True
    try:
        yield store              # with 体在这里执行
    except Exception:
        store.clear()            # 回滚:丢弃本次全部写入
        print("rolled back")
        raise
    else:
        store["_committed"] = True
        print("committed:", sorted(store))

代码示例

from contextlib import contextmanager

# @contextmanager 用 yield 前后两段语句描述进入与退出,省去手写 __enter__/__exit__
@contextmanager
def transaction(store):
    store["_begun"] = True
    try:
        yield store              # with 体在这里执行
    except Exception:
        store.clear()            # 回滚:丢弃本次全部写入
        print("rolled back")
        raise
    else:
        store["_committed"] = True
        print("committed:", sorted(store))

with transaction({}) as tx:
    tx["item"] = 42

try:
    with transaction({}) as tx:
        tx["item"] = 7
        raise RuntimeError("boom")
except RuntimeError:
    pass