Antidotes is a dependency injection micro-framework for Python 3.7+. It is built on the idea of ensuring best maintainability of your code while being as easy to use as possible. It also provides the fastest injection with @inject allowing you to use it virtually anywhere and fast full isolation of your tests.

Antidote provides the following features:

  • Ease of use
    • Injection anywhere you need through a decorator @inject

    • No **kwargs arguments hiding actual arguments and fully mypy typed, helping you and your IDE.

    • Documented, everything has tested examples.

    • No need for any custom setup, just use your injected function as usual. You just don’t have to specify injected arguments anymore. Allowing you to gradually migrate an existing project.

  • Flexibility
    • Most common dependencies out of the box: services, configuration, factories, interface/implementation.

    • All of those are implemented on top of the core implementation. If Antidote doesn’t provide what you need, there’s a good chance you can implement it yourself.

    • Scope support

    • Async injection

  • Maintainability
    • All dependencies can be tracked back to their declaration/implementation easily.

    • Mypy compatibility and usage of type hints as much as possible.

    • Overriding dependencies will raise an error outside of tests.

    • Dependencies can be frozen, which blocks any new declarations.

    • No double injection.

    • Everything is as explicit as possible, @inject does not inject anything implicitly.

    • Type checks when a type is explicitly defined with world.get and constants.

    • Thread-safe, cycle detection.

    • Immutable whenever possible.

  • Testability
    • @inject lets you override any injections by passing explicitly the arguments.

    • Fully isolate each test with world.test.clone. They will work on separate objects.

    • Override globally any dependency locally in a test.

    • When encountering issues you can retrieve the full dependency tree, nicely formatted, with world.debug.

  • Performance*
    • Fastest @inject with heavily tuned Cython.

    • As much as possible is done at import time.

    • Testing utilities are tuned to ensure that even with full isolation it stays fast.

    • Benchmarks: comparison, injection, test utilities

*with the compiled version, in Cython. Pre-built wheels for Linux. See further down for more details.

Comparison benchmark image


To install Antidote, simply run this command:

pip install antidote


Beginner friendly tutorial, recipes, the reference and a FAQ can be found in the documentation.

Here are some links:

Issues / Questions#

Feel free to open an issue on Github for questions or issues !

Hands-on quick start#

Showcase of the most important features of Antidote with short and concise examples. Checkout the Getting started for a full beginner friendly tutorial.


from antidote import inject, injectable

class Database:

