🌐
Ets-labs
python-dependency-injector.ets-labs.org
Dependency Injector — Dependency injection framework for Python — Dependency Injector 4.49.1 documentation
from dependency_injector import containers, providers from dependency_injector.wiring import Provide, inject class Container(containers.DeclarativeContainer): config = providers.Configuration() api_client = providers.Singleton( ApiClient, api_key=config.api_key, timeout=config.timeout, ) service ...
🌐
PyPI
pypi.org › project › dependency-injector
dependency-injector · PyPI
With the Dependency Injector, object assembling is consolidated in a container. Dependency injections are defined explicitly. This makes it easier to understand and change how an application works. Visit the docs to know more about the Dependency injection and inversion of control in Python.
      » pip install dependency-injector
    
Published   Jun 18, 2026
Version   4.49.1
Discussions

python - What is a Pythonic way for Dependency Injection? - Stack Overflow
Some time ago I wrote dependency injection microframework with a ambition to make it Pythonic - Dependency Injector. That's how your code can look like in case of its usage: Copy"""Example of dependency injection in Python.""" import logging import sqlite3 import boto.s3.connection import ... More on stackoverflow.com
🌐 stackoverflow.com
どのDIライブラリを選ぶ? Injector vs Dependency ...
🌐 r/learnpython
Lagom - dependency injector
Automated dependency injectors are not very pythonic - I've not seen a great argument for using them in python that doesn't shoot down monkey patching for nonexistent reasons. 230 stars is quite a lot for a module that does something the language simply doesn't need. More on reddit.com
🌐 r/Python
16
17
February 9, 2024
Dependency Injection in Python?
I am using dependency injection every single day at work with python. Automation stuff, a bit of API work as well. Over 40 classes written, all using dependency injection. Why? It makes things easier to refactor if it is so required(and the project I am working on was started from scratch, so in the beginning a lot of refactoring was required). At first we were not using it, instantiating class fields directly inside the __init__ block. It is safe to say that it was hell to keep track of what class is using what class after a while. Extracted all initialization outside of classes, injected instances into constructors. Easier to read the code now and if I ever need some special kind of treatment for a task, I can write another class with same methods, different implementations and inject it wherever I need. More on reddit.com
🌐 r/Python
32
8
November 24, 2022
🌐
Ets-labs
python-dependency-injector.ets-labs.org › introduction › di_in_python.html
Dependency injection and inversion of control in Python — Dependency Injector 4.49.1 documentation
It contains Python examples that show how to implement dependency injection. It demonstrates a usage of the dependency injection framework Dependency Injector, its container, Factory, Singleton and Configuration providers. The example show how to use Dependency Injector providers overriding ...
🌐
GitHub
github.com › ets-labs › python-dependency-injector
GitHub - ets-labs/python-dependency-injector: Dependency injection framework for Python · GitHub
When you call the main() function the Service dependency is assembled and injected automatically.
Author   ets-labs
🌐
Medium
medium.com › @spraneeth4 › python-dependency-injector-simplifying-dependency-injection-in-your-projects-14385af0bf78
Python Dependency Injector: Simplifying Dependency Injection in Your Projects | by praneeth_vvs | Medium
September 27, 2024 - To effectively integrate dependency injection using the Dependency Injector framework in a FastAPI application, two critical steps need to be implemented: container.wire(modules=[…]) — It Registers Modules: You’re telling the DI container which Python modules (or files) contain components that should have dependencies injected into them.
🌐
DataCamp
datacamp.com › tutorial › python-dependency-injection
Python Dependency Injection: A Guide for Cleaner Code Design | DataCamp
May 7, 2026 - The Provide class tells the dependency-injector which dependency to inject. This approach eliminates the need for manual wiring dependencies from the container. It’s helpful in larger applications where services may depend on multiple components (hence this need to initialize them automatically). Most modern Python frameworks make it easy to work with dependency injection, allowing you to write cleaner and more testable code.
🌐
Medium
medium.com › @rmogylatov › dependency-injector-python-dependency-injection-framework-eeb9f5c6db8b
Dependency Injector — Python dependency injection framework | by Roman Mogylatov | Medium
September 10, 2020 - That’s how the previous example will look like with a multiple containers approach: import logging.config import sqlite3 import boto3 from dependency_injector import containers, providers from .
Find elsewhere
🌐
Better Stack
betterstack.com › community › guides › scaling-python › python-dependency-injection
Dependency Injection in Python | Better Stack Community
April 29, 2025 - In this code, you use the dependency-injector library to manage your dependencies automatically. The Container class defines how objects are created and connected.
🌐
GitHub
github.com › python-injector › injector
GitHub - python-injector/injector: Python dependency injection framework, inspired by Guice · GitHub
For example the Injector.get method is typed such that injector.get(SomeType) is statically declared to return an instance of SomeType, therefore making it possible for tools such as mypy to type-check correctly the code using it. The client code only knows about dependency injection to the extent it needs – inject, Inject and NoInject are simple markers that don't really do anything on their own and your code can run just fine without Injector orchestrating things.
Starred by 1.5K users
Forked by 95 users
Languages   Python
🌐
Snyk
snyk.io › blog › dependency-injection-python
Dependency injection in Python | Snyk
October 31, 2023 - Consider using Django Injector when building Django applications that require seamless integration of DI, especially for class-based views, middleware, and management commands. The Depends function in FastAPI is designed to work with Python's asyncio framework and offers DI features for asynchronous code.
🌐
Ets-labs
python-dependency-injector.ets-labs.org › providers › index.html
Providers — Dependency Injector 4.49.0 documentation
See the example at Provider overriding. If you need to inject not the whole object but the parts see Injecting provided object attributes, items, or call its methods. To create a new provider see Creating a custom provider. Providers module API docs - dependency_injector.providers
🌐
OneUptime
oneuptime.com › home › blog › how to implement dependency injection in python
How to Implement Dependency Injection in Python
February 3, 2026 - # container_config.py # Environment-specific container configuration from dependency_injector import containers, providers import os class Container(containers.DeclarativeContainer): """Container with environment-aware configuration""" # Configuration loaded from environment config = providers.Configuration() # Environment detection environment = providers.Object(os.getenv("ENVIRONMENT", "development")) # Database - different implementations per environment database = providers.Selector( environment, development=providers.Singleton( SqliteDatabase, path="./dev.db" ), testing=providers.Singleto
Top answer
1 of 11
90

