0
# Pinject
1
2
A pythonic dependency injection library that simplifies object graph assembly and management. Pinject enables developers to build maintainable, testable applications by decoupling object creation from business logic, using implicit bindings based on naming conventions and automatic constructor injection.
3
4
## Package Information
5
6
- **Package Name**: pinject
7
- **Language**: Python
8
- **Installation**: `pip install pinject`
9
10
## Core Imports
11
12
```python
13
import pinject
14
```
15
16
For specific functions and classes:
17
18
```python
19
from pinject import (
20
new_object_graph, BindingSpec, inject, injectable, provides, annotate_arg,
21
copy_args_to_internal_fields, copy_args_to_public_fields,
22
SINGLETON, PROTOTYPE, Scope
23
)
24
```
25
26
## Basic Usage
27
28
```python
29
import pinject
30
31
class OuterClass(object):
32
def __init__(self, inner_class):
33
self.inner_class = inner_class
34
35
class InnerClass(object):
36
def __init__(self):
37
self.forty_two = 42
38
39
# Create an object graph
40
obj_graph = pinject.new_object_graph()
41
42
# Provide instances with automatic dependency injection
43
outer_class = obj_graph.provide(OuterClass)
44
print(outer_class.inner_class.forty_two) # 42
45
```
46
47
## Architecture
48
49
Pinject's design centers around automatic dependency resolution:
50
51
- **ObjectGraph**: Central container that manages dependency injection and object creation
52
- **Implicit Bindings**: Automatic dependency resolution based on constructor parameter names
53
- **Explicit Bindings**: Custom binding specifications through BindingSpec classes and provider methods
54
- **Scoping**: Object lifecycle management (SINGLETON, PROTOTYPE, custom scopes)
55
- **Decorators**: Fine-grained control over injection behavior and explicit marking of injectable classes
56
57
This pythonic approach minimizes boilerplate code by automatically inferring dependencies from parameter names and class structures, while supporting advanced features like custom binding specifications, object graph validation, and circular dependency detection.
58
59
## Capabilities
60
61
### Object Graph Creation
62
63
Core functionality for creating and configuring dependency injection containers. Object graphs serve as the central point for providing instances with automatic dependency resolution.
64
65
```python { .api }
66
def new_object_graph(
67
modules=None,
68
classes=None,
69
binding_specs=None,
70
only_use_explicit_bindings=False,
71
allow_injecting_none=False,
72
configure_method_name='configure',
73
dependencies_method_name='dependencies',
74
get_arg_names_from_class_name=None,
75
get_arg_names_from_provider_fn_name=None,
76
id_to_scope=None,
77
is_scope_usable_from_scope=None,
78
use_short_stack_traces=True
79
):
80
"""
81
Creates a new ObjectGraph for dependency injection.
82
83
Args:
84
modules: Modules to search for classes (default: all imported modules)
85
classes: Specific classes to create implicit bindings for
86
binding_specs: BindingSpec classes to get bindings from
87
only_use_explicit_bindings: Whether to only use explicit bindings
88
allow_injecting_none: Whether to allow None injection
89
configure_method_name: Name of binding spec configure method
90
dependencies_method_name: Name of binding spec dependencies method
91
get_arg_names_from_class_name: Function to get arg names from class name
92
get_arg_names_from_provider_fn_name: Function to get arg names from provider
93
id_to_scope: Mapping of scope IDs to scope instances
94
is_scope_usable_from_scope: Function to check scope compatibility
95
use_short_stack_traces: Whether to use short stack traces in errors
96
97
Returns:
98
ObjectGraph: New object graph instance
99
"""
100
101
class ObjectGraph:
102
"""Container for dependency injection and object creation."""
103
104
def provide(self, cls):
105
"""
106
Provides an instance of the given class with dependency injection.
107
108
Args:
109
cls: Class to instantiate
110
111
Returns:
112
Instance of cls with dependencies injected
113
"""
114
```
115
116
[Object Graph Creation](./object-graph.md)
117
118
### Dependency Injection Decorators
119
120
Decorators for controlling injection behavior, marking classes as injectable, defining provider methods, and specifying argument annotations for precise dependency resolution.
121
122
```python { .api }
123
def inject(arg_names=None, all_except=None): ...
124
def injectable(fn): ...
125
def provides(arg_name=None, annotated_with=None, in_scope=None): ...
126
def annotate_arg(arg_name, with_annotation): ...
127
```
128
129
[Dependency Injection Decorators](./decorators.md)
130
131
### Binding Specifications
132
133
Custom binding configuration through BindingSpec classes that define explicit relationships between interfaces and implementations, enabling complex dependency scenarios.
134
135
```python { .api }
136
class BindingSpec(object):
137
def configure(self, bind): ...
138
```
139
140
[Binding Specifications](./binding-specs.md)
141
142
### Scoping and Lifecycle Management
143
144
Object lifecycle control through built-in and custom scopes, managing when and how instances are created and shared across the application.
145
146
```python { .api }
147
SINGLETON: _SingletonScopeId
148
PROTOTYPE: _PrototypeScopeId
149
150
class Scope(object):
151
def provide(self, binding_key, default_provider_fn): ...
152
```
153
154
[Scoping and Lifecycle Management](./scoping.md)
155
156
### Field Initialization Utilities
157
158
Convenience decorators for automatically copying constructor arguments to instance fields, reducing boilerplate code in class initializers.
159
160
```python { .api }
161
def copy_args_to_internal_fields(fn): ...
162
def copy_args_to_public_fields(fn): ...
163
```
164
165
[Field Initialization Utilities](./field-initialization.md)
166
167
### Error Handling
168
169
Comprehensive error system providing clear, actionable feedback for dependency injection issues, from binding conflicts to circular dependencies.
170
171
```python { .api }
172
class Error(Exception): ...
173
class AmbiguousArgNameError(Error): ...
174
class BadDependencyScopeError(Error): ...
175
class ConflictingExplicitBindingsError(Error): ...
176
class CyclicInjectionError(Error): ...
177
# ... and 23 more specific error types
178
```
179
180
[Error Handling](./error-handling.md)