Dependency Injector is a dependency injection framework for Python.

Overview

Latest Version License Supported Python versions Supported Python implementations Downloads Downloads Downloads Wheel Build Status Coverage Status

What is Dependency Injector?

Dependency Injector is a dependency injection framework for Python.

It helps implementing the dependency injection principle.

Key features of the Dependency Injector:

  • Providers. Provides Factory, Singleton, Callable, Coroutine, Object, List, Dict, Configuration, Resource, Dependency and Selector providers that help assembling your objects. See Providers.
  • Overriding. Can override any provider by another provider on the fly. This helps in testing and configuring dev / stage environment to replace API clients with stubs etc. See Provider overriding.
  • Configuration. Reads configuration from yaml & ini files, pydantic settings, environment variables, and dictionaries. See Configuration provider.
  • Containers. Provides declarative and dynamic containers. See Containers.
  • Resources. Helps with initialization and configuring of logging, event loop, thread or process pool, etc. Can be used for per-function execution scope in tandem with wiring. See Resource provider.
  • Wiring. Injects dependencies into functions and methods. Helps integrating with other frameworks: Django, Flask, Aiohttp, Sanic, FastAPI, etc. See Wiring.
  • Asynchronous. Supports asynchronous injections. See Asynchronous injections.
  • Typing. Provides typing stubs, mypy-friendly. See Typing and mypy.
  • Performance. Fast. Written in Cython.
  • Maturity. Mature and production-ready. Well-tested, documented and supported.
from dependency_injector import containers, providers
from dependency_injector.wiring import inject, Provide


class Container(containers.DeclarativeContainer):

    config = providers.Configuration()

    api_client = providers.Singleton(
        ApiClient,
        api_key=config.api_key,
        timeout=config.timeout.as_int(),
    )

    service = providers.Factory(
        Service,
        api_client=api_client,
    )


@inject
def main(service: Service = Provide[Container.service]):
    ...


if __name__ == '__main__':
    container = Container()
    container.config.api_key.from_env('API_KEY')
    container.config.timeout.from_env('TIMEOUT')
    container.wire(modules=[sys.modules[__name__]])

    main()  # <-- dependency is injected automatically

    with container.api_client.override(mock.Mock()):
        main()  # <-- overridden dependency is injected automatically

When you call main() function the Service dependency is assembled and injected automatically.

When doing a testing you call the container.api_client.override() to replace the real API client with a mock. When you call main() the mock is injected.

You can override any provider with another provider.

It also helps you in configuring project for the different environments: replace an API client with a stub on the dev or stage.

With the Dependency Injector objects assembling is consolidated in the container. Dependency injections are defined explicitly. This makes easier to understand and change how application works.

Visit the docs to know more about the Dependency injection and inversion of control in Python.

Installation

The package is available on the PyPi:

pip install dependency-injector

Documentation

The documentation is available here.

Examples

Choose one of the following:

Tutorials

Choose one of the following:

Concept

The framework stands on the PEP20 (The Zen of Python) principle:

Explicit is better than implicit

You need to specify how to assemble and where to inject the dependencies explicitly.

The power of the framework is in a simplicity. Dependency Injector is a simple tool for the powerful concept.

Frequently asked questions

What is the dependency injection?
  • dependency injection is a principle that decreases coupling and increases cohesion
Why should I do the dependency injection?
  • your code becomes more flexible, testable and clear 😎
How do I start doing the dependency injection?
  • you start writing the code following the dependency injection principle
  • you register all of your application components and their dependencies in the container
  • when you need a component, you specify where to inject it or get it from the container
What price do I pay and what do I get?
  • you need to explicitly specify the dependencies
  • it will be extra work in the beginning
  • it will payoff as the project grows
Have a question?
Found a bug?
Want to help?
  • ⭐️ Star the Dependency Injector on the Github
  • 🆕 Start a new project with the Dependency Injector
  • 💬 Tell your friend about the Dependency Injector
Want to contribute?
  • 🔀 Fork the project
  • ⬅️ Open a pull request to the develop branch
Owner
ETS Labs
Expert Technical Solutions Labs
ETS Labs
Allows you to canibalize methods from classes effectively implementing trait-oriented programming