def f(db: Database =
    return db

assert isinstance(f(), Database)  # works !

Simple, right ? And you can still use it like a normal function, typically when testing it:


@inject here used the marker with the help of the type hint to determine the dependency. But it also supports the following ways to express the dependency wiring:

  • annotated type hints:
    from antidote import Inject
    def f(db: Inject[Database]):
  • list (matching argument position):
    def f(db):
  • mapping:
    @inject({'db': Database})
    def f(db):
  • optional dependencies:
    from typing import Optional
    class Dummy:
    # When the type_hint is optional and a marker like `` is used, None will be
    # provided if the dependency does not exists.
    def f(dummy: Optional[Dummy] =
        return dummy
    assert f() is None

You can also retrieve the dependency by hand with world.get:

from antidote import world

# Retrieve dependencies by hand, in tests typically
world.get[Database](Database)  # with type hint, enforced when possible


Any class marked as @injectable can be provided by Antidote. It can be a singleton or not. Scopes and a factory method are also supported. Every method is injected by default, relying on annotated type hints and markers such as

from antidote import injectable, inject

class QueryBuilder:
    # methods are also injected by default
    def __init__(self, db: Database =
        self._db = db

def load_data(builder: QueryBuilder =

load_data()  # yeah !


Constants can be provided lazily by Antidote:

from antidote import inject, const

class Config:
    DB_HOST = const('localhost')
    DB_PORT = const(5432)

def ping_db(db_host: str = Config.DB_HOST):

ping_db()  # nice !

Constants really shines when they aren’t hard-coded:

from typing import Optional

class Config:
    # Retrieve constant from environment variables
    DB_HOST = const.env()  # using the constant name
    # or with an explicit name, default value, and forced conversion to int
    # (and other selected types)
    DB_PORT = const.env[int]("DATABASE_PORT", default=5432)

import os
os.environ['DB_HOST'] = 'localhost'
os.environ['DATABASE_PORT'] = '5432'

def check_connection(db_host: str = Config.DB_HOST,
                     db_port: int = Config.DB_PORT):

check_connection()  # perfect !

Note that on the injection site, nothing changed! And obviously you can create your own logic:

from antidote import const

def static(name: str, arg: Optional[str]) -> str:
    return arg

class Config:
    DB_HOST = static.const('localhost')

Stateful configuration is also possible:

from antidote import injectable, const

class Config:
    def __init__(self): = {'host': 'localhost'}

    def get(self, name: str, arg: Optional[str]) -> str:

    DB_HOST = get.const('host')


Lazy functions can be used in multiple cases:

  • to load external classes:

from antidote import lazy, inject

class Redis:

@lazy  # singleton by default
def load_redis() -> Redis:
    return Redis()

def task(redis = load_redis()):
  • as a factory:

from antidote import lazy, inject

class User:

def current_user(db: Database = -> User:
    return User()

def is_admin(user: User = current_user()):
  • or even to parameterize dependencies:

from dataclasses import dataclass
from antidote import lazy, inject

class Template:
    path: str

def load_template(path: str) -> Template:
    return Template(path=path)

def registration(template: Template = load_template('registration.html')):


Antidote also works with interfaces which can have one or multiple implementations which can be overridden:

from antidote import implements, inject, interface, world

class Task:

class Default(Task):

class Custom(Task):


def f(task: Task = -> Task:
    return task

Implementations support qualifiers out of the box:

import enum

class Hook(enum.Enum):
    START =
    STOP =

class Task:

class StartX(Task):

class StopX(Task):

assert world.get[Task].single(qualified_by=Hook.START) == world.get(StartX)
assert world.get[Task].all(qualified_by=Hook.START) == [world.get(StartX)]

def get_single_task(task: Task = -> Task:
    return task

def get_all_task(tasks: list[Task] = -> list[Task]:
    return tasks

Testing and Debugging#

inject always allows you to pass your own argument to override the injection:

from antidote import injectable, inject

class Database:

def f(db: Database =

f(Database())  # test with specific arguments in unit tests

You can also fully isolate your tests from each other and override any dependency within that context:

from antidote import world

# Clone current world to isolate it from the rest
with world.test.clone():
    x = object()
    # Override the Database
    world.test.override.singleton(Database, x)
    f()  # will have `x` injected for the Database

    def override_database():
        class DatabaseMock:

        return DatabaseMock()

    f()  # will have `DatabaseMock()` injected for the Database

If you ever need to debug your dependency injections, Antidote also provides a tool to have a quick summary of what is actually going on:

def function_with_complex_dependencies():

# would output something like this:
└──<∅> IMDBMovieDB
    └── ImdbAPI
        └── load_imdb
            ├── Config.IMDB_API_KEY
            ├── Config.IMDB_PORT
            └── Config.IMDB_HOST

Singletons have no scope markers.
<∅> = no scope (new instance each time)
<name> = custom scope

Hooked ? Check out the documentation ! There are still features not presented here !


The compiled implementation is roughly 10x faster than the Python one and strictly follows the same API than the pure Python implementation. Pre-compiled wheels are available only for Linux currently. You can check whether you’re using the compiled version or not with:

from antidote import is_compiled

f"Is Antidote compiled ? {is_compiled()}"

You can force the compilation of antidote yourself when installing:

ANTIDOTE_COMPILED=true pip install antidote

On the contrary, you can force the pure Python version with:

pip install --no-binary antidote


The compiled version is not tested against PyPy. The compiled version relies currently on Cython, but it is not part of the public API. Relying on it in your own Cython code is at your risk.

How to Contribute#

  1. Check for open issues or open a fresh issue to start a discussion around a feature or a bug.

  2. Fork the repo on GitHub. Run the tests to confirm they all pass on your machine. If you cannot find why it fails, open an issue.

  3. Start making your changes to the master branch.

  4. Writes tests which shows that your code is working as intended. (This also means 100% coverage.)

  5. Send a pull request.

Be sure to merge the latest from “upstream” before making a pull request!

If you have any issue during development or just want some feedback, don’t hesitate to open a pull request and ask for help !

Pull requests will not be accepted if:

  • public classes/functions have not docstrings documenting their behavior with examples.

  • tests do not cover all of code changes (100% coverage) in the pure python.

If you face issues with the Cython part of Antidote, I may implement it myself.