Dependency injection
Dependency injection means a function or object receives its collaborators as arguments instead of importing and constructing them itself. Tests pass fakes; production passes the real clients.
Detailed Explanation
def charge(order, stripe=None): stripe = stripe or default_stripe() is a hidden global with extra steps. def charge(order, stripe: StripeClient): makes the dependency visible. The composition root — main, a FastAPI lifespan, a Django setup — builds StripeClient once and passes it down.
Python does not need a DI container for most apps. Constructor injection (Checkout(inventory, payments)) and function parameters are the pattern. Frameworks (FastAPI Depends, pytest fixtures) are containers you already use. A full injector library is justified when the graph is deep and you are tired of threading ten arguments by hand.
Injection inverts control. The object no longer imports a concrete email sender. It accepts any object with send(to, body). A Protocol documents that. The benefit is tests: Checkout(Inv(), Pay(), Mail()) with in-memory fakes, no monkeypatch of app.email.send.
Service locators (get_payments()) look like injection and hide the graph again. Prefer passing the instance. Monkeypatching module.client in tests is a smell that the production code imported a global.
Defaults for optional dependencies (clock=time.time) are fine when the default is a stdlib function. They are a trap when the default constructs a network client.
Create long-lived clients once. Injecting a new HTTP session per request is slow. Injecting a request-scoped DB session is correct. Match the lifetime to the resource.
Code Examples
class Mail:
def send(self, to: str, body: str) -> None:
raise NotImplementedError
class RecordingMail:
def __init__(self) -> None:
self.sent: list[tuple[str, str]] = []
def send(self, to: str, body: str) -> None:
self.sent.append((to, body))
def welcome(user: str, mail: Mail) -> None:
mail.send(user, "welcome")
inbox = RecordingMail()
welcome("ada@example.com", inbox)
print(inbox.sent) # [('ada@example.com', 'welcome')]class Checkout:
def __init__(self, mail: Mail):
self.mail = mail
def complete(self, user: str) -> None:
self.mail.send(user, "done")Common Gotchas
Importing the client inside the function "for convenience"
you cannot replace it without monkeypatch. Add a parameter.
A container that is a global
`inject("stripe")` is a service locator. You still have hidden coupling.
New expensive client per call
build it in `main` and inject the instance.
pytest fixtures are DI
`def test_ok(client):` is the same idea as a constructor parameter.