dependencies
raw JSON → 7.7.1 verified Mon Apr 27 auth: no python
A Python library for constructor injection designed with OOP in mind. Current version 7.7.1. It uses a simple decorator-based API to inject dependencies into class constructors, supporting type hints and aliases. Release cadence is irregular.
pip install dependencies Common errors
error dependencies.errors.DependencyError: 'Logger' is not registered. ↓
cause Missing binding for 'Logger' class.
fix
Add
binder.bind(Logger, value(Logger())) inside your configure function. error AttributeError: 'Inject' object has no attribute 'configure' ↓
cause Using `Inject` as a decorator instead of instantiating.
fix
Change
@Inject to container = Inject(); container.configure(...). error TypeError: __init__() missing 1 required positional argument: 'logger' ↓
cause Using `This()` without type hint or incorrect usage.
fix
Add type hint:
def __init__(self, logger: Logger = This()): error RecursionError: maximum recursion depth exceeded ↓
cause Circular dependency between classes.
fix
Refactor to break the cycle or use
This(lazy=True) for one of the dependencies. Warnings
gotcha Inject must be used as a class instance, not a decorator. Common mistake: decorating with @Inject instead of instantiating and calling configure. ↓
fix Use `container = Inject(); container.configure(...)` instead of `@Inject`.
breaking In version 6.x, `Inject` was a decorator. In 7.x, it became a class. Import paths changed. ↓
fix Use `from dependencies import Inject` (class). Code using `@inject` must be rewritten.
deprecated Using `This()` with non-type-hinted arguments may be deprecated in future versions. ↓
fix Always provide type hints for parameters using `This()`.
gotcha When using `autoload=False`, you must explicitly configure all dependencies. Common mistake: forgetting to bind a dependency leads to `DependencyError`. ↓
fix Bind all dependencies with `binder.bind(...)` inside `configure` function.
gotcha Circular dependencies are not detected automatically and cause recursion errors. ↓
fix Avoid circular references or use lazy injection with `This(lazy=True)`.
Imports
- Inject
from dependencies import Inject - This
from dependencies import This - value
from dependencies import value
Quickstart
from dependencies import Inject, This, value
class Logger:
pass
class Database:
def __init__(self, logger: Logger = This()):
self.logger = logger
def configure(binder):
db = Database()
binder.bind(Database, value(db))
binder.bind(Logger, value(Logger()))
container = Inject(autoload=False)
container.configure(configure)
db = container.instance(Database)
print(db.logger.__class__.__name__) # Logger