Simple-DI

0.1.5 · active · verified Fri Apr 17

Simple-DI is a lightweight Python library for dependency injection. It helps manage application components and their dependencies in a clear, testable, and maintainable way using a container pattern. As of version 0.1.5, it provides core features like `Container` for organizing providers and `Provider` for defining how dependencies are created. Releases are infrequent, driven by new features or bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a `Container` for configuration, nest containers, define `Provider` instances with dependencies, resolve dependencies using `.get()`, and dynamically override configuration values.

from simple_di import Container, Provider

class MyConfig(Container):
    debug_mode = Provider(bool, default=False)
    database_url = Provider(str, default="sqlite:///test.db")

class MyDependencies(Container):
    # Instantiate nested containers
    config = MyConfig()

    # A factory function for a database client
    def _create_db_client(url: str):
        print(f"[DB] Connecting to {url}...")
        return f"DatabaseClient({url})"

    # Define a provider for the database client, depending on config.database_url
    db_client = Provider(_create_db_client, config.database_url)

    # A factory function for the main application
    def _create_app(client):
        print(f"[App] Creating app with client: {client}")
        return f"MyApp({client})"

    # Define a provider for the app, depending on db_client
    app = Provider(_create_app, db_client)

# Instantiate the main dependency container
my_app_deps = MyDependencies()

# Accessing dependencies (calling .get() is crucial to resolve them)
print("\n--- First Resolution ---")
db_client_instance = my_app_deps.db_client.get()
print(f"Retrieved DB Client: {db_client_instance}")

app_instance = my_app_deps.app.get()
print(f"Retrieved App: {app_instance}")

# Overriding a configuration value and observing changes
print("\n--- Overriding Configuration ---")
my_app_deps.config.database_url.set("postgresql://user:pass@host/prod_db")

# Accessing again will re-evaluate the db_client provider due to dependency change
print("\n--- Second Resolution (after override) ---")
new_db_client_instance = my_app_deps.db_client.get()
print(f"Retrieved NEW DB Client: {new_db_client_instance}")

# Accessing app again will use the new db client
new_app_instance = my_app_deps.app.get()
print(f"Retrieved NEW App: {new_app_instance}")

view raw JSON →