Dependency injection in Python
Tags: opensourcesecurity, engineering, python
Published: 2023-11-01 02:00:21

Dependency injection (DI) might sound complex, but it's really just about enhancing your code's flexibility. It's like giving your software a boost to be more adaptable and robust. And because Python is a popular coding language, understanding dependency injection is especially valuable. Think about creating software that's not only good but excellent — easy to adjust, expand, and secure. That's the essence of DI in Python.


If you're trying to figure out how to add dependency injection to your work, you've come to the right place. This tutorial will show you how DI works, how to use it, and how it can make your Python projects better.


How dependency injection works
------------------------------


To better understand how DI works, think of how a car is assembled. It wouldn't make much sense if every car had to create its own tires, right? In a car factory, tires are made separately and then attached to the car. This way, if a car needs different tires, they can switch them out. DI uses this same idea but in the world of software.


Imagine you're diving into a Python application. Inside, there's a class named `DatabaseClient` that needs specific details to connect to a database. Now, if you were to put these details inside the class directly, it would be like a car with tires that can't ever be changed. But with DI, instead of locking those details in, you provide (or inject) them from outside. This means that if, down the road, you want to change the details or try a different database, you can do so without tearing apart your entire application.


This approach offers numerous benefits. It's like having a toolbox where you can easily swap out tools depending on the job. Your software becomes more flexible; you can experiment and test with ease and make updates or fixes easily.


Next, take a look at some of the benefits of dependency injection to better understand why you need it.


Why you need dependency injection
---------------------------------


DI is all about giving you more control and making your coding life easier. Explore some of the key reasons why you should consider incorporating DI into your projects.


### Improves maintainability and testability of code


Dependency injection is a pattern that promotes the decoupling of components, making them less reliant on each other. This means that if a particular component or service needs an update or modification, you can make those changes without causing a ripple effect throughout the entire codebase.


Additionally, DI is a great fit for testing. When components are decoupled, it becomes far simpler for you to inject mock dependencies during unit tests. This enables you to test the behavior of individual parts in isolation, leading to more robust and comprehensive testing.


### Allows for easy swapping of dependencies


Have you ever faced the daunting task of switching technologies, like migrating from one database solution to another? With DI, transitions like this become significantly less challenging. Instead of reworking the whole class or module that interacts with the database, you merely need to alter the injected dependency. This flexibility can save you immense amounts of time and reduce the potential for errors during migrations or updates.


### Enhances modularity and reusability of code


Dependency injection encourages the design of components that aren't strictly bound to specific implementations. For you, this translates to greater modularity in your codebase. Modules or components developed with DI in mind can easily be reused across various parts of your application or even in entirely separate projects. This can speed up development timelines and foster a more consistent coding approach.


### Supports inversion of control


