Lagom Dependency Injection

2.7.7 · active · verified Thu Apr 16

Lagom is a dependency injection container designed to give you 'just enough' help with building your dependencies. It emphasizes type-based auto-wiring with strong Mypy integration and minimal changes to existing code. It currently supports Python 3.7+ and is actively maintained with frequent releases.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates basic auto-wiring with `Container`, explicit dependency configuration, and integrating with functions using `@bind_to_container`. It shows how to provide a `Config` instance and how `HttpClient` and `MyService` are automatically resolved based on their type hints.

from lagom import Container, injectable

class Config:
    def __init__(self, api_key: str):
        self.api_key = api_key

class HttpClient:
    def __init__(self, config: Config):
        self.config = config

class MyService:
    def __init__(self, http_client: HttpClient):
        self.http_client = http_client

# Create a container
container = Container()

# Configure a dependency (e.g., from environment variables)
# In a real app, this might come from os.environ.get or a settings file
container[Config] = lambda: Config(api_key=os.environ.get('MY_API_KEY', 'default_api_key'))

# Lagom will auto-wire HttpClient and MyService based on type hints
service = container[MyService]

print(f"Service created with API Key: {service.http_client.config.api_key}")

# Example with function binding
from lagom.decorators import bind_to_container

@bind_to_container(container)
def process_request(service: MyService, request_data: dict):
    print(f"Processing request with API Key: {service.http_client.config.api_key}")
    return {"status": "ok", "data": request_data}

process_request(request_data={"id": 123})

view raw JSON →