Repository
A repository is an object that pretends to be an in-memory collection while loading and saving domain objects behind the scenes. Callers ask for an Order, not a SQL row.
Detailed Explanation
Application code that writes SQL (or SQLAlchemy queries) in every view is hard to test and hard to change. A repository exposes get(id), add(order), list_open(), and hides the storage. Tests supply an in-memory repository. Production supplies a SQL one. Both satisfy the same protocol.
The repository maps between two models. Inside: tables, columns, JSON documents. Outside: dataclasses or entities with behaviour. Do not return ORM instances from a repository if those instances stay attached to a session you cannot see. Return domain objects, or make the session the explicit unit of work.
A repository is not a second ORM. It does not need filter_by_* for every column. Add methods for queries you actually run. "Generic repository" with a magical find(spec) is an untyped query builder. Prefer list_overdue(today).
Transactions usually sit above the repository: a unit of work or a service calls several repositories and commits once. If each repository method commits, you cannot compose them safely.
Python's duck typing keeps this light. class OrderRepo(Protocol): def get(self, id: str) -> Order: ... is enough. You do not need a class hierarchy. Django's managers are a built-in repository-like layer; wrapping them is still useful when you want the domain to stay free of QuerySet.
Do not put HTTP or email in a repository. It loads and saves. Side effects belong in a service.
Code Examples
from typing import Protocol
class Order:
def __init__(self, id: str, cents: int):
self.id = id
self.cents = cents
class OrderRepo(Protocol):
def get(self, id: str) -> Order: ...
def add(self, order: Order) -> None: ...
class MemoryOrderRepo:
def __init__(self) -> None:
self._data: dict[str, Order] = {}
def get(self, id: str) -> Order:
return self._data[id]
def add(self, order: Order) -> None:
self._data[order.id] = order
def bump(repo: OrderRepo, id: str, extra: int) -> Order:
order = repo.get(id)
order.cents += extra
repo.add(order)
return order
repo = MemoryOrderRepo()
repo.add(Order("1", 100))
print(bump(repo, "1", 50).cents) # 150Common Gotchas
Returning a live ORM object tied to a closed session
`DetachedInstanceError` later. Map to a dataclass, or keep the session open for the request.
One repository method per column
the interface becomes the schema. Write use-case queries.
Commit inside every method
you cannot put two writes in one transaction. Let a unit of work commit.
An in-memory fake is a first-class implementation
if you cannot write one, the interface leaked storage types.