Traditional programming often sees classes instantiate and manage their own dependencies. With DI, this control is flipped on its head. Instead of the class having the responsibility, external entities (often a DI container or framework) handle the instantiation and provision of these dependencies. This [inversion of control (IoC)](https://en.wikipedia.org/wiki/Inversion_of_control) can simplify the management of dependencies and promote a cleaner, more organized architecture.


### Facilitates configurable application behavior


One of the subtle yet powerful advantages of DI is its ability to alter application behavior on the fly. By injecting different implementations of a dependency, you can modify how certain parts of your application function without rewriting vast amounts of code. Whether adapting to different runtime environments or catering to various user preferences, DI provides you with the flexibility to tailor application behavior.


Limitations of dependency injection in Python
---------------------------------------------


While DI offers many benefits, it's important to acknowledge that it comes with its own set of challenges and limitations. These limitations should be considered when deciding whether to incorporate DI into your Python projects:


* **Complexity:** DI fundamentally alters how components or objects are instantiated and managed in an application. For a sprawling, large-scale application, setting up DI requires a meticulous mapping of dependencies, interfaces, and the classes that implement them. This added layer can mean more boilerplate code, more configuration, and a steeper learning curve, particularly if you're transitioning an existing project to use DI. You need a deep grasp of your application's architecture to navigate this successfully.
* **Potential for confusion:** DI can be abstract. If you or your teammates are new to or unfamiliar with DI, you might find certain parts of the codebase puzzling. Instead of direct instantiation, objects are provided or injected, which can initially make tracing the flow of an application more difficult. This can lead to longer onboarding times for new developers or steeper learning curves.
* **Runtime errors:** DI frameworks often wire up dependencies at runtime. If there's a mismatch or a missing configuration, the application could crash or behave unexpectedly. These errors might not be evident during compilation or initial testing, making them trickier to diagnose and fix. Proper testing and understanding of DI can mitigate this, but it's a potential pitfall.
* **Performance overhead:** While the overhead is often negligible in many applications, the act of resolving and injecting dependencies at runtime can have a performance cost. This is especially pertinent in scenarios where every millisecond counts, like in high-frequency trading platforms. It's essential to benchmark and profile your application to understand this overhead and optimize where necessary.
* **Rollback challenges:** Because dependencies in DI are closely linked, if you introduce a change that leads to issues, reverting that change isn't always straightforward. Dependencies could have cascading effects, meaning a change in one area might affect multiple other components. As such, thorough testing, version control, and meticulous documentation become even more crucial.
* **Not always necessary:** DI shines in complex applications where components must be loosely coupled and tested in isolation and where there's a need for better modularity. However, for a simple script or a small application with minimal components, introducing DI might be overkill. It could lead to more complexity without tangible benefits. As with any design pattern or architectural choice, it's essential to evaluate if it's appropriate for the task at hand.


Dependency injection in popular Python frameworks
-------------------------------------------------


In this section, you'll explore how to set up dependency injection using three popular Python frameworks: [Flask](https://flask.palletsprojects.com/en/2.3.x/), [Django](https://www.djangoproject.com/), and [FastAPI](https://fastapi.tiangolo.com/). While each framework has its distinct approach, they all share a foundational principle — the decoupling of dependencies to build applications that are more maintainable, modular, and easily testable.


Before diving into the frameworks, it's important to ensure you have Python installed. If it's not already installed, you can download and install it from [Python's official website](https://www.python.org/downloads/).


Now that you have Python on your machine explore dependency injection in these different frameworks.


### Dependency injection in Flask


Flask is a lightweight web framework. While it doesn't offer built-in DI support, you can integrate extensions like [Flask-Injector](https://pypi.org/project/Flask-Injector/) to achieve this.


To install Flask and [Flask-Injector](https://github.com/python-injector/flask_injector), use the following command:



```
pip3 install Flask Flask-Injector
```

Flask-Injector seamlessly integrates the Injector library for controlled dependency injection in Flask apps.


#### Create a Flask application


To create a simple flask application, create a folder named `flask_di_project`. Then, under this folder, create a new file named `app.py` and add the following code:



```
from flask import Flask, jsonify
from flask_injector import FlaskInjector, inject, singleton

app = Flask(__name__)

class Database:
    def __init__(self):
        self.data = {"message": "Data from the Database!"}

class Logger:
    def log(self, message):
        print("Logging:", message)

class DataService:
    def __init__(self, database: Database, logger: Logger):
        self.database = database
        self.logger = logger

    def fetch_data(self):
        self.logger.log("Fetching data...")
        return self.database.data

@app.route('/')
@inject
def index(data_service: DataService):
    return jsonify(data_service.fetch_data())

# Dependency configurations
def configure(binder):
    binder.bind(Database, to=Database(), scope=singleton)
    binder.bind(Logger, to=Logger(), scope=singleton)
    binder.bind(DataService, to=DataService(Database(), Logger()), scope=singleton)

if __name__ == '__main__':
    FlaskInjector(app=app, modules=[configure])
    app.run(debug=True)
```

In this code, you're building a Flask web application that utilizes dependency injection to manage its components. The application consists of three classes: `Database`, `Logger`, and `DataService`. You define the dependencies of the `DataService` class using constructor injection, allowing you to inject instances of `Database` and `Logger` when creating a `DataService` instance. With the `@inject` decorator on the index route function, you're using Flask-Injector to automatically inject a `DataService` instance into the function. Furthermore, a `configure` function defines the binding of these dependencies, ensuring that whenever an instance is required, Flask-Injector knows how to provide it.


#### Run and test the application


In your terminal or shell, navigate to the directory containing `app.py` and run the following:



```
python3 app.py
```

Open a browser and go to <http://127.0.0.1:5000/>. You should see the message `{"message": "Data from the Database!"}`:


![](https://res.cloudinary.com/snyk/image/upload/v1698786242/blog-di-python-data-database.jpg)
### Dependency injection in Django


Django, a high-level web framework, provides avenues for DI through external libraries. For this instance, you utilize the [Django Injector](https://pypi.org/project/django-injector/) library to introduce DI into your Django project.


Use the following command to install Django and Django Injector:



```
pip3 install Django django-injector
```

#### Create a new Django project and app


To create a new Django project and application, use the following commands:



```
django-admin startproject django_di_project
cd django_di_project
python3 manage.py startapp myapp
```

Once you have the `django-injector` installed, you need to add it to your project. Go to the `settings.py` file located under the `django_di_project` folder and add `django_injector` to the `INSTALLED_APPS` array:



```
INSTALLED_APPS = [
    … code omitted …
    'django_injector',
]
```

Then, in `myapp/views.py`, use `django-injector` to achieve DI:



```
from django.http import JsonResponse
from injector import inject
from django.views import View
from myapp.services import DataService  # Import your DataService class

class MyView(View):
    @inject
    def __init__(self, data_service: DataService):
        self.data_service = data_service
        super().__init__()

    def get(self, request):
        data = self.data_service.fetch_data()
        return JsonResponse(data)
```

Here, you've defined a Django view, `MyView`, that, when accessed via a GET request, fetches data using dependency-injected `DataService` and returns it as a JSON response.


#### Update the URLs


Update `django_di_project/urls.py` to route the root URL to this view:



```
from django.urls import path
from myapp.views import MyView

urlpatterns = [
    path('', MyView.as_view(), name='index'),
]
```

Then create a `services.py` file in your `myapp` directory and define the `DataService` class there:



```
from injector import inject

class DataService:
    @inject
    def __init__(self):
        self.message = "Hello from Dynamic DataService in Django!"

    def fetch_data(self):
        return {"message": self.message}
```

By incorporating `django-injector`, you've seamlessly integrated DI into your Django application. The `@inject` decorator efficiently injects the `DataService` instance into the constructor of the `MyView` class, promoting modularity and improved manageability within your Django application.


#### Run and test the application


In your terminal or shell, within the `django_di_project` directory, run the following:



```
python3 manage.py runserver
```

Open your browser and go to <http://127.0.0.1:8000/>. You should see the message `{"message": "Hello from Dynamic DataService in Django!"}`:


![](https://res.cloudinary.com/snyk/image/upload/v1698786242/blog-di-python-django.jpg)
### Dependency injection in FastAPI


FastAPI represents a modern web framework that comes with native DI support. By using FastAPI, you embrace a framework that inherently integrates DI, allowing you to seamlessly build modular and testable applications without relying on external libraries.


Use the following code to install FastAPI and [Uvicorn](https://www.uvicorn.org/) (an ASGI server for running FastAPI):



```
pip3 install fastapi uvicorn
```

#### Create a simple FastAPI application


To create a simple FastAPI application, create a new folder named `fast_di_project` in your root directory. Inside this folder, create a file named `main.py` and add the following code:



```
from fastapi import FastAPI, Depends

app = FastAPI()

class DataService:
    def fetch_data(self):
        return {"message": "Greetings from the Dynamic DataService in the World of FastAPI!"}

def get_data_service():
    return DataService()

@app.get('/')
def index(data_service: DataService = Depends(get_data_service)):
    data = data_service.fetch_data()
    return {"result": data, "info": "Fetched from the Dynamic DataService in FastAPI!"}
```

Here, you start by creating an instance of the `FastAPI` class. Then, you define a `DataService` class that encapsulates a method for fetching data. When you access the root URL of your application, FastAPI's built-in dependency management comes into play. You've created a function `get_data_service()` to provide an instance of the `DataService` class. FastAPI's `Depends` mechanism allows you to inject this instance into the `index` route function. When you visit the root URL in your browser, you'll receive a response containing the fetched data along with a personalized message from the dynamic `DataService` in the realm of FastAPI.


#### Run and test the application


In your terminal or shell, navigate to the directory containing `main.py` and run the following:



```
uvicorn main:app --reload
```

Open your browser and go to <http://127.0.0.1:8000/>. You should see the message `{"result":{"message":"Greetings from the Dynamic DataService in the World of FastAPI!"},"info":"Fetched from the Dynamic DataService in FastAPI!"}`:


![](https://res.cloudinary.com/snyk/image/upload/v1698786242/blog-di-python-fastapi.jpg)
All the code used in this tutorial is available in this [GitHub repository](https://github.com/See4Devs/dependency-injection-python).


Python dependency injection frameworks
--------------------------------------


When deciding which DI framework to use, it's important to evaluate the specific requirements of your project, the level of modularity and testability you desire, and the framework you're working with. Each option offers different capabilities, and your choice should align with your project's complexity and design goals. Take a look at a few of the different options:


### Flask-Injector


[Flask-Injector](https://pypi.org/project/Flask-Injector/) is an excellent choice when you're building Flask applications. It's particularly valuable for lightweight projects that are based on the Flask framework.


Flask-Injector integrates seamlessly into the Flask ecosystem, making it easy to manage dependencies and achieve modularity within your Flask app. However, for larger and more complex applications that might require more advanced dependency management features, you might consider exploring other DI frameworks that offer additional capabilities tailored to those specific needs.


### Django Injector


If you're developing with Django, the [Django Injector](https://pypi.org/project/django-injector/) library can be a valuable asset. It simplifies DI within Django projects, making it an excellent choice when you want to achieve modularity and testability.


Consider using Django Injector when building Django applications that require seamless integration of DI, especially for class-based views, middleware, and management commands.


### Depends


The [Depends](https://fastapi.tiangolo.com/tutorial/dependencies/) function in FastAPI is designed to work with Python's `asyncio` framework and offers DI features for asynchronous code. If you're building asynchronous applications using `FastAPI`, `Depends` can assist in managing and injecting dependencies into your asynchronous functions and coroutines. This feature is especially valuable when working with async-based projects in `FastAPI`, aiming to maintain code quality and modular design.


### Dependency Injector


The [Dependency Injector](https://pypi.org/project/dependency-injector/) library is a comprehensive DI framework suitable for various Python applications. It provides advanced features, such as container management, scoping, and lifecycle control.


You should use the Dependency Injector when you're working on larger projects that demand robust dependency management, inversion of control, and complex scenarios where you need more control over how dependencies are injected and managed.


### Injector


The [Injector](https://pypi.org/project/injector/) library is a general-purpose DI framework that can be integrated into different Python projects, regardless of the framework. It's particularly suitable for projects where you want to manually configure and manage dependency injection without framework-specific integrations.


You should use Injector when you need a flexible and versatile DI solution for applications that span across multiple frameworks or even stand-alone scripts.


Keeping your project dependencies secure with Snyk
--------------------------------------------------


When you focus on functionality, you can't afford to push security to the side. This is where [Snyk](https://snyk.io/) can help. With the [Snyk toolkit](https://docs.snyk.io/snyk-api/other-tools), you have the ability to do the following:


* Scan Python dependencies, pinpointing vulnerabilities and getting suggestions for fixes.
* Receive real-time feedback on security concerns as you code.
* Benefit from automated solutions for any vulnerabilities detected.
* Seamlessly integrate with popular continuous integration continuous delivery (CI/CD) pipelines, ensuring consistent security checks.


By incorporating the [Snyk IDE extensions](https://snyk.io/platform/ide-plugins/) into your workflow, you're proactively adopting secure coding practices right from the start, simplifying your dependency management process. For more information related to Snyk, you can check the [Snyk official documentation](https://docs.snyk.io/).


Conclusion
----------


In this article, you learned all about why you need dependency injection in Python. In doing so, you learned about some of its benefits, like improved code maintainability and modularity. Additionally, you learned about some of the obstacles it presents, including the possibility of heightened complexity and the potential for runtime errors. Moreover, you learned about integrating dependency injection within widely recognized Python frameworks, such as Flask, FastAPI, and Django.


While DI can present certain challenges, mastering its nuances can elevate the quality of Python applications. As you navigate the world of dependency management, leveraging tools like [Snyk](https://snyk.io/) is crucial to keep security at the forefront of your development endeavors. For further insights into Python dependency management and best practices, it's worth exploring the [Python Poetry package manager](https://snyk.io/blog/python-poetry-package-manager/) on the Snyk blog. This resource offers a comprehensive overview of tools that can assist you in managing your Python projects more efficiently.