🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Repository and Unit of Work Patterns in Python

Python PatternsEnterprise PatternsđŸŸĸ Free Lesson

Repository and Unit of Work Patterns in Python

Domain code that imports the ORM is domain code that can only be tested with a database running. That single coupling is behind most of the pain in growing Python services: unit tests that need containers, business rules that cannot be reasoned about without reading query code, and a schema change that ripples through a dozen modules. The repository pattern severs the link by giving storage a collection-like interface — find, filter, add, remove — that the domain depends on and that infrastructure implements. The unit of work pattern complements it by making the transaction boundary an explicit object rather than a scatter of commit() calls.

Neither pattern is about persistence technology. The same interfaces support SQL today, an HTTP client tomorrow, and an in-memory fake in tests, which is precisely the point.


The leak you are plugging

Without a boundary, persistence concerns migrate into business logic: a method that both validates a discount and executes an UPDATE, a service that knows the session object, a test that must create three tables to check one arithmetic rule. The symptoms compound — every new query couples another module to the schema, and refactoring the data model becomes an all-repository affair rather than a change in one adapter.

python
# tangled: domain logic and SQL in the same method
def apply_discount(session, order_id, percent):
    order = session.query(Order).get(order_id)          # persistence detail
    if order.status != "OPEN":
        raise ValueError("cannot discount a closed order")
    order.total = order.total * (1 - percent / 100)     # business rule
    session.commit()                                     # transaction control

Splitting this into three parts — a domain rule that operates on an Order object, a repository that loads and saves orders, and a unit of work that owns the commit — costs three small files and buys the ability to test the rule with Order(total=100) and no infrastructure at all.

Repository: a collection over your storage

The interface should read like a collection of domain objects, not like a query language. Callers ask for find_by_email, not for a way to express a filter clause; they ask for add, not for a way to obtain a session. Every method speaks in domain nouns, which is what keeps SQL — or whatever replaces it — confined to one file.

python
from abc import ABC, abstractmethod

class UserRepository(ABC):
    @abstractmethod
    def find_by_id(self, user_id: str) -> "User | None":
        ...

    @abstractmethod
    def find_by_email(self, email: str) -> "User | None":
        ...

    @abstractmethod
    def add(self, user: "User") -> None:
        ...

    @abstractmethod
    def list_active(self) -> list["User"]:
        ...

class SqlUserRepository(UserRepository):
    def __init__(self, session):
        self._session = session

    def find_by_id(self, user_id):
        return self._session.query(User).filter(User.id == user_id).one_or_none()

    def find_by_email(self, email):
        return self._session.query(User).filter(User.email == email).one_or_none()

    def add(self, user):
        self._session.add(user)

    def list_active(self):
        return self._session.query(User).filter(User.active.is_(True)).all()

class InMemoryUserRepository(UserRepository):
    def __init__(self):
        self._rows: dict[str, "User"] = {}

    def find_by_id(self, user_id):
        return self._rows.get(user_id)

    def find_by_email(self, email):
        return next((u for u in self._rows.values() if u.email == email), None)

    def add(self, user):
        self._rows[user.id] = user

    def list_active(self):
        return [u for u in self._rows.values() if u.active]

The abstract base class is doing real work here, not ceremony: it documents the complete contract in one place, and it lets a test assert that the SQL implementation covers every method. Python duck typing would let you skip it, but then an incomplete fake surfaces as an AttributeError at three in the morning instead of at import time.

Unit of work: one transaction per use case

A unit of work collects every change made during a use case and commits them together, rolling all of them back if any fails. It also removes the commit() calls that otherwise spread through services, where one forgotten call leaves the database half-updated and a reviewer hunting for it.

python
class UnitOfWork:
    def __init__(self, session, users_factory=SqlUserRepository):
        self._session = session
        self.users = users_factory(session)
        self._committed = False

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        if exc_type is not None:
            self.rollback()
        elif not self._committed:
            self.commit()

    def commit(self):
        self._session.commit()
        self._committed = True

    def rollback(self):
        self._session.rollback()

def register_user(uow, email: str, plan: str):
    with uow:
        if uow.users.find_by_email(email):
            raise ValidationError("email", "already registered")
        user = User.new(email=email, plan=plan)
        uow.users.add(user)
        # commit happens here on the way out; rollback if anything raised

