Transaction Context Manager with Rollback
Wrap state changes in a context manager that commits on success, restores a snapshot on any exception, and re-raises the error.
Code
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any
class TransactionAborted(RuntimeError):
pass
@dataclass
class Store:
data: dict[str, Any] = field(default_factory=dict)
commits: int = 0
rollbacks: int = 0
@contextmanager
def transaction(self) -> Iterator["Transaction"]:
snapshot = dict(self.data)
tx = Transaction(self)
try:
yield tx
except BaseException:
self.data = snapshot
self.rollbacks += 1
raise
else:
self.commits += 1
@dataclass
class Transaction:
store: Store
def set(self, key: str, value: Any) -> None:
self.store.data[key] = value
def delete(self, key: str) -> None:
self.store.data.pop(key, None)
def main() -> None:
store = Store(data={"balance": 100})
with store.transaction() as tx:
tx.set("balance", 80)
tx.set("currency", "USD")
print(store.data, store.commits, store.rollbacks)
try:
with store.transaction() as tx:
tx.set("balance", 0)
raise TransactionAborted("payment declined")
except TransactionAborted as error:
print("rolled back:", error)
print(store.data, store.commits, store.rollbacks)
if __name__ == "__main__":
main()
How it works
The working surface is the classes TransactionAborted and class and the functions transaction, set, delete and main — everything else is wiring.
else and TransactionAborted appears at a raise inside an except handler — it fires only while that failure type is already being handled.
Applying it
The main signature reads def transaction(self) -> Iterator["Transaction"]
The demo output is labeled (rolled back:), so every printed line maps back to its originating operation.
Execute the file and main walks through transaction and set, in that order.
Statements that matter
def set(self, key: str, value: Any) -> None:
self.store.data[key] = value
def delete(self, key: str) -> None:
self.store.data.pop(key, None)
def transaction(self) -> Iterator["Transaction"]:
snapshot = dict(self.data)
tx = Transaction(self)
try:
yield tx
except BaseException:
self.data = snapshot
self.rollbacks += 1
raise
else:
self.commits += 1
Interactive Tools for This Topic
FAQ
- When is the exception raised?
- Inside an `except` handler — the `else` and `TransactionAborted` fires only while that failure type is already being handled, not on its own trigger.
- What does Transaction Context Manager with Rollback print when run?
- The script runs standalone; its 1 labeled outputs include `rolled back:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.