Inject

5.3.0 · active · verified Sat Apr 11

Inject is a lightweight, fast, and thread-safe Python dependency injection framework. It facilitates the creation and management of object dependencies, promoting modular and testable code. The library supports features like automatic parameter injection using type annotations and context managers. It maintains an active development status, with the current version being 5.3.0, and new releases are made periodically.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up and use `inject` for dependency injection. It covers configuring bindings, requesting instances directly with `inject.instance()`, and automatically injecting parameters into functions using `@inject.autoparams` (with type hints) or explicitly with `@inject.params`.

import inject

# 1. Define services/dependencies
class Cache:
    def save(self, key, value):
        print(f"Saving to cache: {key} = {value}")

class DbInterface:
    def query(self, statement):
        print(f"Executing DB query: {statement}")
        return [f"result_for_{statement}"]

# 2. Configure bindings (once at application start)
def config(binder):
    binder.bind(Cache, Cache())
    binder.bind(DbInterface, DbInterface())

inject.configure(config)

# 3. Use dependency injection
# Method 1: Using inject.instance()
cache_instance = inject.instance(Cache)
cache_instance.save('app_init', 'initial_value')

# Method 2: Using @inject.autoparams (requires type hints)
@inject.autoparams
def process_data(data: str, cache: Cache, db: DbInterface):
    cache.save('processed', data)
    results = db.query(f"SELECT * FROM data WHERE value = '{data}'")
    print(f"Processed '{data}', results: {results}")

process_data('example_data')

# Method 3: Using @inject.params (explicitly name dependencies)
@inject.params(cache=Cache, db=DbInterface)
def report_status(message: str, cache=None, db=None):
    if cache: cache.save('status', message)
    if db: db.query(f"INSERT INTO logs VALUES ('{message}')")
    print(f"Status reported: {message}")

report_status('Application running successfully')

view raw JSON →