Dependency injection
suggest changeDependency injection (DI) means that an object or function receives the things it depends on (a database, an HTTP client, a clock, a logger) from the outside instead of creating them itself.
In Python you rarely need a framework for this. Passing arguments to __init__ or to a function is dependency injection. The rest of this article shows how to do it well.
The problem: hard-coded dependencies
import smtplib
from datetime import datetime
class Notifier:
def __init__(self):
self.smtp = smtplib.SMTP("mail.example.com", 587)
def remind(self, user_email: str) -> None:
now = datetime.now()
if now.hour < 9:
return
self.smtp.sendmail("noreply@example.com", [user_email], "Reminder!")
This class is hard to test and hard to reuse:
- creating a
Notifieropens a network connection - you can't swap SMTP for another mail provider without editing the class
- the behaviour depends on the real wall clock, so tests that check the "before 9am" rule are flaky
Constructor injection
Move the creation of the dependencies out of the class and pass them in:
from datetime import datetime
from typing import Callable, Protocol
class MailSender(Protocol):
def send(self, to: str, body: str) -> None: ...
class Notifier:
def __init__(self, mailer: MailSender, now: Callable[[], datetime] = datetime.now):
self.mailer = mailer
self.now = now
def remind(self, user_email: str) -> None:
if self.now().hour < 9:
return
self.mailer.send(user_email, "Reminder!")
Notifier now depends only on an abstraction: "something with a send(to, body) method" and "a callable that returns the current time".
typing.Protocol (Python 3.8+) describes the interface structurally. Any class with a matching send method satisfies it; it doesn't have to inherit from MailSender. Type checkers such as mypy or pyright verify this; at runtime nothing is enforced, which is ordinary duck typing.
If you prefer explicit inheritance and a runtime check that all methods are implemented, use an abstract base class from abc instead of a Protocol.
A real implementation:
import smtplib
from email.message import EmailMessage
class SmtpMailSender:
def __init__(self, host: str, port: int, sender: str):
self.host = host
self.port = port
self.sender = sender
def send(self, to: str, body: str) -> None:
msg = EmailMessage()
msg["From"] = self.sender
msg["To"] = to
msg["Subject"] = "Notification"
msg.set_content(body)
with smtplib.SMTP(self.host, self.port) as smtp:
smtp.starttls()
smtp.send_message(msg)
Testing with fakes
Because dependencies are passed in, tests can pass simple fakes. No patching of module globals is needed:
from datetime import datetime
class FakeMailSender:
def __init__(self):
self.sent: list[tuple[str, str]] = []
def send(self, to: str, body: str) -> None:
self.sent.append((to, body))
def test_no_reminder_before_9am():
mailer = FakeMailSender()
n = Notifier(mailer, now=lambda: datetime(2024, 1, 1, 8, 30))
n.remind("bob@example.com")
assert mailer.sent == []
def test_reminder_after_9am():
mailer = FakeMailSender()
n = Notifier(mailer, now=lambda: datetime(2024, 1, 1, 10, 0))
n.remind("bob@example.com")
assert mailer.sent == [("bob@example.com", "Reminder!")]
You can also pass a unittest.mock.Mock(spec=SmtpMailSender) when you want to assert on calls, but hand-written fakes are often clearer and catch more mistakes.
Function parameters are injection too
DI isn't only for classes. A function can take its dependencies as parameters, usually keyword-only with a sensible default:
import time
import urllib.request
def fetch_with_retry(url: str, *, attempts: int = 3,
opener=urllib.request.urlopen,
sleep=time.sleep) -> bytes:
for i in range(attempts):
try:
with opener(url, timeout=10) as resp:
return resp.read()
except OSError:
if i == attempts - 1:
raise
sleep(2 ** i)
raise AssertionError("unreachable")
Production code calls fetch_with_retry(url). A test passes a fake opener and sleep=lambda s: None so it runs instantly.
Default arguments are evaluated once, at definition time. Defaulting to a function like time.sleep is fine. Don't default to an object with state, such as client=HttpClient(), because every call would share that single instance. Use None and create the object inside the function instead.
The composition root
Somebody still has to create the real objects. Do it in one place, close to the program's entry point. This place is called the composition root:
import os
def build_app() -> Notifier:
mailer = SmtpMailSender(
host=os.environ.get("SMTP_HOST", "localhost"),
port=int(os.environ.get("SMTP_PORT", "587")),
sender="noreply@example.com",
)
return Notifier(mailer)
def main() -> None:
notifier = build_app()
notifier.remind("bob@example.com")
if __name__ == "__main__":
main()
Only build_app knows about concrete classes and configuration. The rest of the code depends on interfaces. When the graph of objects grows, build_app grows with it, but it stays plain, readable Python.
Factories and lazily created dependencies
Sometimes an object needs to create new dependencies on demand, for example one database connection per job. Inject a factory (any callable) instead of an instance:
import sqlite3
from typing import Callable
class JobRunner:
def __init__(self, connect: Callable[[], sqlite3.Connection]):
self.connect = connect
def run(self, job_id: int) -> None:
conn = self.connect()
try:
with conn: # commits on success, rolls back on exception
conn.execute("UPDATE jobs SET done = 1 WHERE id = ?", (job_id,))
finally:
conn.close()
runner = JobRunner(lambda: sqlite3.connect("jobs.db"))
functools.partial is handy for building such factories: partial(sqlite3.connect, "jobs.db").
Dependency injection in FastAPI
Some frameworks have DI built in. In FastAPI you declare dependencies with Depends, and the framework calls the provider for each request:
from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
class UserRepo:
def get_name(self, user_id: int) -> str:
return f"user-{user_id}"
def get_repo() -> UserRepo:
return UserRepo()
@app.get("/users/{user_id}")
def read_user(user_id: int, repo: Annotated[UserRepo, Depends(get_repo)]):
return {"name": repo.get_name(user_id)}
In tests you replace a provider without touching the endpoint:
from fastapi.testclient import TestClient
class FakeRepo:
def get_name(self, user_id: int) -> str:
return "fake"
app.dependency_overrides[get_repo] = lambda: FakeRepo()
client = TestClient(app)
assert client.get("/users/1").json() == {"name": "fake"}
app.dependency_overrides.clear()
A provider can also be a generator that yields the dependency. The code after yield runs when the request is done, which is a good place to close a database session.
DI containers
Libraries such as dependency-injector, injector, punq or lagom provide containers that wire objects together automatically, often based on type hints. They can help in large applications with many long-lived services, scopes and configuration-driven wiring.
For most Python programs they are unnecessary. Start with constructor arguments and a hand-written composition root; reach for a container only when that function becomes genuinely painful to maintain.
Guidelines
- Inject things that do I/O or are non-deterministic: databases, network clients, filesystem access, clocks, random number generators.
- Don't inject everything. Pure helper functions and value objects can be imported and used directly.
- Depend on the narrowest interface you need. A
Protocolwith one method is easier to fake than a whole client class. - Keep construction (composition root) separate from use (business logic).
- If a constructor takes many dependencies, the class probably does too much. Split it.
- Prefer passing dependencies explicitly over
unittest.mock.patch. Patching works, but it couples tests to import paths and hides what code really depends on.