Inject Dependencies through Explicit Parameters
Core idea
Dependency injection supplies a collaborator from outside rather than constructing it inside the business operation. A function parameter or constructor is enough. Production and tests can provide different implementations of the same contract, including controlled errors. The caller that assembles components owns their lifetimes.
def stamp(message, clock): return f'{clock()}: {message}'print(stamp('ready', lambda: '09:00'))The fixed clock makes the result independent of wall time.
Expected output:
09:00: readyInject a sender
class Reporter: def __init__(self, send): self.send = send def report(self, code): self.send('done:' + code)messages = []Reporter(messages.append).report('A')print(messages)A list method acts as a test double that records the message.
Expected output:
['done:A']Common mistake
Avoid hidden global dependencies and giant containers for small programs. A substitute must respect the real collaborator contract; fake success does not establish integration correctness.
Practice
Inject a sender that raises a documented error, then test that the caller handles or propagates it according to a stated policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dependency injection
Check your understanding of dependency injection.
What is printed?
def f(read): return read()*2print(f(lambda: 6))What is printed?
out=[]def emit(send): send(3)emit(out.append)print(out)Who should construct the collaborator?
What does a fake sender not prove?