Dependency Injection in Python Without a Framework
This article explains how dependency injection passes collaborators to Python objects and functions instead of creating them inside, how it simplifies testing, and which mistakes undo its benefits.
An object that creates the objects it depends on fixes, in its own code, which implementation it will use, and every change of implementation, including the replacement needed in a test, then requires editing or patching that code. The present article examines dependency injection, the technique of passing dependencies to an object or function from outside instead of letting it build them. It compares a hard-wired class with an injected one, shows how a test replaces a dependency without patching, extends the idea to functions such as clocks, describes where the dependencies of a program should be assembled, and analyses the mistakes that turn a simple technique into a source of shared state or excessive indirection. Deciding which implementation an object uses in one visible place, outside the object, is the secret weapon of dependency injection.
Hard-Wired Dependencies
A class whose constructor creates its collaborators is bound to them: the following coffee machine always uses an electric grinder, and nothing in its interface allows another one.
class ElectricGrinder:
def grind(self):
return "ground with electricity"
class CoffeeMachine:
def __init__(self):
self.grinder = ElectricGrinder()
def brew(self):
return f"coffee, {self.grinder.grind()}"
print(CoffeeMachine().brew()) # Output: coffee, ground with electricity
The class works, but its dependency is invisible from outside: a reader of the call CoffeeMachine() cannot tell that a grinder is involved, and a test that must avoid the real grinder, because it is slow, needs hardware or calls a network service, has to replace the name ElectricGrinder inside the module, the technique described in the article devoted to monkey patching.
Equipment Slots: Injecting Through the Constructor
Role-playing games give each character equipment slots: the character does not forge its own weapon, but equips whichever item fits the slot, and the same character can fight with a sword or a staff. Constructor injection applies the same rule to objects: the constructor declares a parameter for each dependency, and the caller supplies any object that offers the required interface, which typing.Protocol can state explicitly. The analogy, however, stops at this point, because a character usually changes equipment during play, whereas an injected dependency is normally fixed when the object is created and stays the same for its whole life.
from typing import Protocol
class Grinder(Protocol):
def grind(self) -> str: ...
class ElectricGrinder:
def grind(self):
return "ground with electricity"
class ManualGrinder:
def grind(self):
return "ground by hand"
class CoffeeMachine:
def __init__(self, grinder: Grinder):
self.grinder = grinder
def brew(self):
return f"coffee, {self.grinder.grind()}"
print(CoffeeMachine(ElectricGrinder()).brew()) # Output: coffee, ground with electricity
print(CoffeeMachine(ManualGrinder()).brew()) # Output: coffee, ground by hand
The class CoffeeMachine no longer mentions any concrete grinder, and neither grinder inherits from Grinder: the protocol only documents, for the reader and for a type checker, the method that a valid dependency must provide, as explained in the article devoted to advanced type hints. The dependency is now visible in the signature, which is the main gain of the technique: whoever creates the object sees what it needs.
Testing Without Patching
Since the dependency arrives through the constructor, a test can pass a fake object written for the purpose, which returns a fixed value and records how it was used.
class CoffeeMachine:
def __init__(self, grinder):
self.grinder = grinder
def brew(self):
return f"coffee, {self.grinder.grind()}"
class FakeGrinder:
def __init__(self):
self.calls = 0
def grind(self):
self.calls += 1
return "fake grounds"
fake = FakeGrinder()
machine = CoffeeMachine(fake)
print(machine.brew()) # Output: coffee, fake grounds
print(machine.brew()) # Output: coffee, fake grounds
print(fake.calls) # Output: 2
The test needs no knowledge of the module in which the real grinder is defined and no patching of global names, so it cannot leak a replacement into other tests. A unittest.mock.Mock can play the same role when recording calls in detail is useful, but the essential point is that the object under test receives its collaborator instead of looking it up.
Injecting Functions and Choosing Defaults
In Python, a dependency does not have to be an object with methods: a function is often enough, and the most frequent example is the clock. A function that reads the current time directly cannot be tested at a fixed moment, whereas one that receives the clock as a parameter can.
import time
def is_expired(token_created_at, ttl_seconds, now=time.time):
return now() - token_created_at > ttl_seconds
print(is_expired(1_000, 60, now=lambda: 1_030)) # Output: False
print(is_expired(1_000, 60, now=lambda: 1_100)) # Output: True
print(is_expired(time.time(), 60)) # Output: False
The default value time.time keeps the ordinary call short, while a test passes a function that returns a chosen instant. The default is the function itself, not the result of calling it, which is why it remains correct on every call. The same reasoning connects dependency injection with the Strategy pattern: an injected function is a strategy, and the difference lies in the purpose, since Strategy selects an algorithm while dependency injection decides where any collaborator comes from.
Pitfalls of Dependency Injection
Dependency injection moves the creation of objects to another place, and the errors appear when that place is chosen badly or when the technique is applied where it adds nothing. Six pitfalls are distinguished, which are the following:
- A default instance in the signature. A default such as
grinder=Grinder()is evaluated once, when the function is defined, so every object created without an explicit argument shares the same dependency. - Dependencies created everywhere. If every module builds its own collaborators, the technique is lost; the objects of a program should be assembled in one place, usually the entry point, called the composition root.
- Service locators. A global registry from which objects fetch their dependencies hides them again, because the signature no longer reveals what the object needs.
- Too many parameters. A constructor that receives eight dependencies usually belongs to a class with too many responsibilities; injection makes the problem visible but does not solve it.
- Injecting everything. Pure functions, the standard library and values that never vary gain nothing from being passed as parameters.
- Implicit containers. Frameworks that wire dependencies automatically are convenient, but they can make the origin of an object hard to trace; their use should be a deliberate decision, not a substitute for understanding the wiring.
The first pitfall is reproduced in the following example.
class Grinder:
def __init__(self):
self.uses = 0
def grind(self):
self.uses += 1
class SharedByAccident:
def __init__(self, grinder=Grinder()):
self.grinder = grinder
class OnePerMachine:
def __init__(self, grinder=None):
self.grinder = grinder if grinder is not None else Grinder()
a, b = SharedByAccident(), SharedByAccident()
a.grinder.grind()
b.grinder.grind()
print(a.grinder is b.grinder, b.grinder.uses) # Output: True 2
c, d = OnePerMachine(), OnePerMachine()
print(c.grinder is d.grinder) # Output: False
The two machines of the first class share a single grinder, created when the class was defined, so the use counted by one appears in the other. The sentinel None, replaced inside the constructor, creates a new grinder for each machine while keeping the dependency injectable.
Choosing How to Provide a Dependency
Consequently, the form of injection depends on how often the dependency varies and on who needs to replace it, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| An object needs a collaborator for its whole life | Constructor injection |
| Only one operation needs the collaborator | A parameter of that method or function |
| The dependency is a single behaviour, such as a clock | Inject a function, with a sensible default |
| A default implementation is usually right | Default None, created inside the constructor |
| Several objects must share one instance | Create it once in the composition root and pass it to each |
| A hard-wired dependency in code that cannot be changed | unittest.mock.patch, as a last resort in tests |
Conclusion
It is concluded that dependency injection consists of passing an object or function its collaborators instead of letting it create them, which makes those collaborators visible in its signature, replaceable in tests without patching and decided in a single place of the program. This magic needs no framework in Python, since constructor parameters, protocols, functions as values and the sentinel None provide everything it requires, and its main risks lie in shared defaults and in hiding the wiring again behind global registries. A related design lets an object delegate its behaviour to another object that it replaces as its situation changes, the State pattern, which is developed in a future article of this series.