See Raymond Hettinger - Super considered super! - PyCon 2015 for an argument about how to use super and multiple inheritance instead of DI. If you don't have time to watch the whole video, jump to minute 15 (but I'd recommend watching all of it).

Here is an example of how to apply what's described in this video to your example:

Framework Code:

class TokenInterface():
    def getUserFromToken(self, token):
        raise NotImplementedError

class FrameworkClass(TokenInterface):
    def do_the_job(self, ...):
        # some stuff
        self.user = super().getUserFromToken(...)

Client Code:

class SQLUserFromToken(TokenInterface):
    def getUserFromToken(self, token):      
        # load the user from the database
        return user

class ClientFrameworkClass(FrameworkClass, SQLUserFromToken):
    pass

framework_instance = ClientFrameworkClass()
framework_instance.do_the_job(...)

This will work because the Python MRO will guarantee that the getUserFromToken client method is called (if super() is used). The code will have to change if you're on Python 2.x.

One added benefit here is that this will raise an exception if the client does not provide a implementation.

Of course, this is not really dependency injection, it's multiple inheritance and mixins, but it is a Pythonic way to solve your problem.

2 of 11
25

The way we do dependency injection in our project is by using the inject lib. Check out the documentation. I highly recommend using it for DI. It kinda makes no sense with just one function but starts making lots of sense when you have to manage multiple data sources etc, etc.

Following your example it could be something similar to:

# framework.py
class FrameworkClass():
    def __init__(self, func):
        self.func = func

    def do_the_job(self):
        # some stuff
        self.func()

