punq - IOC Container for Python

raw JSON →
0.7.0 verified Fri May 01 auth: no python

A lightweight, dependency injection container for Python 3.8+. Version 0.7.0 is the latest stable release. The library supports registering and resolving services, auto-registration, scoped containers, and singleton lifetimes. Release cadence is irregular.

pip install punq
error ModuleNotFoundError: No module named 'punq'
cause punq is not installed.
fix
Run: pip install punq
error punq.exceptions.ContainerResolutionError: No registration found for <class '...'>
cause You tried to resolve a type that has not been registered.
fix
Register the type before resolving: container.register(MyClass, MyClass())
error AttributeError: 'Container' object has no attribute 'child'
cause The `child()` method was introduced in v0.8.0-dev. You are using an older version.
fix
Upgrade to the dev release with: pip install punq==0.8.0-dev1 or later.
error TypeError: 'str' object is not callable
cause You attempted to register a string instance without the instance argument (e.g., container.register(str) instead of container.register(str, 'value')).
fix
Use: container.register(str, 'my string')
breaking Version 0.7.0 drops Python 3.7 support. If you need Python 3.7, use punq 0.6.2 or earlier.
fix Use Python >=3.8.1 or pin punq to <=0.6.2.
gotcha Registering a class with a complex constructor (e.g., multiple dependencies) without using the container's auto-wiring may raise ContainerResolutionError if dependencies are not registered.
fix Register all dependencies explicitly or use the `auto_register` feature (available in dev versions).
gotcha The `container.child()` method for scoped containers is only available in v0.8.0-dev and later. Using it in v0.7.0 will raise AttributeError.
fix Upgrade to dev version or avoid using child().
deprecated Auto-registration API is in development; the final API may change. Not yet stable.
fix Do not rely on auto-registration in production yet.

Create a container, register a string instance, and resolve it.

import punq

container = punq.Container()
container.register(str, "Hello, world!")
resolved = container.resolve(str)
print(resolved)