# Python dependency injection libraries

Python dependency injection libraries supply the objects a class or function needs instead of letting it construct them itself. A container registers how to build each dependency and resolves the full graph when the application asks for an object. These libraries let developers swap databases, clients, and other services in tests without changing application code.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Dependency Injector](#dependency-injector) | 11.0M | 4.9K | Jun 2026 | MIT |
| [Injector](#injector) | 3.9M | 1.5K | Jan 2026 | BSD |
| [svcs](#svcs) | 3.0M | 423 | Aug 2026 | MIT |
| [Inject](#inject) | 2.9M | 778 | Jul 2026 | Apache-2.0 |
| [FastDepends](#fast-depends) | 2.3M | 519 | Nov 2026 | MIT |
| [Dishka](#dishka) | 1.5M | 1.3K | Apr 2026 | Apache-2.0 |
| [Lagom](#lagom) | 447.1K | 357 | Jul 2025 | MIT |
| [Wireup](#wireup) | 155.3K | 442 | Nov 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Dependency Injector](#dependency-injector) has the most monthly downloads in this comparison, at 11.0M.

## Capabilities

| Library | Async factories | Resource cleanup |
| --- | --- | --- |
| [Dependency Injector](#dependency-injector) | Yes | Yes |
| [Injector](#injector) | Undocumented | Undocumented |
| [svcs](#svcs) | Yes | Yes |
| [Inject](#inject) | Yes | Yes |
| [FastDepends](#fast-depends) | Yes | Yes |
| [Dishka](#dishka) | Yes | Yes |
| [Lagom](#lagom) | Yes | Yes |
| [Wireup](#wireup) | Yes | Yes |

## Libraries

### Dependency Injector

[GitHub](https://github.com/ets-labs/python-dependency-injector) · [PyPI](https://pypi.org/project/dependency-injector) · [Docs](https://python-dependency-injector.ets-labs.org/)

Assembles application objects using explicit providers and containers.

- Downloads / mo: 11.0M
- Stars: 4.9K
- Last release: 4.49.1
- License: MIT
- Capabilities: [From the Dependency Injector docs](https://python-dependency-injector.ets-labs.org/)

**Strengths**

- **Replaces providers for tests.** Override an API-client provider with a test stub.
- **Initializes and closes resources.** Use Resource providers for components with startup and shutdown.

**Watch out for**

- **Ordinary singletons need thread protection.** Use ThreadSafeSingleton when multiple threads share a provider.
- **Function resources cannot define shutdown.** Use a context manager or generator when cleanup is required.

```sh
python -m pip install dependency-injector==4.49.1
```

**mlco2/codecarbon** (1.9K stars)

[mlco2/codecarbon](https://github.com/mlco2/codecarbon) 

```python
def init_container():
    container = ServerContainer()
    container.wire(
        modules=[
            emissions,
            runs,
            experiments,
            projects,
            project_api_tokens,
            organizations,
            telemetry,
            authenticate,
            auth_service,
        ]
    )
    return container

```

[carbonserver/main.py](https://github.com/mlco2/codecarbon/blob/9b02bdc8bafd57023e10e7ff0388ab86b329831e/carbonserver/main.py#L62-L77) · [More projects using Dependency Injector →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20dependency-injector%20for%20dependency%20binding%20and%20resource%20lifecycle&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from dependency_injector import providers

service = providers.Factory(dict, message='hello')
print(service())

```

From [resource.py](https://python-dependency-injector.ets-labs.org/providers/factory.html)

### Injector

[GitHub](https://github.com/python-injector/injector) · [PyPI](https://pypi.org/project/injector) · [Docs](https://github.com/python-injector/injector/blob/master/README.md)

Resolves Python object dependencies through configured Injector instances.

- Downloads / mo: 3.9M
- Stars: 1.5K
- Last release: 0.24.0
- License: BSD
- Capabilities: [From the Injector docs](https://github.com/python-injector/injector/blob/master/README.md)

**Strengths**

- **Uses separate container instances.** Keep independent dependency configurations in separate Injector instances.
- **Offers custom lifetime scopes.** Implement Scope.get to cache objects for a chosen lifetime.

**Watch out for**

- **Provider work blocks other injections.** Keep blocking I/O outside providers to avoid blocking other threads.
- **Automatic injection excludes ordinary methods.** Use constructor injection rather than decorating other object methods.

```sh
python -m pip install injector==0.24.0
```

**zylon-ai/private-gpt** (57.6K stars)

[zylon-ai/private-gpt](https://github.com/zylon-ai/private-gpt) 

```python
def create_application_injector() -> Injector:
    """Create a new injector with the default bindings."""
    _injector = Injector(auto_bind=True)
    _injector.binder.bind(Settings, to=unsafe_typed_settings)
    return _injector

```

[private_gpt/di.py](https://github.com/zylon-ai/private-gpt/blob/9d37a133f1d50e9b10ed527ce198ffd7ded1af70/private_gpt/di.py#L32-L36) · [More projects using Injector →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20injector%20for%20dependency%20binding%20and%20resource%20lifecycle&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from dataclasses import dataclass
from injector import Injector, inject
class Inner:
    def __init__(self):
        self.forty_two = 42

@inject
@dataclass
class Outer:
    inner: Inner

injector = Injector()
outer = injector.get(Outer)
print(outer.inner.forty_two)  # Prints 42

```

From [README.md](https://github.com/python-injector/injector/blob/master/README.md)

### svcs

[GitHub](https://github.com/hynek/svcs) · [PyPI](https://pypi.org/project/svcs) · [Docs](https://svcs.hynek.me/)

Provides a service locator.

- Downloads / mo: 3.0M
- Stars: 423
- Last release: 26.2.0
- License: MIT
- Capabilities: [From the svcs docs](https://svcs.hynek.me/)

```sh
python -m pip install svcs==26.2.0
```

**apache/airflow** (47.5K stars)

[apache/airflow](https://github.com/apache/airflow) 

```python
@svcs.fastapi.lifespan
async def lifespan(app: FastAPI, registry: svcs.Registry):
    app.state.lifespan_called = True

    # According to svcs's docs this shouldn't be needed, but something about SubApps is odd, and we need to
    # record this here
    app.state.svcs_registry = registry

    registry.register_factory(JWTGenerator, create_jwt_generator)

    # InProcessExecutionAPI stubs out JWTValidator: don't re-register in that case.
    if JWTValidator not in registry:
        # Create an app scoped validator, so that we don't have to fetch it every time
        registry.register_value(JWTValidator, _jwt_validator(), ping=JWTValidator.status)

    yield

```

[airflow-core/src/airflow/api_fastapi/execution_api/app.py](https://github.com/apache/airflow/blob/ea289c5bb41a6fa206f23dac210055547ea1bc7d/airflow-core/src/airflow/api_fastapi/execution_api/app.py#L95-L110) · [More projects using svcs →](https://dashboard.exa.ai/playground/search?q=svcs%20GitHub%20projects)

**Quickstart**

```python
import svcs

with svcs.Registry() as registry:
    registry.register_value(str, 'hello')
    with svcs.Container(registry) as services:
        print(services.get(str))

```

From [core-concepts.html](https://svcs.hynek.me/en/stable/core-concepts.html)

### Inject

[GitHub](https://github.com/ivankorobkov/python-inject) · [PyPI](https://pypi.org/project/inject) · [Docs](https://github.com/ivankorobkov/python-inject/blob/master/README.md)

Injects registered dependencies into parameters or attributes through a shared injector.

- Downloads / mo: 2.9M
- Stars: 778
- Last release: 5.5.0
- License: Apache-2.0
- Capabilities: [From the Inject docs](https://github.com/ivankorobkov/python-inject/blob/master/README.md)

**Strengths**

- **Reads parameter type annotations.** Use autoparams to resolve annotated function dependencies.
- **Supports custom current-user providers.** Bind a provider to return the current thread’s user.

**Watch out for**

- **Implicit bindings create shared instances.** Disable runtime bindings to require explicit registrations.
- **Configuration is shared.** Use clear=True when replacing an existing configuration.

```sh
python -m pip install inject==5.5.0
```

**geigi/cozy** (1.2K stars)

[geigi/cozy](https://github.com/geigi/cozy) 

```python
def configure_inject(self, binder):
    binder.bind_to_provider(SqliteDatabase, get_db)
    binder.bind("MainWindow", self.main_window)
    binder.bind("GtkApp", self.gtk_app)
    binder.bind("MainWindowBuilder", self.main_window_builder)
    binder.bind_to_constructor(Gio.Settings, lambda: Gio.Settings("com.github.geigi.cozy"))
    binder.bind_to_constructor(ApplicationSettings, lambda: ApplicationSettings())
    binder.bind_to_constructor(Settings, lambda: Settings())
    binder.bind_to_constructor("FilesystemMonitor", lambda: FilesystemMonitor())
    binder.bind_to_constructor(OfflineCache, lambda: OfflineCache())
    binder.bind_to_constructor(Player, lambda: Player())
    binder.bind_to_constructor(Library, lambda: Library())
    binder.bind_to_constructor(DatabaseImporter, lambda: DatabaseImporter())
    binder.bind_to_constructor(LibraryViewModel, lambda: LibraryViewModel())
    binder.bind_to_constructor(SearchViewModel, lambda: SearchViewModel())
    binder.bind_to_constructor(Files, lambda: Files())
    binder.bind_to_constructor(BookDetailViewModel, lambda: BookDetailViewModel())
    binder.bind_to_constructor(PlaybackControlViewModel, lambda: PlaybackControlViewModel())
    binder.bind_to_constructor(HeaderbarViewModel, lambda: HeaderbarViewModel())
    binder.bind_to_constructor(PlaybackSpeedViewModel, lambda: PlaybackSpeedViewModel())
    binder.bind_to_constructor(SleepTimerViewModel, lambda: SleepTimerViewModel())
    binder.bind_to_constructor(GstPlayer, lambda: GstPlayer())
    binder.bind_to_constructor(ToastNotifier, lambda: ToastNotifier())
    binder.bind_to_constructor(AppViewModel, lambda: AppViewModel())
    binder.bind_to_constructor(SettingsViewModel, lambda: SettingsViewModel())
    binder.bind_to_constructor(StoragesViewModel, lambda: StoragesViewModel())

```

[cozy/app_controller.py](https://github.com/geigi/cozy/blob/a4ee50d1cf1aa3ae955d8b9a4e1bd6ae2d3924c3/cozy/app_controller.py#L75-L100) · [More projects using Inject →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20inject%20for%20dependency%20binding%20and%20resource%20lifecycle&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import inject

inject.configure(lambda binder: binder.bind(str, 'hello'))
print(inject.instance(str))

```

From [README.md](https://pypi.org/pypi/inject/5.5.0/json)

### FastDepends

[GitHub](https://github.com/Lancetnik/FastDepends) · [PyPI](https://pypi.org/project/fast-depends) · [Docs](https://lancetnik.github.io/FastDepends/)

Runs the FastAPI dependency injection system outside HTTP code, with async and sync support.

- Downloads / mo: 2.3M
- Stars: 519
- Last release: 3.0.11
- License: MIT
- Capabilities: [From the FastDepends docs](https://lancetnik.github.io/FastDepends/)

```sh
python -m pip install "fast-depends[pydantic]==3.0.11"
```

**ag2ai/ag2** (5.1K stars)

[ag2ai/ag2](https://github.com/ag2ai/ag2) 

```python
def build_model(
    f: Callable[..., Any],
    *,
    sync_to_thread: bool = True,
    serialize_result: bool = True,
    use_fastdepends_errors: bool = False,
    provider: Provider | None = None,
) -> CallModel:
    return build_call_model(
        _to_async(f, sync_to_thread=sync_to_thread),
        dependency_provider=provider if provider is not None else dependency_provider,
        serializer_cls=PydanticSerializer(
            pydantic_config={"arbitrary_types_allowed": True},
            use_fastdepends_errors=use_fastdepends_errors,
        ),
        serialize_result=serialize_result,
    )

```

[ag2/utils.py](https://github.com/ag2ai/ag2/blob/6d2dd8bab8af873ea29ed759cfacb572466d925e/ag2/utils.py#L30-L46) · [More projects using FastDepends →](https://dashboard.exa.ai/playground/search?q=fast-depends%20GitHub%20projects)

**Quickstart**

```python
from fast_depends import Depends, inject

def greeting() -> str:
    return 'hello'

@inject
def show(message: str = Depends(greeting)) -> str:
    return message

print(show())

```

From [use.py](https://api.github.com/repos/Lancetnik/FastDepends/git/blobs/481efabb396d5f24635e4e4c5801d4f1bafa5ca4)

### Dishka

[GitHub](https://github.com/reagento/dishka) · [PyPI](https://pypi.org/project/dishka) · [Docs](https://dishka.readthedocs.io/en/stable/)

Builds dependency graphs with scoped caches and resource finalization.

- Downloads / mo: 1.5M
- Stars: 1.3K
- Last release: 1.10.1
- License: Apache-2.0
- Capabilities: [From the Dishka docs](https://dishka.readthedocs.io/en/stable/)

**Strengths**

- **Clears scoped dependency caches.** Scope exit clears cached dependencies and finalizes generator factories.
- **Awaits asynchronous factories.** Use an async container for synchronous and asynchronous dependency sources.

**Watch out for**

- **Sync providers block async resolution.** Keep network I/O out of synchronous providers in async containers.
- **Concurrent child scopes need locks.** Pass a matching lock_factory for concurrently used nested scopes.

```sh
python -m pip install dishka==1.10.1
```

**bitcart/bitcart** (1.0K stars)

[bitcart/bitcart](https://github.com/bitcart/bitcart) 

```python
def build_container(
    settings: Settings,
    *,
    extra_providers: Iterable[Provider] = (),
    context_overrides: dict[type[Any], Any] | None = None,
    include_plugins: bool = True,
    **kwargs: Any,
) -> AsyncContainer:
    context: dict[type[Any], Any] = {Settings: settings, TasksBroker: broker, ClientTasksBroker: client_tasks_broker}
    providers = get_providers()
    providers.extend(extra_providers)
    if include_plugins:
        plugin_classes, plugin_providers = load_plugins(settings)
        plugin_objects = init_plugins(plugin_classes)
        plugin_context = build_plugin_di_context(plugin_objects)
        context[PluginObjects] = plugin_objects
        context.update(cast(dict[type[Any], Any], plugin_context))
        providers.extend(plugin_providers)
    if context_overrides:
        context.update(context_overrides)
    return make_async_container(
        *providers,
        context=context,
        **kwargs,
    )

```

[api/ioc/__init__.py](https://github.com/bitcart/bitcart/blob/3a83c0a1440260b8bfb3dd90c7b74e808a60fc6a/api/ioc/__init__.py#L20-L44) · [More projects using Dishka →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20dishka%20for%20dependency%20binding%20and%20resource%20lifecycle&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from dishka import Provider, Scope, make_container

class Service:
    def __init__(self) -> None:
        self.message = 'hello'

provider = Provider(scope=Scope.APP)
provider.provide(Service)
container = make_container(provider)
print(container.get(Service).message)
container.close()

```

From [README.md](https://pypi.org/pypi/dishka/1.10.1/json)

### Lagom

[GitHub](https://github.com/meadsteve/lagom) · [PyPI](https://pypi.org/project/lagom) · [Docs](https://lagom-di.readthedocs.io/)

Provides a dependency injection container that gives just enough help with building dependencies.

- Downloads / mo: 447.1K
- Stars: 357
- Last release: 2.7.7
- License: MIT
- Capabilities: [From the Lagom docs](https://lagom-di.readthedocs.io/)

```sh
python -m pip install lagom==2.7.7
```

**emcie-co/parlant** (18.3K stars)

[emcie-co/parlant](https://github.com/emcie-co/parlant) 

```python
def _define_singleton(container: Container, interface: type, implementation: type) -> None:
    try:
        container[implementation] = Singleton(implementation)

        if interface != implementation:
            container[interface] = lambda c: c[implementation]
    except BaseException:
        rich.print(
            rich.text.Text(
                f"Error adding {implementation} as implementation for {interface}",
                style="bold red",
            )
        )
        raise

```

[src/parlant/bin/server.py](https://github.com/emcie-co/parlant/blob/ea737442b8ae65854a842542e544fbe7e6144bad/src/parlant/bin/server.py#L534-L547) · [More projects using Lagom →](https://dashboard.exa.ai/playground/search?q=lagom%20GitHub%20projects)

**Quickstart**

```python
from lagom import Container

class Service:
    def __init__(self) -> None:
        self.message = 'hello'

container = Container()
print(container[Service].message)

```

From [README.md](https://pypi.org/pypi/lagom/2.7.7/json)

### Wireup

[GitHub](https://github.com/maldoinc/wireup) · [PyPI](https://pypi.org/project/wireup) · [Docs](https://maldoinc.github.io/wireup/)

Provides dependency injection for Python.

- Downloads / mo: 155.3K
- Stars: 442
- Last release: 2.13.1
- License: MIT
- Capabilities: [From the Wireup docs](https://maldoinc.github.io/wireup/)

```sh
python -m pip install wireup==2.13.1
```

**Quickstart**

```python
import wireup

@wireup.injectable
class Service:
    def __init__(self) -> None:
        self.message = 'hello'

container = wireup.create_sync_container(injectables=[Service])
print(container.get(Service).message)

```

From [README.md](https://pypi.org/pypi/wireup/2.13.1/json) · [Find projects using Wireup →](https://dashboard.exa.ai/playground/search?q=wireup%20GitHub%20projects)

## FAQ

### Which Python dependency injection library should I use?

[Dependency Injector](#dependency-injector) suits applications that want an explicit graph of providers and containers. [Dishka](#dishka) suits applications that need nested scopes with cleanup of resources. [svcs](#svcs) suits teams that prefer a typed service locator over automatic injection.

### How does dependency injection work in Python?

A container records how to build each service and passes the built objects into parameters or attributes that declare them. Without a library, applications pass dependencies by hand.

### What is Dishka?

[Dishka](#dishka) is a dependency injection framework that builds dependency graphs with scoped caches. Nested scopes finalize generator-based resources when they close.

### What is Dependency Injector?

[Dependency Injector](#dependency-injector) assembles application objects from explicit providers and containers, with module wiring to inject them.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python dependency injection libraries dependency injector Injector inject dishka code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
