Pinject
raw JSON → 0.15.3 verified Fri May 01 auth: no python maintenance
A pythonic dependency injection library for Python, inspired by Guice. Current version is 0.15.3 (last release on PyPI 0.14.1 but GitHub has 0.15.3). Development appears to be in maintenance mode with no recent releases.
pip install pinject Common errors
error AttributeError: module 'pinject' has no attribute 'injectable' ↓
cause Using deprecated @injectable decorator which was removed or aliased.
fix
Use @pinject.inject() instead of @pinject.injectable.
error TypeError: 'module' object is not callable ↓
cause Trying to invoke a module as a function, e.g., pinject.new_object_graph() but imported pinject incorrectly.
fix
Make sure you import correctly: from pinject import new_object_graph
error TypeError: object() takes no arguments ↓
cause Incorrectly using @inject without parentheses. @inject is a function that returns a decorator, so you need @inject() with parentheses.
fix
Use @pinject.inject() (with parentheses) on the __init__ method.
Warnings
gotcha Pinject does not support Python 3.12+ due to removal of inspect.getargspec and other deprecated APIs. Pinject relies on inspect module details that are removed in Python 3.12. ↓
fix Use Python 3.11 or earlier, or switch to an actively maintained DI library like 'inject' or 'dependency-injector'.
deprecated @injectable decorator is deprecated since v0.10. Use @inject instead. ↓
fix Replace @pinject.injectable with @pinject.inject() (note the parentheses).
breaking In v0.10, the default method names for BindingSpec were changed. Custom names can be set via 'configure_method_name' and 'dependencies_method_name' in new_object_graph. ↓
fix If you relied on default method names like 'configure', they still work. Only breaking if you overrode them and expected the old behavior.
Imports
- new_object_graph wrong
import pinject new_object_graph = pinject.new_object_graphcorrectfrom pinject import new_object_graph - inject wrong
from pinject import injectablecorrectfrom pinject import inject - BindingSpec wrong
from pinject import binding_speccorrectfrom pinject import BindingSpec
Quickstart
import pinject
class MyClass:
@pinject.inject()
def __init__(self, dep):
self.dep = dep
class DepClass:
pass
obj_graph = pinject.new_object_graph(binding_specs=[], modules=[DepClass])
obj = obj_graph.provide(MyClass)
print(obj.dep.__class__.__name__) # DepClass