Skip to content

dependency injection (DI)

Dependency injection (DI) is a technique in which an object receives the other objects it needs from an outside source, rather than building them itself. Those supplied objects are its dependencies. DI is a specific form of inversion of control (IoC), the broader idea that surrounding code, not the component, decides which concrete implementations get wired together.

The pattern separates building an object from using it. The client is the object with a need, the service is what it needs, and the injector creates the service and supplies it. Because the client refers only to an abstract type, the injector can hand it any compatible implementation without changing the client’s own code. The diagram below contrasts an object that builds its own dependency with one whose dependency is injected:

Without DI a client builds its concrete service. With DI an injector supplies it behind a service interface.
Injecting a Service Loosens the Client's Coupling

Dependencies usually reach a client in a few standard ways:

  • Constructor injection passes them as arguments when the object is built, so it starts life in a valid state. It’s the form to reach for first.
  • Setter injection assigns them afterward through dedicated setter methods, trading that guarantee for flexibility.
  • Method injection hands a dependency to the one method that needs it.
  • Interface injection has the dependency expose an injector method that pushes itself into any client handed to it. It’s the least common of the four, since it means writing extra interfaces just to enable injection.

Injecting dependencies loosens the coupling between a client and the concrete types it uses, which makes code easier to reconfigure and to test. A test can pass in a stub or a mock instead of a real service, isolating the unit under examination. Large systems often rely on a DI container to wire these object graphs automatically.

OOP in Python 3

Tutorial

Object-Oriented Programming (OOP) in Python

In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.

intermediate python

For additional information on related topics, take a look at the following resources:


By Martin Breuss • Updated Aug. 8, 2026