pico-ioc 1.1.0__py3-none-any.whl → 1.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pico_ioc/__init__.py +18 -4
- pico_ioc/_state.py +30 -0
- pico_ioc/_version.py +1 -1
- pico_ioc/api.py +206 -106
- pico_ioc/builder.py +242 -0
- pico_ioc/container.py +62 -34
- pico_ioc/decorators.py +76 -18
- pico_ioc/interceptors.py +50 -0
- pico_ioc/plugins.py +17 -1
- pico_ioc/policy.py +332 -0
- pico_ioc/proxy.py +41 -1
- pico_ioc/resolver.py +52 -33
- pico_ioc/scanner.py +76 -111
- pico_ioc/utils.py +25 -0
- pico_ioc-1.3.0.dist-info/METADATA +235 -0
- pico_ioc-1.3.0.dist-info/RECORD +20 -0
- pico_ioc/typing_utils.py +0 -29
- pico_ioc-1.1.0.dist-info/METADATA +0 -166
- pico_ioc-1.1.0.dist-info/RECORD +0 -17
- {pico_ioc-1.1.0.dist-info → pico_ioc-1.3.0.dist-info}/WHEEL +0 -0
- {pico_ioc-1.1.0.dist-info → pico_ioc-1.3.0.dist-info}/licenses/LICENSE +0 -0
- {pico_ioc-1.1.0.dist-info → pico_ioc-1.3.0.dist-info}/top_level.txt +0 -0
pico_ioc/scanner.py
CHANGED
|
@@ -6,6 +6,7 @@ import pkgutil
|
|
|
6
6
|
from types import ModuleType
|
|
7
7
|
from typing import Any, Callable, Optional, Tuple, List, Iterable
|
|
8
8
|
|
|
9
|
+
from .plugins import run_plugin_hook
|
|
9
10
|
from .container import PicoContainer, Binder
|
|
10
11
|
from .decorators import (
|
|
11
12
|
COMPONENT_FLAG,
|
|
@@ -14,11 +15,15 @@ from .decorators import (
|
|
|
14
15
|
FACTORY_FLAG,
|
|
15
16
|
PROVIDES_KEY,
|
|
16
17
|
PROVIDES_LAZY,
|
|
18
|
+
COMPONENT_TAGS,
|
|
19
|
+
PROVIDES_TAGS,
|
|
20
|
+
INTERCEPTOR_META,
|
|
17
21
|
)
|
|
18
22
|
from .proxy import ComponentProxy
|
|
19
23
|
from .resolver import Resolver
|
|
20
24
|
from .plugins import PicoPlugin
|
|
21
25
|
from . import _state
|
|
26
|
+
from .utils import _provider_from_class, _provider_from_callable
|
|
22
27
|
|
|
23
28
|
|
|
24
29
|
def scan_and_configure(
|
|
@@ -27,15 +32,15 @@ def scan_and_configure(
|
|
|
27
32
|
*,
|
|
28
33
|
exclude: Optional[Callable[[str], bool]] = None,
|
|
29
34
|
plugins: Tuple[PicoPlugin, ...] = (),
|
|
30
|
-
) ->
|
|
35
|
+
) -> tuple[int, int, list[tuple[Any, dict]]]:
|
|
31
36
|
"""
|
|
32
|
-
Scan a package,
|
|
37
|
+
Scan a package, bind components/factories, and collect interceptor declarations.
|
|
38
|
+
Returns: (component_count, factory_count, interceptor_decls)
|
|
33
39
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
plugins: Optional lifecycle plugins that receive scan/bind events.
|
|
40
|
+
interceptor_decls contains entries of the form:
|
|
41
|
+
- (cls, meta) for class-level @interceptor on a class
|
|
42
|
+
- (fn, meta) for module-level function with @interceptor
|
|
43
|
+
- ((owner_cls, fn), meta) for methods on a class decorated with @interceptor
|
|
39
44
|
"""
|
|
40
45
|
package = _as_module(package_or_name)
|
|
41
46
|
logging.info("Scanning in '%s'...", getattr(package, "__name__", repr(package)))
|
|
@@ -43,34 +48,26 @@ def scan_and_configure(
|
|
|
43
48
|
binder = Binder(container)
|
|
44
49
|
resolver = Resolver(container)
|
|
45
50
|
|
|
46
|
-
|
|
51
|
+
run_plugin_hook(plugins, "before_scan", package, binder)
|
|
47
52
|
|
|
48
|
-
comp_classes, factory_classes =
|
|
53
|
+
comp_classes, factory_classes, interceptor_decls = _collect_decorated(
|
|
49
54
|
package=package,
|
|
50
55
|
exclude=exclude,
|
|
51
56
|
plugins=plugins,
|
|
52
57
|
binder=binder,
|
|
53
58
|
)
|
|
54
59
|
|
|
55
|
-
|
|
60
|
+
run_plugin_hook(plugins, "after_scan", package, binder)
|
|
56
61
|
|
|
57
|
-
_register_component_classes(
|
|
58
|
-
|
|
59
|
-
container=container,
|
|
60
|
-
resolver=resolver,
|
|
61
|
-
)
|
|
62
|
+
_register_component_classes(classes=comp_classes, container=container, resolver=resolver)
|
|
63
|
+
_register_factory_classes(factory_classes=factory_classes, container=container, resolver=resolver)
|
|
62
64
|
|
|
63
|
-
|
|
64
|
-
factory_classes=factory_classes,
|
|
65
|
-
container=container,
|
|
66
|
-
resolver=resolver,
|
|
67
|
-
)
|
|
65
|
+
return len(comp_classes), len(factory_classes), interceptor_decls
|
|
68
66
|
|
|
69
67
|
|
|
70
|
-
# -------------------- Helpers
|
|
68
|
+
# -------------------- Helpers --------------------
|
|
71
69
|
|
|
72
70
|
def _as_module(package_or_name: Any) -> ModuleType:
|
|
73
|
-
"""Return a module from either a module object or an importable string name."""
|
|
74
71
|
if isinstance(package_or_name, str):
|
|
75
72
|
return importlib.import_module(package_or_name)
|
|
76
73
|
if hasattr(package_or_name, "__spec__"):
|
|
@@ -78,85 +75,76 @@ def _as_module(package_or_name: Any) -> ModuleType:
|
|
|
78
75
|
raise TypeError("package_or_name must be a module or importable package name (str).")
|
|
79
76
|
|
|
80
77
|
|
|
81
|
-
def
|
|
82
|
-
|
|
83
|
-
hook_name: str,
|
|
84
|
-
*args,
|
|
85
|
-
**kwargs,
|
|
86
|
-
) -> None:
|
|
87
|
-
"""Run a lifecycle hook across all plugins, logging (but not raising) exceptions."""
|
|
88
|
-
for pl in plugins:
|
|
89
|
-
try:
|
|
90
|
-
fn = getattr(pl, hook_name, None)
|
|
91
|
-
if fn:
|
|
92
|
-
fn(*args, **kwargs)
|
|
93
|
-
except Exception:
|
|
94
|
-
logging.exception("Plugin %s failed", hook_name)
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
def _iter_package_modules(
|
|
98
|
-
package: ModuleType,
|
|
99
|
-
) -> Iterable[str]:
|
|
100
|
-
"""
|
|
101
|
-
Yield fully qualified module names under the given package.
|
|
102
|
-
|
|
103
|
-
Requires the package to have a __path__ (i.e., be a package, not a single module).
|
|
104
|
-
"""
|
|
78
|
+
def _iter_package_modules(package: ModuleType) -> Iterable[str]:
|
|
79
|
+
"""Yield fully-qualified module names under a package (recursive)."""
|
|
105
80
|
try:
|
|
106
81
|
pkg_path = package.__path__ # type: ignore[attr-defined]
|
|
107
82
|
except Exception:
|
|
108
|
-
return
|
|
109
|
-
|
|
83
|
+
return
|
|
110
84
|
prefix = package.__name__ + "."
|
|
111
85
|
for _finder, name, _is_pkg in pkgutil.walk_packages(pkg_path, prefix):
|
|
112
86
|
yield name
|
|
113
87
|
|
|
114
88
|
|
|
115
|
-
def
|
|
89
|
+
def _collect_decorated(
|
|
116
90
|
*,
|
|
117
91
|
package: ModuleType,
|
|
118
92
|
exclude: Optional[Callable[[str], bool]],
|
|
119
93
|
plugins: Tuple[PicoPlugin, ...],
|
|
120
94
|
binder: Binder,
|
|
121
|
-
) -> Tuple[List[type], List[type]]:
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
95
|
+
) -> Tuple[List[type], List[type], List[tuple[Any, dict]]]:
|
|
96
|
+
comps: List[type] = []
|
|
97
|
+
facts: List[type] = []
|
|
98
|
+
interceptors: List[tuple[Any, dict]] = []
|
|
99
|
+
|
|
100
|
+
def _collect_from_class(cls: type):
|
|
101
|
+
# Class decorators
|
|
102
|
+
if getattr(cls, COMPONENT_FLAG, False):
|
|
103
|
+
comps.append(cls)
|
|
104
|
+
elif getattr(cls, FACTORY_FLAG, False):
|
|
105
|
+
facts.append(cls)
|
|
106
|
+
|
|
107
|
+
# Class-level interceptor (decorated class itself)
|
|
108
|
+
meta_class = getattr(cls, INTERCEPTOR_META, None)
|
|
109
|
+
if meta_class:
|
|
110
|
+
interceptors.append((cls, dict(meta_class)))
|
|
111
|
+
|
|
112
|
+
# Method-level interceptors
|
|
113
|
+
for _nm, fn in inspect.getmembers(cls, predicate=inspect.isfunction):
|
|
114
|
+
meta_m = getattr(fn, INTERCEPTOR_META, None)
|
|
115
|
+
if meta_m:
|
|
116
|
+
# Preserve the owner to allow proper binding (self) later
|
|
117
|
+
interceptors.append(((cls, fn), dict(meta_m)))
|
|
128
118
|
|
|
129
119
|
def _visit_module(module: ModuleType):
|
|
120
|
+
# Classes
|
|
130
121
|
for _name, obj in inspect.getmembers(module, inspect.isclass):
|
|
131
|
-
|
|
132
|
-
|
|
122
|
+
run_plugin_hook(plugins, "visit_class", module, obj, binder)
|
|
123
|
+
_collect_from_class(obj)
|
|
133
124
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
125
|
+
# Module-level functions that declare interceptors
|
|
126
|
+
for _name, fn in inspect.getmembers(module, predicate=inspect.isfunction):
|
|
127
|
+
meta = getattr(fn, INTERCEPTOR_META, None)
|
|
128
|
+
if meta:
|
|
129
|
+
interceptors.append((fn, dict(meta)))
|
|
139
130
|
|
|
140
|
-
#
|
|
131
|
+
# Walk submodules
|
|
141
132
|
for mod_name in _iter_package_modules(package):
|
|
142
133
|
if exclude and exclude(mod_name):
|
|
143
134
|
logging.info("Skipping module %s (excluded)", mod_name)
|
|
144
135
|
continue
|
|
145
|
-
|
|
146
136
|
try:
|
|
147
137
|
module = importlib.import_module(mod_name)
|
|
148
138
|
except Exception as e:
|
|
149
139
|
logging.warning("Module %s not processed: %s", mod_name, e)
|
|
150
140
|
continue
|
|
151
|
-
|
|
152
141
|
_visit_module(module)
|
|
153
142
|
|
|
154
|
-
#
|
|
143
|
+
# Also visit the root module itself (in case it's a single-file module)
|
|
155
144
|
if not hasattr(package, "__path__"):
|
|
156
145
|
_visit_module(package)
|
|
157
146
|
|
|
158
|
-
return
|
|
159
|
-
|
|
147
|
+
return comps, facts, interceptors
|
|
160
148
|
|
|
161
149
|
def _register_component_classes(
|
|
162
150
|
*,
|
|
@@ -164,26 +152,12 @@ def _register_component_classes(
|
|
|
164
152
|
container: PicoContainer,
|
|
165
153
|
resolver: Resolver,
|
|
166
154
|
) -> None:
|
|
167
|
-
"""
|
|
168
|
-
Register @component classes into the container.
|
|
169
|
-
|
|
170
|
-
Binding key:
|
|
171
|
-
- If the class has COMPONENT_KEY, use it; otherwise, bind by the class itself.
|
|
172
|
-
Laziness:
|
|
173
|
-
- If COMPONENT_LAZY is True, provide a proxy that defers instantiation.
|
|
174
|
-
"""
|
|
175
155
|
for cls in classes:
|
|
176
156
|
key = getattr(cls, COMPONENT_KEY, cls)
|
|
177
157
|
is_lazy = bool(getattr(cls, COMPONENT_LAZY, False))
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
if lazy:
|
|
182
|
-
return ComponentProxy(lambda: resolver.create_instance(c))
|
|
183
|
-
return resolver.create_instance(c)
|
|
184
|
-
return _factory
|
|
185
|
-
|
|
186
|
-
container.bind(key, _provider_factory(), lazy=is_lazy)
|
|
158
|
+
tags = tuple(getattr(cls, COMPONENT_TAGS, ()))
|
|
159
|
+
provider = _provider_from_class(cls, resolver=resolver, lazy=is_lazy)
|
|
160
|
+
container.bind(key, provider, lazy=is_lazy, tags=tags)
|
|
187
161
|
|
|
188
162
|
|
|
189
163
|
def _register_factory_classes(
|
|
@@ -192,19 +166,9 @@ def _register_factory_classes(
|
|
|
192
166
|
container: PicoContainer,
|
|
193
167
|
resolver: Resolver,
|
|
194
168
|
) -> None:
|
|
195
|
-
"""
|
|
196
|
-
Register products of @factory_component classes.
|
|
197
|
-
|
|
198
|
-
For each factory class:
|
|
199
|
-
- Instantiate the factory via the resolver.
|
|
200
|
-
- For each method with @provides:
|
|
201
|
-
- Bind the provided key to a callable that calls the factory method.
|
|
202
|
-
- If PROVIDES_LAZY is True, bind a proxy that defers the method call.
|
|
203
|
-
"""
|
|
204
169
|
for fcls in factory_classes:
|
|
205
170
|
try:
|
|
206
|
-
#
|
|
207
|
-
# elevando temporalmente el flag `_resolving` para no chocar con la guardia.
|
|
171
|
+
# Prevent accidental container access recursion while constructing factories
|
|
208
172
|
tok_res = _state._resolving.set(True)
|
|
209
173
|
try:
|
|
210
174
|
finst = resolver.create_instance(fcls)
|
|
@@ -220,19 +184,20 @@ def _register_factory_classes(
|
|
|
220
184
|
continue
|
|
221
185
|
|
|
222
186
|
is_lazy = bool(getattr(func, PROVIDES_LAZY, False))
|
|
223
|
-
|
|
224
|
-
bound = getattr(finst, attr_name, func.__get__(finst, fcls))
|
|
187
|
+
tags = tuple(getattr(func, PROVIDES_TAGS, ()))
|
|
225
188
|
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
189
|
+
# bind the method to the concrete factory instance
|
|
190
|
+
bound = getattr(finst, attr_name, func.__get__(finst, fcls))
|
|
191
|
+
prov = _provider_from_callable(bound, owner_cls=fcls, resolver=resolver, lazy=is_lazy)
|
|
192
|
+
|
|
193
|
+
if isinstance(provided_key, type):
|
|
194
|
+
# Mark for aliasing policy pipeline and ensure uniqueness of the provider key
|
|
195
|
+
try:
|
|
196
|
+
setattr(prov, "_pico_alias_for", provided_key)
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
unique_key = (provided_key, f"{fcls.__name__}.{attr_name}")
|
|
200
|
+
container.bind(unique_key, prov, lazy=is_lazy, tags=tags)
|
|
201
|
+
else:
|
|
202
|
+
container.bind(provided_key, prov, lazy=is_lazy, tags=tags)
|
|
238
203
|
|
pico_ioc/utils.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# src/pico_ioc/utils.py
|
|
2
|
+
from typing import Any, Callable
|
|
3
|
+
from .container import PicoContainer
|
|
4
|
+
from .proxy import ComponentProxy
|
|
5
|
+
|
|
6
|
+
def _wrap_if_lazy(provider: Callable, is_lazy: bool) -> Callable:
|
|
7
|
+
"""Wraps a provider in a ComponentProxy if it's marked as lazy."""
|
|
8
|
+
return (lambda: ComponentProxy(provider)) if is_lazy else provider
|
|
9
|
+
|
|
10
|
+
def _provider_from_class(cls: type, *, resolver, lazy: bool):
|
|
11
|
+
def _new():
|
|
12
|
+
return resolver.create_instance(cls)
|
|
13
|
+
return _wrap_if_lazy(_new, lazy)
|
|
14
|
+
|
|
15
|
+
def _provider_from_callable(fn, *, owner_cls, resolver, lazy: bool):
|
|
16
|
+
def _invoke():
|
|
17
|
+
kwargs = resolver.kwargs_for_callable(fn, owner_cls=owner_cls)
|
|
18
|
+
return fn(**kwargs)
|
|
19
|
+
return _wrap_if_lazy(_invoke, lazy)
|
|
20
|
+
|
|
21
|
+
def create_alias_provider(container: PicoContainer, target_key: Any) -> Callable[[], Any]:
|
|
22
|
+
"""Creates a provider that delegates the get() call to the container for another key."""
|
|
23
|
+
def _provider():
|
|
24
|
+
return container.get(target_key)
|
|
25
|
+
return _provider
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pico-ioc
|
|
3
|
+
Version: 1.3.0
|
|
4
|
+
Summary: A minimalist, zero-dependency Inversion of Control (IoC) container for Python.
|
|
5
|
+
Author-email: David Perez Cabrera <dperezcabrera@gmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 David Pérez Cabrera
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/dperezcabrera/pico-ioc
|
|
29
|
+
Project-URL: Repository, https://github.com/dperezcabrera/pico-ioc
|
|
30
|
+
Project-URL: Issue Tracker, https://github.com/dperezcabrera/pico-ioc/issues
|
|
31
|
+
Keywords: ioc,di,dependency injection,inversion of control,decorator
|
|
32
|
+
Classifier: Development Status :: 4 - Beta
|
|
33
|
+
Classifier: Programming Language :: Python :: 3
|
|
34
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
35
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
39
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
40
|
+
Classifier: Operating System :: OS Independent
|
|
41
|
+
Requires-Python: >=3.8
|
|
42
|
+
Description-Content-Type: text/markdown
|
|
43
|
+
License-File: LICENSE
|
|
44
|
+
Dynamic: license-file
|
|
45
|
+
|
|
46
|
+
# 📦 Pico-IoC: A Minimalist IoC Container for Python
|
|
47
|
+
|
|
48
|
+
[](https://pypi.org/project/pico-ioc/)
|
|
49
|
+
[](https://deepwiki.com/dperezcabrera/pico-ioc)
|
|
50
|
+
[](https://opensource.org/licenses/MIT)
|
|
51
|
+

|
|
52
|
+
[](https://codecov.io/gh/dperezcabrera/pico-ioc)
|
|
53
|
+
[](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
|
|
54
|
+
[](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
|
|
55
|
+
[](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
|
|
56
|
+
|
|
57
|
+
**pico-ioc** is a **tiny, zero-dependency, decorator-based IoC container for Python**.
|
|
58
|
+
It helps you build loosely-coupled, testable apps without manual wiring. Inspired by the Spring ecosystem, but minimal.
|
|
59
|
+
|
|
60
|
+
> ⚠️ **Requires Python 3.10+** (uses `typing.Annotated` and `include_extras=True`).
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## ⚖️ Principles
|
|
65
|
+
|
|
66
|
+
* **Focus & Simplicity**: A minimal core for one job: managing dependencies. It avoids accidental complexity by doing one thing well.
|
|
67
|
+
* **Predictable & Explicit**: No magic. Behavior is deterministic, relying on explicit decorators and a clear resolution order.
|
|
68
|
+
* **Unified Composition Root**: The application is assembled from a single entry point (`init`) which defines a clear, predictable boundary. This ensures a stable and understandable bootstrap process.
|
|
69
|
+
* **Fail-Fast Bootstrap**: Catches dependency graph errors at startup, not in production. If the application runs, it's wired correctly.
|
|
70
|
+
* **Testability First**: Features like `scope()` and `overrides` are first-class citizens, enabling fast and isolated testing.
|
|
71
|
+
* **Extensible by Design**: Lifecycle hooks and AOP are available through a clean Plugin and Interceptor API without altering the core.
|
|
72
|
+
* **Framework Agnostic**: Zero hard dependencies. It works with any Python application, from simple scripts to complex web servers.
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## ✨ Why Pico-IoC?
|
|
77
|
+
|
|
78
|
+
`pico-ioc` exists to solve a common problem that arises as Python applications grow: managing how objects are created and connected becomes complex and brittle. This manual wiring, where a change deep in the application can cause a cascade of updates, makes the code hard to test and maintain. `pico-ioc` introduces the principle of Inversion of Control (IoC) in a simple, Pythonic way. Instead of you creating and connecting every object, you declare your components with a simple `@component` decorator, and the container automatically wires them together based on their type hints. It brings the architectural robustness and testability of mature frameworks like Spring to the Python ecosystem, but without the heavy boilerplate, allowing you to build complex, loosely-coupled applications that remain simple to manage.
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
| Feature | Manual Wiring | With Pico-IoC |
|
|
82
|
+
| :------------------ | :------------------------------------------------ | :------------------------------ |
|
|
83
|
+
| **Object Creation** | `service = Service(Repo(Config()))` | `svc = container.get(Service)` |
|
|
84
|
+
| **Testing** | Manual replacement or monkey-patching | `overrides={Repo: FakeRepo()}` |
|
|
85
|
+
| **Coupling** | High (code knows about constructors) | Low (code just asks for a type) |
|
|
86
|
+
| **Maintenance** | Brittle (changing a constructor breaks consumers) | Robust (changes are isolated) |
|
|
87
|
+
| **Learning Curve** | Ad-hoc, implicit patterns | Uniform, explicit, documented |
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 🧩 Features
|
|
93
|
+
|
|
94
|
+
### Core
|
|
95
|
+
|
|
96
|
+
* **Zero dependencies** — pure Python, framework-agnostic.
|
|
97
|
+
* **Single Entry Point (`init`)** — Robustly bootstrap your entire application from a single root package, enforcing a clean "Composition Root" pattern.
|
|
98
|
+
* **Decorator API** — `@component`, `@factory_component`, `@provides`, `@plugin`.
|
|
99
|
+
* **Fail-fast bootstrap** — eager by default; missing deps surface at startup.
|
|
100
|
+
* **Opt-in lazy** — `lazy=True` wraps with `ComponentProxy`.
|
|
101
|
+
* **Smart resolution order** — parameter name → type annotation → MRO → string.
|
|
102
|
+
* **Overrides for testing** — inject mocks/fakes directly via `init(overrides={...})`.
|
|
103
|
+
* **Public API helper** — auto-export decorated symbols in `__init__.py`.
|
|
104
|
+
* **Thread/async safe** — isolation via `ContextVar`.
|
|
105
|
+
|
|
106
|
+
### Advanced
|
|
107
|
+
|
|
108
|
+
* **Qualifiers & collections** — `list[Annotated[T, Q]]` filters by qualifier.
|
|
109
|
+
* **Flexible Scopes (`scope`)** — Create lightweight, temporary containers from multiple modules, ideal for testing, scripting, or modular tasks.
|
|
110
|
+
* **Interceptors API** — observe/modify resolution, instantiation, invocation, errors.
|
|
111
|
+
* **Conditional providers** — activate components by env vars or predicates.
|
|
112
|
+
* **Plugins** — lifecycle hooks (`before_scan`, `after_ready`).
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 📦 Installation
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
# Requires Python 3.10+
|
|
120
|
+
pip install pico-ioc
|
|
121
|
+
````
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 🚀 Quick start
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from pico_ioc import component, init
|
|
129
|
+
|
|
130
|
+
@component
|
|
131
|
+
class Config:
|
|
132
|
+
url = "sqlite:///demo.db"
|
|
133
|
+
|
|
134
|
+
@component
|
|
135
|
+
class Repo:
|
|
136
|
+
def __init__(self, cfg: Config):
|
|
137
|
+
self.url = cfg.url
|
|
138
|
+
def fetch(self): return f"fetching from {self.url}"
|
|
139
|
+
|
|
140
|
+
@component
|
|
141
|
+
class Service:
|
|
142
|
+
def __init__(self, repo: Repo):
|
|
143
|
+
self.repo = repo
|
|
144
|
+
def run(self): return self.repo.fetch()
|
|
145
|
+
|
|
146
|
+
# bootstrap
|
|
147
|
+
import myapp
|
|
148
|
+
c = init(myapp)
|
|
149
|
+
svc = c.get(Service)
|
|
150
|
+
print(svc.run())
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**Output:**
|
|
154
|
+
|
|
155
|
+
```
|
|
156
|
+
fetching from sqlite:///demo.db
|
|
157
|
+
```
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
### Quick overrides for testing
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from pico_ioc import init
|
|
164
|
+
import myapp
|
|
165
|
+
|
|
166
|
+
fake = {"repo": "fake-data"}
|
|
167
|
+
c = init(myapp, overrides={
|
|
168
|
+
"fast_model": fake, # constant instance
|
|
169
|
+
"user_service": lambda: {"id": 1}, # provider
|
|
170
|
+
})
|
|
171
|
+
assert c.get("fast_model") == {"repo": "fake-data"}
|
|
172
|
+
```
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
### Scoped subgraphs
|
|
176
|
+
|
|
177
|
+
For unit tests or lightweight integration, you can bootstrap **only a subset of the graph**.
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
from pico_ioc
|
|
181
|
+
from src.runner_service import RunnerService
|
|
182
|
+
from tests.fakes import FakeDocker
|
|
183
|
+
import src
|
|
184
|
+
|
|
185
|
+
c = pico_ioc.scope(
|
|
186
|
+
modules=[src],
|
|
187
|
+
roots=[RunnerService], # only RunnerService and its deps
|
|
188
|
+
overrides={
|
|
189
|
+
"docker.DockerClient": FakeDocker(),
|
|
190
|
+
},
|
|
191
|
+
strict=True, # fail if something is missing
|
|
192
|
+
lazy=True, # instantiate on demand
|
|
193
|
+
)
|
|
194
|
+
svc = c.get(RunnerService)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
This way you don’t need to bootstrap your entire app (`controllers`, `http`, …) just to test one service.
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
## 📖 Documentation
|
|
201
|
+
|
|
202
|
+
* **🚀 New to pico-ioc? Start with the User Guide.**
|
|
203
|
+
* [**GUIDE.md**](.llm/GUIDE.md) — Learn with practical examples: testing, configuration, collection injection, and web framework integration.
|
|
204
|
+
|
|
205
|
+
* **🏗️ Want to understand the internals? See the Architecture.**
|
|
206
|
+
* [**ARCHITECTURE.md**](.llm/ARCHITECTURE.md) — A deep dive into the algorithms, lifecycle, and internal diagrams. Perfect for contributors.
|
|
207
|
+
|
|
208
|
+
* **🤔 Want to know *why* it's designed this way? Read the Decisions.**
|
|
209
|
+
* [**DECISIONS.md**](.llm/DECISIONS.md) — The history and rationale behind key technical decisions.
|
|
210
|
+
|
|
211
|
+
* **💡 Just need a quick summary?**
|
|
212
|
+
* [**OVERVIEW.md**](.llm/OVERVIEW.md) — What pico-ioc is and why you should use it.
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
## 🧪 Development
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
pip install tox
|
|
219
|
+
tox
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## 📜 Changelog
|
|
225
|
+
|
|
226
|
+
See [CHANGELOG.md](./CHANGELOG.md) for version history.
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## 📜 License
|
|
231
|
+
|
|
232
|
+
MIT — see [LICENSE](https://opensource.org/licenses/MIT)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
pico_ioc/__init__.py,sha256=Vl0nnRou3BZY1QSUOSyZ8-PFIFrz979DAzhXp0KYvIg,1014
|
|
2
|
+
pico_ioc/_state.py,sha256=XG3Q8NsRN-Di5MrWn6kLzJXg25PXp2_qAzfgytNoP-s,1021
|
|
3
|
+
pico_ioc/_version.py,sha256=zi_LaUT_OsChAtsPXbOeRpQkCohSsOyeXfavQPM0GoE,22
|
|
4
|
+
pico_ioc/api.py,sha256=PbR9_VX3ipxgv7-vKq1TyjKC75RqyDr65QUCG4i7eeI,9172
|
|
5
|
+
pico_ioc/builder.py,sha256=QPn1yC3JQYkjV08XpCAIFs95Bi0VQG5NZnSXKx4IgsI,10730
|
|
6
|
+
pico_ioc/container.py,sha256=YCrjAhChHtDcPBg1Zz0PnMbY-6x6V313nA1liPNaUaM,6306
|
|
7
|
+
pico_ioc/decorators.py,sha256=jhJxpaR9wCeBsNm1W0ziTCF3C0LGhu866-9x4IJ9-4U,3581
|
|
8
|
+
pico_ioc/interceptors.py,sha256=-ZH-AG4h_6vUgTJGbP8YESlODhOEkdC6r82GHTRrKxk,1978
|
|
9
|
+
pico_ioc/plugins.py,sha256=GP7WEMshggQ-FEjiShkcuLrSMxfueUnhbY9I8PcIyPU,1039
|
|
10
|
+
pico_ioc/policy.py,sha256=XQs8Nr7aTq0xbNPGaeFiBgJCI65r5rXK4yQdhhQuLjM,12054
|
|
11
|
+
pico_ioc/proxy.py,sha256=ZQ0g5QT32QV_v72N9oUWtQRnTh5An66GPtvaF1HtNp8,6187
|
|
12
|
+
pico_ioc/public_api.py,sha256=E3sArCoI1xxkIw7xQBvLYAWcIoVJjcq1s0kH-0qIVDE,2383
|
|
13
|
+
pico_ioc/resolver.py,sha256=qCzyjsfq59b_XEa5LNAgWzPniqoJYxyG-mXn2fzqFsk,5063
|
|
14
|
+
pico_ioc/scanner.py,sha256=VjIW6e2nsYuI1pm38RX8yIGs7SUrvuKHPN5vgTss3h4,7257
|
|
15
|
+
pico_ioc/utils.py,sha256=OyhOKnyepwGQ_uQKlQLt-fymEV1bQ6hCq4Me7h3dfco,1002
|
|
16
|
+
pico_ioc-1.3.0.dist-info/licenses/LICENSE,sha256=N1_nOvHTM6BobYnOTNXiQkroDqCEi6EzfGBv8lWtyZ0,1077
|
|
17
|
+
pico_ioc-1.3.0.dist-info/METADATA,sha256=GRIv4XBIAY8vFFXv0BVFyT4lVqryoUEQU9qF6jOlftc,10259
|
|
18
|
+
pico_ioc-1.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
19
|
+
pico_ioc-1.3.0.dist-info/top_level.txt,sha256=_7_RLu616z_dtRw16impXn4Mw8IXe2J4BeX5912m5dQ,9
|
|
20
|
+
pico_ioc-1.3.0.dist-info/RECORD,,
|
pico_ioc/typing_utils.py
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
# pico_ioc/typing_utils.py
|
|
2
|
-
|
|
3
|
-
import sys
|
|
4
|
-
import typing
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
def evaluated_hints(func, owner_cls=None) -> dict:
|
|
8
|
-
"""Return type hints; swallow any error and return {}."""
|
|
9
|
-
try:
|
|
10
|
-
module = sys.modules.get(func.__module__)
|
|
11
|
-
globalns = getattr(module, "__dict__", {})
|
|
12
|
-
localns = vars(owner_cls) if owner_cls is not None else None
|
|
13
|
-
return typing.get_type_hints(func, globalns=globalns, localns=localns, include_extras=True)
|
|
14
|
-
except Exception:
|
|
15
|
-
return {}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def resolve_annotation_to_type(ann, func, owner_cls=None):
|
|
19
|
-
"""Best-effort evaluation of a string annotation; return original on failure."""
|
|
20
|
-
if not isinstance(ann, str):
|
|
21
|
-
return ann
|
|
22
|
-
try:
|
|
23
|
-
module = sys.modules.get(func.__module__)
|
|
24
|
-
globalns = getattr(module, "__dict__", {})
|
|
25
|
-
localns = vars(owner_cls) if owner_cls is not None else None
|
|
26
|
-
return eval(ann, globalns, localns)
|
|
27
|
-
except Exception:
|
|
28
|
-
return ann
|
|
29
|
-
|