Your custom function:

# my_stuff.py
def my_func():
    print('aww yiss')

Somewhere in the application you want to create a bootstrap file that keeps track of all the defined dependencies:

# bootstrap.py
import inject
from .my_stuff import my_func

def configure_injection(binder):
    binder.bind(FrameworkClass, FrameworkClass(my_func))

inject.configure(configure_injection)

And then you could consume the code this way:

# some_module.py (has to be loaded with bootstrap.py already loaded somewhere in your app)
import inject
from .framework import FrameworkClass

framework_instance = inject.instance(FrameworkClass)
framework_instance.do_the_job()

I'm afraid this is as pythonic as it can get (the module has some python sweetness like decorators to inject by parameter etc - check the docs), as python does not have fancy stuff like interfaces or type hinting.

So to answer your question directly would be very hard. I think the true question is: does python have some native support for DI? And the answer is, sadly: no.

🌐
Readthedocs
injector.readthedocs.io
Injector 0.24.0 documentation
You need to be explicit and use Injector.get, Injector.create_object or inject MyClass into the place that needs it. Cooperation with static type checking infrastructure – the API provides as much static type safety as possible and only breaks it where there’s no other option. For example the Injector.get method is typed such that injector.get(SomeType) is statically declared to return an instance of SomeType, therefore making it possible for tools such as mypy to type-check correctly the code using it.
🌐
Medium
medium.com › @pavlomorozov78 › dependency-injection-in-python-with-injector-7ce7cab9d7f4
Dependency Injection in Python with Injector | by Pavlo Morozov | Medium
November 21, 2023 - In our example it is one of two: ... Now when the run method execution will start we will get the fundamentals data from the service we got injected. The DeveloperNote attribute in response JSON is actually not available in HTTP API and it was added to development JSON file only, to indicate which profile service implementation returned the data. Here running application output in case of default profile: $ python3 injector_example_main.py --Profile default Fundamentals data DeveloperNote: None
🌐
DEV Community
dev.to › sxddhxrthx › introduction-to-dependency-injection-in-python-35c
Introduction to Dependency Injection in Python - DEV Community
March 20, 2021 - import sys from dependency_injector import containers, providers from dependency_injector.wiring import inject, Provide class School: def __init__(self, name: str, city: str, board: str): self.schoolname = name self.city = city self.board = board def get_schoolname(self): print(f"school name is {self.schoolname}") class Student(): def __init__(self, name: str, age: int, grade: int, school: School): self.name = name self.age = age self.grade = grade self.school = school #super().__init__(school, city, board) def get_students(self): student_detail = f""" Student Name: {self.name} Student Age: {s
🌐
PyPI
pypi.org › project › injector
injector · PyPI
For example the Injector.get method is typed such that injector.get(SomeType) is statically declared to return an instance of SomeType, therefore making it possible for tools such as mypy to type-check correctly the code using it. The client code only knows about dependency injection to the extent it needs – inject, Inject and NoInject are simple markers that don't really do anything on their own and your code can run just fine without Injector orchestrating things.
      » pip install injector
    
Published   Jan 09, 2026
Version   0.24.0
🌐
Medium
medium.easyread.co › cleaner-more-maintainable-python-code-with-dependency-injector-fc290b52de10
Cleaner, More Maintainable Python Code with Dependency-Injector | by Ferdina Kusumah | Easyread
July 16, 2024 - After we refactoring the code, we can see that each class is independent now, no class build own object. It passed from dependency injector.
🌐
GitHub
github.com › sfermigier › awesome-dependency-injection-in-python
GitHub - sfermigier/awesome-dependency-injection-in-python: A curated list of awesome things related to dependency inversion / dependency injection in Python. (Contributions welcomed). · GitHub
Pythonic Dependency Injection: A Practical Guide (Sune Andreas Dybro Debel, 2018) Elegant Flask API Development Part 1 (mostly covers Flask-Injector). "(pytest) Fixtures: a prime example of dependency injection"
Author   sfermigier