About This package enables code reuse in non-inheritance way from existing classes, effectively implementing traits-oriented programming pattern. Stor

1 Dec 13, 2021
Extract the download URL from OneDrive or SharePoint share link and push it to aria2

OneDriveShareLinkPushAria2 Extract the download URL from OneDrive or SharePoint share link and push it to aria2 从OneDrive或SharePoint共享链接提取下载URL并将其推送到a

高玩梁 262 Jan 08, 2023
A repo for working with and building daos

DAO Mix DAO Mix About How to DAO No Code Tools Getting Started Prerequisites Installation Usage On-Chain Governance Example Off-Chain governance Examp

Brownie Mixes 86 Dec 19, 2022
Similar looking domain detection using python fuzzywuzzy

Major cause of phishing and BEC incident is similar looking domain, if you detect it early, you can prevent incidents early, python fuzzywuzzy module let you do that

2 Nov 07, 2021
Let's renew the puzzle collection. We'll produce a collection of new puzzles out of the lichess game database.

Let's renew the puzzle collection. We'll produce a collection of new puzzles out of the lichess game database.

Thibault Duplessis 96 Jan 03, 2023
Manage your exceptions in Python like a PRO

A linter to manage all your python exceptions and try/except blocks (limited only for those who like dinosaurs).

Guilherme Latrova 353 Dec 31, 2022
Aggregating gridded data (xarray) to polygons

A package to aggregate gridded data in xarray to polygons in geopandas using area-weighting from the relative area overlaps between pixels and polygons.

Kevin Schwarzwald 42 Nov 09, 2022
Patch the pclntable from Go binaries

Pretrain and Fine-tune a T5 model with Flax on GCP This tutorial details how pretrain and fine-tune a FlaxT5 model from HuggingFace using a TPU VM ava

6 Oct 05, 2022
Finger is a function symbol recognition engine for binary programs

Finger is a function symbol recognition engine for binary programs

332 Jan 01, 2023
A simple Python app that generates semi-random chord progressions.

chords-generator A simple Python app that generates semi-random chord progressions.

53 Sep 07, 2022
A Python package implementing various colour checker detection algorithms and related utilities.

A Python package implementing various colour checker detection algorithms and related utilities.

colour-science 147 Dec 29, 2022
A python tool give n number of inputs and parallelly you will get a output by separetely

http-status-finder Hello Everyone!! This is kavisurya, In this tool you can give n number of inputs and parallelly you will get a output by separetely

KAVISURYA V 3 Dec 05, 2021
Grank is a feature-rich script that automatically grinds Dank Memer for you

Grank Inspired by this repository. This is a WIP and there will be more functions added in the future. What is Grank? Grank is a feature-rich script t

42 Jul 20, 2022
Extract XML from the OS X dictionaries.

Extract XML from the OS X dictionaries.

Joshua Olson 13 Dec 11, 2022
ULID implementation for Python

What is this? This is a port of the original JavaScript ULID implementation to Python. A ULID is a universally unique lexicographically sortable ident

Martin Domke 158 Jan 04, 2023
Create C bindings for python automatically with the help of libclang

Python C Import Dynamic library + header + ctypes = Module like object! Create C bindings for python automatically with the help of libclang. Examples

1 Jul 25, 2022
An OData v4 query parser and transpiler for Python

odata-query is a library that parses OData v4 filter strings, and can convert them to other forms such as Django Queries, SQLAlchemy Queries, or just plain SQL.

Gorilla 39 Jan 05, 2023
A simple tool to move and rename Nvidia Share recordings to a more sensible format.

A simple tool to move and rename Nvidia Share recordings to a more sensible format.

Jasper Rebane 8 Dec 23, 2022
extract gene TSS/TES site form gencode/ensembl/gencode database GTF file and export bed format file.

GetTsite python Package extract gene TSS/TES site form gencode/ensembl/gencode database GTF file and export bed format file. Install $ pip install Get

laojunjun 7 Nov 21, 2022
Create password - Generate Random Password with Passphrase

Generate Random Password with Passphrase This is a python code to generate stron

1 Jan 18, 2022