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.

pythonarchitecturepatterns

See Also