@contextmanager Wraps Transactions

Turn setup and teardown into a @contextmanager generator: commit on clean exit, roll back and re-raise on error, all without a class.

PythonData Integrity

Code

pythonsnippet
25 lines
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

Output

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

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

What the code does

Structurally, expect the function transaction and nothing else.

else and RuntimeError appears at a raise inside an except handler — it fires only while that failure type is already being handled.

The input store is mutated in place — callers that need the original must pass a copy.

What to watch for

  • Install step: none; the snippet lives entirely in the standard library.
  • store is mutated in place — the value you pass will not be the same afterward.

Using it

Signature: def transaction(store)

Look for the rolled back, committed: prefixes when the file runs; they tie each line to its step.

Import transaction from the file and call it — the rest of the code is implementation detail.

Key statements

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

Interactive Tools for This Topic

FAQ

Does `transaction` modify its input?
Yes — `store` is mutated in place. Pass a copy if the caller needs the original preserved.
When is the exception raised?
Inside an `except` handler — the `else` and `RuntimeError` fires only while that failure type is already being handled, not on its own trigger.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `contextlib`. The file defines `transaction` at load time.