Making the unit of work a context manager is what makes the boundary unbreakable: the with block is the transaction, and the __exit__ logic means a developer cannot forget to roll back after an exception. Passing repositories as attributes of the unit of work also gives you one place to swap the storage implementation for tests.

Wiring without a framework

You do not need a dependency injection container to assemble this. A composition root — one function that builds the object graph for a request — is enough, and it keeps the construction order visible.

python
def handle_request(session_factory, request):
    with session_factory() as session:
        uow = UnitOfWork(session)
        if request.method == "POST":
            register_user(uow, request.json["email"], request.json["plan"])
            return {"status": "created"}, 201
        users = uow.users.list_active()
        return {"users": [u.dict() for u in users]}, 200

# tests substitute the whole graph in one line
fake_uow = UnitOfWork(DummySession(), users_factory=InMemoryUserRepository)

When the graph grows, promote the composition root to a small module and keep it the only place that knows about concrete classes. Domain modules then import only abstractions, which is the property that makes the whole structure pay off.

Watch for one subtle trap while wiring: repositories that each open their own session break the unit of work entirely, because two repositories would commit independently and the "one transaction" promise becomes fiction. Every repository belonging to a unit of work must share that unit's session, which is exactly why the factory takes the session as an argument rather than creating one internally. A single integration test that asserts "rollback undoes changes made through two repositories" is enough to keep that invariant from eroding as the codebase grows.

Patterns worth comparing

Several patterns occupy adjacent territory, and picking the wrong one produces either boilerplate or leakage.

PatternResponsibilityKey difference from repository
RepositoryCollection-like access to domain objectsSpeaks domain nouns, hides queries
Data access objectThin wrapper over a specific storage APIOften mirrors SQL shape rather than domain
GatewayBoundary to an external systemMay return DTOs, not domain entities
Unit of workTransaction boundary across repositoriesCoordinates commits, does not fetch
Active recordObject owns its own persistenceCouples domain to storage by design
ORM sessionIdentity map and change trackingInfrastructure primitive, not an abstraction

Active record deserves a particular note: it is entirely reasonable for a small application, and it becomes expensive exactly when business rules start needing to be tested without the database. Choose it knowingly rather than by default.

When enterprise patterns are the wrong size

These patterns carry real cost — more files, more indirection, more names to learn. For a script or a CRUD app with no business rules, repositories around every table is architecture astronautics, and a service module calling the ORM directly will be simpler and fine. The signal that you have crossed the line is when you cannot write a unit test for a business rule without a database session, or when a schema change forces edits in files that contain no queries. At that point the boundary pays for itself, and introducing it gradually — around the aggregate you are currently testing, not around every table at once — is both safer and more persuasive to a team than a big-bang refactor.

A practical migration order helps too. Start with the write side, where transactions and invariants matter most, because that is where an unguarded session does the most damage. Leave read-only reporting queries alone — they rarely benefit from an interface, and forcing them through a repository often just adds a method that forwards one query. When the team can name the boundary's benefit in a stand-up ("I tested the rule without the database"), the pattern has paid for itself; until then, keep the surface area small.

Common Mistakes

Letting repositories return ORM objects into domain services

Fix: Map to domain entities at the repository boundary so the ORM never leaks upward

Calling session.commit() inside individual methods

Fix: Let the unit of work own commit and rollback, one transaction per use case

Building repositories for every table before any rule needs them

Fix: Introduce the boundary around the aggregate you are actually testing

Faking repositories in tests without implementing the full contract

Fix: Have fakes subclass the ABC so missing methods fail at construction

Passing the session into domain functions for convenience

Fix: Pass the unit of work, which exposes repositories and nothing else

Best Practices

  • Design repository interfaces around the queries the domain needs, not around the schema
  • Make the transaction boundary a context manager so rollback is automatic
  • Keep one composition root that knows about concrete implementations
  • Map between storage rows and domain entities once, at the boundary
  • Introduce the pattern where tests hurt, not across the whole codebase at once

Key Takeaways

  • Repositories give storage a collection-like interface expressed in domain nouns
  • Abstract base classes document the contract and catch incomplete fakes early
  • A unit of work turns the transaction into an explicit, unbreakable boundary
  • In-memory implementations of the same interface make business rules testable in milliseconds
  • Right-size the pattern: no boundary for scripts, a hard boundary once rules multiply
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement