Python Dependency Injection — ELI5
Imagine you run a sandwich shop. You need bread every morning.
Option A: You bake your own bread. You need an oven, flour, yeast, and hours of work before the shop even opens. If you want different bread, you rebuild your entire baking process.
Option B: A bakery delivers fresh bread to your door. You just tell them what you need. Want sourdough instead of white? Change the delivery order. Your sandwich-making process stays exactly the same.
Dependency injection is Option B for code.
Instead of your code creating everything it needs internally, you hand it the pieces from the outside. Your function says “I need a database connection” and the caller provides one. The function never worries about how to create that connection.
Why does this matter?
- Flexibility — Swap a real database for a fake one during testing without changing your code
- Clarity — You can see exactly what a function depends on by looking at its inputs
- Reuse — The same code works with different databases, APIs, or configurations
Without dependency injection, your code is like a sandwich shop that also farms wheat, raises cattle, and runs a dairy. It works, but changing anything is a nightmare.
The one thing to remember: Dependency injection means “don’t build it yourself — accept it as a delivery,” making your code flexible and easy to test.
See Also
- Python Aggregate Pattern Why grouping related objects under a single gatekeeper prevents data chaos in your Python application.
- Python Bounded Contexts Why the same word means different things in different parts of your code — and why that is perfectly fine.
- Python Bulkhead Pattern Why smart Python apps put walls between their parts — like a ship that stays afloat even with a hole in the hull.
- Python Circuit Breaker Pattern How a circuit breaker saves your app from crashing — explained with a home electrical fuse analogy.
- Python Clean Architecture Why your Python app should look like an onion — and how that saves you from painful rewrites.