Injector - Python Dependency Injection Framework

0.24.0 · active · verified Fri Apr 10

Injector is a Python dependency injection framework, inspired by Guice, that simplifies managing application components and their dependencies. It encourages compartmentalized code through the use of modules and supports static type checking. The library currently is at version 0.24.0 and has a regular release cadence with recent updates focusing on Python version compatibility and typing enhancements. [3, 4, 10]

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up basic dependency injection using `injector`. It defines `Config`, `DatabaseConnection` (as a singleton), and `Service` classes. A `Module` is used to provide the `Config` instance, including a placeholder for environment variable-driven configuration. The `Injector` then resolves and provides instances, showcasing constructor injection with type hints. [4, 10, 11]

from injector import Injector, inject, singleton, Module, provider

class Config:
    def __init__(self, value: str = "default"): 
        self.value = value

@singleton
class DatabaseConnection:
    def __init__(self, config: Config):
        self.config = config
        # Simulate a connection based on config
        self.status = f"Connected to DB with {self.config.value}"

class Service:
    @inject
    def __init__(self, db: DatabaseConnection):
        self.db = db

class MyModule(Module):
    @singleton
    @provider
    def provide_config(self) -> Config:
        # In a real app, this might come from env vars or a file
        env_val = os.environ.get('APP_CONFIG_VALUE', 'configured_via_module')
        return Config(value=env_val)

def main():
    injector = Injector([MyModule])
    service = injector.get(Service)
    print(service.db.status)

if __name__ == "__main__":
    import os
    # os.environ['APP_CONFIG_VALUE'] = 'production_setting' # Uncomment to test env var injection
    main()

view raw JSON →