from types import TracebackType from django.db import transaction class DjangoUnitOfWork: """Wraps a use case in ``transaction.atomic``.""" def __init__(self) -> None: self._atomic: transaction.Atomic | None = None def __enter__(self) -> DjangoUnitOfWork: self._atomic = transaction.atomic() self._atomic.__enter__() return self def __exit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, ) -> None: assert self._atomic is not None self._atomic.__exit__(exc_type, exc, tb) self._atomic = None