Junior — Middle
Which decorator pattern is recommended for implementing transaction management?
sobes.tech AI
Answer from AI
In Python, transaction management is often handled using a decorator pattern that wraps a function or method, providing automatic start, commit, and rollback of transactions. Such a decorator typically:
- Starts a transaction before calling the function.
- Executes the function.
- If the function completes successfully, performs a commit.
- If an exception occurs, performs a rollback.
An example of a simple decorator for transaction management:
from functools import wraps
def transactional(session):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
result = func(*args, **kwargs)
session.commit()
return result
except Exception:
session.rollback()
raise
return wrapper
return decorator
# Usage:
# @transactional(db_session)
# def some_db_operation():
# ...
This approach allows centralized and transparent transaction management, improving code readability and reliability.