pico-ioc 1.4.0__tar.gz → 2.0.0__tar.gz

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.
Files changed (146) hide show
  1. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/.github/workflows/ci.yml +1 -1
  2. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/CHANGELOG.md +29 -0
  3. pico_ioc-2.0.0/PKG-INFO +230 -0
  4. pico_ioc-2.0.0/README.md +184 -0
  5. pico_ioc-2.0.0/docs/DECISIONS.md +156 -0
  6. pico_ioc-2.0.0/docs/README.md +96 -0
  7. pico_ioc-2.0.0/docs/adr/README.md +8 -0
  8. pico_ioc-2.0.0/docs/adr/adr-0001-async-native.md +32 -0
  9. pico_ioc-2.0.0/docs/adr/adr-0002-tree-based-configuration.md +31 -0
  10. pico_ioc-2.0.0/docs/adr/adr-0003-context-aware-scopes.md +32 -0
  11. pico_ioc-2.0.0/docs/adr/adr-0004-observability.md +32 -0
  12. pico_ioc-2.0.0/docs/adr/adr-0005-aop.md +32 -0
  13. pico_ioc-2.0.0/docs/adr/adr-0006-eager-validation.md +29 -0
  14. pico_ioc-2.0.0/docs/adr/adr-0007-event_bus.md +32 -0
  15. pico_ioc-2.0.0/docs/advanced-features/README.md +66 -0
  16. pico_ioc-2.0.0/docs/advanced-features/aop-interceptors.md +278 -0
  17. pico_ioc-2.0.0/docs/advanced-features/async-resolution.md +197 -0
  18. pico_ioc-2.0.0/docs/advanced-features/conditional-binding.md +202 -0
  19. pico_ioc-2.0.0/docs/advanced-features/event-bus.md +225 -0
  20. pico_ioc-2.0.0/docs/advanced-features/health-checks.md +137 -0
  21. pico_ioc-2.0.0/docs/api-reference/README.md +36 -0
  22. pico_ioc-2.0.0/docs/api-reference/container.md +200 -0
  23. pico_ioc-2.0.0/docs/api-reference/decorators.md +127 -0
  24. pico_ioc-2.0.0/docs/api-reference/glossary.md +74 -0
  25. pico_ioc-2.0.0/docs/api-reference/protocols.md +155 -0
  26. pico_ioc-2.0.0/docs/architecture/README.md +47 -0
  27. pico_ioc-2.0.0/docs/architecture/comparison.md +111 -0
  28. pico_ioc-2.0.0/docs/architecture/design-principles.md +83 -0
  29. pico_ioc-2.0.0/docs/architecture/internals.md +165 -0
  30. pico_ioc-2.0.0/docs/architecture.md +160 -0
  31. pico_ioc-2.0.0/docs/cookbook/README.md +41 -0
  32. pico_ioc-2.0.0/docs/cookbook/pattern-aop-feature-toggle.md +277 -0
  33. pico_ioc-2.0.0/docs/cookbook/pattern-aop-profiling.md +82 -0
  34. pico_ioc-2.0.0/docs/cookbook/pattern-aop-security.md +298 -0
  35. pico_ioc-2.0.0/docs/cookbook/pattern-aop-structured-logging.md +230 -0
  36. pico_ioc-2.0.0/docs/cookbook/pattern-cli-app.md +198 -0
  37. pico_ioc-2.0.0/docs/cookbook/pattern-cqrs.md +208 -0
  38. pico_ioc-2.0.0/docs/cookbook/pattern-dynamic-langchain.md +212 -0
  39. pico_ioc-2.0.0/docs/cookbook/pattern-hot-reload.md +234 -0
  40. pico_ioc-2.0.0/docs/cookbook/pattern-multi-tenant.md +232 -0
  41. pico_ioc-2.0.0/docs/getting-started.md +195 -0
  42. pico_ioc-2.0.0/docs/guide.md +416 -0
  43. pico_ioc-2.0.0/docs/integrations/README.md +51 -0
  44. pico_ioc-2.0.0/docs/integrations/ai-langchain.md +187 -0
  45. pico_ioc-2.0.0/docs/integrations/web-django.md +158 -0
  46. pico_ioc-2.0.0/docs/integrations/web-fastapi.md +185 -0
  47. pico_ioc-2.0.0/docs/integrations/web-flask.md +195 -0
  48. pico_ioc-2.0.0/docs/observability/README.md +54 -0
  49. pico_ioc-2.0.0/docs/observability/container-context.md +143 -0
  50. pico_ioc-2.0.0/docs/observability/exporting-graph.md +117 -0
  51. pico_ioc-2.0.0/docs/observability/observers-metrics.md +167 -0
  52. pico_ioc-2.0.0/docs/overview.md +80 -0
  53. pico_ioc-2.0.0/docs/user-guide/configuration-basic.md +200 -0
  54. pico_ioc-2.0.0/docs/user-guide/configuration-binding.md +530 -0
  55. pico_ioc-2.0.0/docs/user-guide/core-concepts.md +170 -0
  56. pico_ioc-2.0.0/docs/user-guide/qualifiers-lists.md +182 -0
  57. pico_ioc-2.0.0/docs/user-guide/testing.md +206 -0
  58. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/pyproject.toml +2 -1
  59. pico_ioc-2.0.0/src/pico_ioc/__init__.py +104 -0
  60. pico_ioc-2.0.0/src/pico_ioc/_version.py +1 -0
  61. pico_ioc-2.0.0/src/pico_ioc/aop.py +247 -0
  62. pico_ioc-2.0.0/src/pico_ioc/api.py +805 -0
  63. pico_ioc-2.0.0/src/pico_ioc/config_runtime.py +289 -0
  64. pico_ioc-2.0.0/src/pico_ioc/constants.py +10 -0
  65. pico_ioc-2.0.0/src/pico_ioc/container.py +305 -0
  66. pico_ioc-2.0.0/src/pico_ioc/event_bus.py +224 -0
  67. pico_ioc-2.0.0/src/pico_ioc/exceptions.py +66 -0
  68. pico_ioc-2.0.0/src/pico_ioc/factory.py +48 -0
  69. pico_ioc-2.0.0/src/pico_ioc/locator.py +53 -0
  70. pico_ioc-2.0.0/src/pico_ioc/scope.py +112 -0
  71. pico_ioc-2.0.0/src/pico_ioc.egg-info/PKG-INFO +230 -0
  72. pico_ioc-2.0.0/src/pico_ioc.egg-info/SOURCES.txt +84 -0
  73. pico_ioc-2.0.0/tests/test_configured.py +314 -0
  74. pico_ioc-2.0.0/tests/test_container_context.py +51 -0
  75. pico_ioc-2.0.0/tests/test_container_runtime.py +110 -0
  76. pico_ioc-2.0.0/tests/test_event_bus.py +107 -0
  77. pico_ioc-2.0.0/tests/test_pico_extends.py +368 -0
  78. pico_ioc-2.0.0/tests/test_pico_integration.py +310 -0
  79. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/tox.ini +7 -2
  80. pico_ioc-1.4.0/.llm/ARCHITECTURE.md +0 -428
  81. pico_ioc-1.4.0/.llm/DECISIONS.md +0 -185
  82. pico_ioc-1.4.0/.llm/GUIDE-CONFIGURATION-INJECTION.md +0 -129
  83. pico_ioc-1.4.0/.llm/GUIDE.md +0 -496
  84. pico_ioc-1.4.0/.llm/GUIDE_CQRS.md +0 -110
  85. pico_ioc-1.4.0/.llm/GUIDE_CREATING_PLUGINS_AND_INTERCEPTORS.md +0 -182
  86. pico_ioc-1.4.0/.llm/OVERVIEW.md +0 -167
  87. pico_ioc-1.4.0/PKG-INFO +0 -241
  88. pico_ioc-1.4.0/README.md +0 -196
  89. pico_ioc-1.4.0/src/pico_ioc/__init__.py +0 -58
  90. pico_ioc-1.4.0/src/pico_ioc/_state.py +0 -75
  91. pico_ioc-1.4.0/src/pico_ioc/_version.py +0 -1
  92. pico_ioc-1.4.0/src/pico_ioc/api.py +0 -221
  93. pico_ioc-1.4.0/src/pico_ioc/builder.py +0 -294
  94. pico_ioc-1.4.0/src/pico_ioc/config.py +0 -332
  95. pico_ioc-1.4.0/src/pico_ioc/container.py +0 -205
  96. pico_ioc-1.4.0/src/pico_ioc/decorators.py +0 -158
  97. pico_ioc-1.4.0/src/pico_ioc/interceptors.py +0 -56
  98. pico_ioc-1.4.0/src/pico_ioc/plugins.py +0 -28
  99. pico_ioc-1.4.0/src/pico_ioc/policy.py +0 -245
  100. pico_ioc-1.4.0/src/pico_ioc/proxy.py +0 -129
  101. pico_ioc-1.4.0/src/pico_ioc/public_api.py +0 -76
  102. pico_ioc-1.4.0/src/pico_ioc/resolver.py +0 -132
  103. pico_ioc-1.4.0/src/pico_ioc/scanner.py +0 -203
  104. pico_ioc-1.4.0/src/pico_ioc/scope.py +0 -46
  105. pico_ioc-1.4.0/src/pico_ioc/utils.py +0 -25
  106. pico_ioc-1.4.0/src/pico_ioc.egg-info/PKG-INFO +0 -241
  107. pico_ioc-1.4.0/src/pico_ioc.egg-info/SOURCES.txt +0 -69
  108. pico_ioc-1.4.0/tests/test_api.py +0 -269
  109. pico_ioc-1.4.0/tests/test_conditional_with_predicate.py +0 -42
  110. pico_ioc-1.4.0/tests/test_config_injection.py +0 -176
  111. pico_ioc-1.4.0/tests/test_container.py +0 -204
  112. pico_ioc-1.4.0/tests/test_core_helpers_and_errors.py +0 -86
  113. pico_ioc-1.4.0/tests/test_decorators_and_policy.py +0 -216
  114. pico_ioc-1.4.0/tests/test_decorators_unit.py +0 -138
  115. pico_ioc-1.4.0/tests/test_defaults_and_overrides.py +0 -71
  116. pico_ioc-1.4.0/tests/test_factory_policy_and_defaults.py +0 -179
  117. pico_ioc-1.4.0/tests/test_fingerprint_public.py +0 -31
  118. pico_ioc-1.4.0/tests/test_interceptors.py +0 -269
  119. pico_ioc-1.4.0/tests/test_no_overrides_needed_with_on_missing.py +0 -30
  120. pico_ioc-1.4.0/tests/test_on_missing_and_primary_mix.py +0 -29
  121. pico_ioc-1.4.0/tests/test_on_missing_blackbox.py +0 -90
  122. pico_ioc-1.4.0/tests/test_on_missing_component.py +0 -50
  123. pico_ioc-1.4.0/tests/test_on_missing_factory.py +0 -29
  124. pico_ioc-1.4.0/tests/test_pico_ioc.py +0 -280
  125. pico_ioc-1.4.0/tests/test_pico_ioc_additional.py +0 -192
  126. pico_ioc-1.4.0/tests/test_pico_ioc_discovery.py +0 -114
  127. pico_ioc-1.4.0/tests/test_policy_and_container_helpers.py +0 -106
  128. pico_ioc-1.4.0/tests/test_policy_env_activation.py +0 -33
  129. pico_ioc-1.4.0/tests/test_policy_profile_primary.py +0 -35
  130. pico_ioc-1.4.0/tests/test_proxy_unit.py +0 -188
  131. pico_ioc-1.4.0/tests/test_public_api.py +0 -220
  132. pico_ioc-1.4.0/tests/test_qualifiers_unit.py +0 -70
  133. pico_ioc-1.4.0/tests/test_resolver_unit.py +0 -121
  134. pico_ioc-1.4.0/tests/test_scanner_providers.py +0 -151
  135. pico_ioc-1.4.0/tests/test_scanner_unit.py +0 -190
  136. pico_ioc-1.4.0/tests/test_scope.py +0 -80
  137. pico_ioc-1.4.0/tests/test_scope_defaults.py +0 -69
  138. pico_ioc-1.4.0/tests/test_scope_defaults_and_policy.py +0 -38
  139. pico_ioc-1.4.0/tests/test_scope_unit.py +0 -232
  140. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/.coveragerc +0 -0
  141. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/.github/workflows/publish-to-pypi.yml +0 -0
  142. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/LICENSE +0 -0
  143. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/MANIFEST.in +0 -0
  144. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/setup.cfg +0 -0
  145. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/src/pico_ioc.egg-info/dependency_links.txt +0 -0
  146. {pico_ioc-1.4.0 → pico_ioc-2.0.0}/src/pico_ioc.egg-info/top_level.txt +0 -0
@@ -13,7 +13,7 @@ jobs:
13
13
  strategy:
14
14
  fail-fast: false
15
15
  matrix:
16
- python-version: [ "3.10", "3.11", "3.12", "3.13" ]
16
+ python-version: [ "3.10", "3.11", "3.12", "3.13", "3.14" ]
17
17
 
18
18
  steps:
19
19
  - name: Checkout
@@ -106,6 +106,35 @@ These were evaluated and **rejected** to keep pico-ioc simple, deterministic, an
106
106
 
107
107
  ---
108
108
 
109
+ ## [1.5.0] — 2025-09-17
110
+
111
+ ### 🚨 Breaking
112
+ - **Removed legacy `@interceptor` API**
113
+ The old `before/after/error` style is no longer supported.
114
+ → Interceptors must be migrated to the new `MethodInterceptor.invoke` / `ContainerInterceptor.around_*` contracts.
115
+
116
+ ### ✨ New
117
+ - **`@infrastructure` decorator**
118
+ - Enables bootstrap-time configuration via dedicated infrastructure classes.
119
+ - Provides a safe façade (`infra.query`, `infra.intercept`, `infra.mutate`) to explore and mutate the model.
120
+ - Deterministic ordering (`order=`) for infrastructure execution.
121
+ - **Around-style interceptors**
122
+ - `MethodInterceptor.invoke(ctx, call_next)` for sync/async method interception.
123
+ - `ContainerInterceptor.around_resolve` and `around_create` for lifecycle interception.
124
+ - Enforced guardrails: must call `call_next` at most once; default cap of 16 interceptors per method.
125
+
126
+ ### 🧪 Testing
127
+ - Added unit tests for `Select` DSL (tag/profile/class/method filters).
128
+ - Integration tests for interceptor chain order (sync + async).
129
+ - Negative tests for empty `where` and cap-exceeded cases.
130
+
131
+ ### 📚 Docs
132
+ - Updated **GUIDE.md** and added **GUIDE-INFRASTRUCTURE.md** with migration examples.
133
+ - Updated **DECISIONS.md** to record the removal of legacy interceptor support.
134
+ - Release notes include a migration guide for existing interceptor users.
135
+
136
+ ---
137
+
109
138
  ## [Unreleased]
110
139
  - Upcoming improvements and fixes will be listed here.
111
140
 
@@ -0,0 +1,230 @@
1
+ Metadata-Version: 2.4
2
+ Name: pico-ioc
3
+ Version: 2.0.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: Programming Language :: Python :: 3.14
40
+ Classifier: License :: OSI Approved :: MIT License
41
+ Classifier: Operating System :: OS Independent
42
+ Requires-Python: >=3.8
43
+ Description-Content-Type: text/markdown
44
+ License-File: LICENSE
45
+ Dynamic: license-file
46
+
47
+ # 📦 Pico-IoC: A Robust, Async-Native IoC Container for Python
48
+
49
+ [![PyPI](https://img.shields.io/pypi/v/pico-ioc.svg)](https://pypi.org/project/pico-ioc/)
50
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/dperezcabrera/pico-ioc)
51
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
52
+ ![CI (tox matrix)](https://github.com/dperezcabrera/pico-ioc/actions/workflows/ci.yml/badge.svg)
53
+ [![codecov](https://codecov.io/gh/dperezcabrera/pico-ioc/branch/main/graph/badge.svg)](https://codecov.io/gh/dperezcabrera/pico-ioc)
54
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-ioc&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
55
+ [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-ioc&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
56
+ [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-ioc&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
57
+
58
+ **pico-ioc** is a **robust, async-native, decorator-based IoC container for Python**.
59
+ It helps you build loosely-coupled, testable, enterprise-grade applications without manual wiring. Inspired by the Spring ecosystem, but fully Pythonic.
60
+
61
+ > ⚠️ **Requires Python 3.10+** (due to extensive use of modern `typing` features).
62
+
63
+ ---
64
+
65
+ ## ⚖️ Principles
66
+
67
+ * **Focus & Simplicity**: A declarative API for one job: managing dependencies. It avoids accidental complexity by doing one thing well.
68
+ * **Declarative & Explicit**: No magic. Behavior is deterministic, relying on explicit decorators (`@component`, `@factory`) and type hints.
69
+ * **Unified Composition Root**: The application is assembled from a single entry point (`init`) which defines a clear, predictable boundary.
70
+ * **Fail-Fast by Design**: Catches **circular dependencies** and **missing bindings** at startup, not at runtime. If the application runs, it's wired correctly.
71
+ * **Testability First**: Features like `@conditional`, profiles, and `overrides` are first-class citizens, enabling fast and isolated testing.
72
+ * **Async Native & Extensible**: Full `async`/`await` support, AOP (`@intercepted_by`), and a built-in `EventBus` are available out-of-the-box.
73
+ * **Framework Agnostic**: Zero hard dependencies (standard library only). It works with any Python application, from simple scripts to complex web servers.
74
+
75
+ ---
76
+
77
+ ## ✨ Why Pico-IoC?
78
+
79
+ `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.
80
+
81
+ `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, allowing you to build complex, loosely-coupled applications that remain simple to manage.
82
+
83
+ | Feature | Manual Wiring | With Pico-IoC |
84
+ | :--- | :--- | :--- |
85
+ | **Object Creation** | `service = Service(Repo(Config()))` | `svc = container.get(Service)` |
86
+ | **Testing** | Manual replacement or monkey-patching | `overrides={Repo: FakeRepo()}` |
87
+ | **Coupling** | High (code knows about constructors) | Low (code just asks for a type) |
88
+ | **Maintenance** | Brittle (changing a constructor breaks consumers) | Robust (changes are isolated) |
89
+ | **Learning Curve** | Ad-hoc, implicit patterns | Uniform, explicit, documented |
90
+
91
+ ---
92
+
93
+ ## 🧩 Features
94
+
95
+ ### Core
96
+
97
+ * **Zero external dependencies** — pure Python, framework-agnostic.
98
+ * **Decorator-based API** — `@component`, `@factory`, `@provides`, `@configuration`.
99
+ * **Fail-fast Bootstrap** — Detects **circular dependencies** and **missing bindings** at startup.
100
+ * **Async-Native Resolution** — Full `async`/`await` support with `container.aget()`.
101
+ * **Sophisticated Scopes** — `singleton`, `prototype`, and `ContextVar`-based scopes (e.g., `request`, `session`).
102
+ * **Typed Configuration** — Injects `dataclasses` from environment/files via `@configuration`.
103
+ * **Test-Driven** — Built-in `overrides` and `profiles` for easy mocking.
104
+
105
+ ### Advanced
106
+
107
+ * **AOP / Interceptors** — Intercept method calls with `@intercepted_by`.
108
+ * **Qualifiers** — Inject subsets of components with `Annotated[List[T], Qualifier(...)]`.
109
+ * **Async Event Bus** — Built-in `EventBus` for decoupled, event-driven architecture.
110
+ * **Conditional Registration** — `@conditional` (by profile, env var) and `@on_missing` (fallbacks).
111
+ * **Lifecycle Hooks** — `@configure` (post-init) and `@cleanup` (on shutdown).
112
+ * **Health Checks** — Built-in `@health` decorator and `container.health_check()`.
113
+ * **Serializable Proxies** — Lazy (`@lazy`) and AOP proxies are `pickle`-safe.
114
+
115
+ ---
116
+
117
+ ## 📦 Installation
118
+
119
+ ```bash
120
+ # Requires Python 3.10+
121
+ pip install pico-ioc
122
+ ````
123
+
124
+ -----
125
+
126
+ ## 🚀 Quick Start
127
+
128
+ ```python
129
+ from pico_ioc import component, init, configuration
130
+ from dataclasses import dataclass
131
+
132
+ @configuration
133
+ @dataclass
134
+ class Config:
135
+ url: str = "sqlite:///demo.db"
136
+
137
+ @component
138
+ class Repo:
139
+ def __init__(self, cfg: Config):
140
+ self.url = cfg.url
141
+ def fetch(self):
142
+ return f"fetching from {self.url}"
143
+
144
+ @component
145
+ class Service:
146
+ def __init__(self, repo: Repo):
147
+ self.repo = repo
148
+ def run(self):
149
+ return self.repo.fetch()
150
+
151
+ # Bootstrap the container by scanning modules
152
+ # We use __name__ to scan the current module
153
+ container = init(modules=[__name__])
154
+
155
+ # Resolve the service and run
156
+ svc = container.get(Service)
157
+ print(svc.run())
158
+ ```
159
+
160
+ **Output:**
161
+
162
+ ```
163
+ fetching from sqlite:///demo.db
164
+ ```
165
+
166
+ -----
167
+
168
+ ### Quick Overrides for Testing
169
+
170
+ The `init` function accepts `overrides` to replace any component for testing.
171
+
172
+ ```python
173
+ import my_app_module
174
+ from pico_ioc import init
175
+
176
+ # Define a fake repository
177
+ class FakeRepo:
178
+ def fetch(self):
179
+ return "fake-data"
180
+
181
+ # Initialize the container, overriding the real Repo
182
+ container = init(
183
+ modules=[my_app_module],
184
+ overrides={
185
+ Repo: FakeRepo() # Override by type
186
+ }
187
+ )
188
+
189
+ # The service now receives FakeRepo instead of the real one
190
+ svc = container.get(Service)
191
+ assert svc.run() == "fake-data"
192
+ ```
193
+
194
+ -----
195
+
196
+ ## 📖 Documentation
197
+
198
+ * **🚀 New to pico-ioc? Start with the User Guide.**
199
+
200
+ * [**guide.md**](.docs/guide.md) — Learn with practical examples: testing, configuration, AOP, async, and web framework integration.
201
+
202
+ * **🏗️ Want to understand the internals? See the Architecture.**
203
+
204
+ * [**architecture.md**](./docs/architecture.md) — A deep dive into the resolution algorithm, lifecycle, and internal design.
205
+
206
+ -----
207
+
208
+ ## 🧪 Development
209
+
210
+ ```bash
211
+ pip install tox
212
+ tox
213
+ ```
214
+
215
+ -----
216
+
217
+ ## 📜 Changelog
218
+
219
+ See [CHANGELOG.md](./CHANGELOG.md) for version history.
220
+
221
+ -----
222
+
223
+ ## 📜 License
224
+
225
+ MIT — see [LICENSE](https://opensource.org/licenses/MIT)
226
+
227
+ ```
228
+ ```
229
+
230
+
@@ -0,0 +1,184 @@
1
+ # 📦 Pico-IoC: A Robust, Async-Native IoC Container for Python
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/pico-ioc.svg)](https://pypi.org/project/pico-ioc/)
4
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/dperezcabrera/pico-ioc)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
6
+ ![CI (tox matrix)](https://github.com/dperezcabrera/pico-ioc/actions/workflows/ci.yml/badge.svg)
7
+ [![codecov](https://codecov.io/gh/dperezcabrera/pico-ioc/branch/main/graph/badge.svg)](https://codecov.io/gh/dperezcabrera/pico-ioc)
8
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-ioc&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
9
+ [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-ioc&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
10
+ [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-ioc&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-ioc)
11
+
12
+ **pico-ioc** is a **robust, async-native, decorator-based IoC container for Python**.
13
+ It helps you build loosely-coupled, testable, enterprise-grade applications without manual wiring. Inspired by the Spring ecosystem, but fully Pythonic.
14
+
15
+ > ⚠️ **Requires Python 3.10+** (due to extensive use of modern `typing` features).
16
+
17
+ ---
18
+
19
+ ## ⚖️ Principles
20
+
21
+ * **Focus & Simplicity**: A declarative API for one job: managing dependencies. It avoids accidental complexity by doing one thing well.
22
+ * **Declarative & Explicit**: No magic. Behavior is deterministic, relying on explicit decorators (`@component`, `@factory`) and type hints.
23
+ * **Unified Composition Root**: The application is assembled from a single entry point (`init`) which defines a clear, predictable boundary.
24
+ * **Fail-Fast by Design**: Catches **circular dependencies** and **missing bindings** at startup, not at runtime. If the application runs, it's wired correctly.
25
+ * **Testability First**: Features like `@conditional`, profiles, and `overrides` are first-class citizens, enabling fast and isolated testing.
26
+ * **Async Native & Extensible**: Full `async`/`await` support, AOP (`@intercepted_by`), and a built-in `EventBus` are available out-of-the-box.
27
+ * **Framework Agnostic**: Zero hard dependencies (standard library only). It works with any Python application, from simple scripts to complex web servers.
28
+
29
+ ---
30
+
31
+ ## ✨ Why Pico-IoC?
32
+
33
+ `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.
34
+
35
+ `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, allowing you to build complex, loosely-coupled applications that remain simple to manage.
36
+
37
+ | Feature | Manual Wiring | With Pico-IoC |
38
+ | :--- | :--- | :--- |
39
+ | **Object Creation** | `service = Service(Repo(Config()))` | `svc = container.get(Service)` |
40
+ | **Testing** | Manual replacement or monkey-patching | `overrides={Repo: FakeRepo()}` |
41
+ | **Coupling** | High (code knows about constructors) | Low (code just asks for a type) |
42
+ | **Maintenance** | Brittle (changing a constructor breaks consumers) | Robust (changes are isolated) |
43
+ | **Learning Curve** | Ad-hoc, implicit patterns | Uniform, explicit, documented |
44
+
45
+ ---
46
+
47
+ ## 🧩 Features
48
+
49
+ ### Core
50
+
51
+ * **Zero external dependencies** — pure Python, framework-agnostic.
52
+ * **Decorator-based API** — `@component`, `@factory`, `@provides`, `@configuration`.
53
+ * **Fail-fast Bootstrap** — Detects **circular dependencies** and **missing bindings** at startup.
54
+ * **Async-Native Resolution** — Full `async`/`await` support with `container.aget()`.
55
+ * **Sophisticated Scopes** — `singleton`, `prototype`, and `ContextVar`-based scopes (e.g., `request`, `session`).
56
+ * **Typed Configuration** — Injects `dataclasses` from environment/files via `@configuration`.
57
+ * **Test-Driven** — Built-in `overrides` and `profiles` for easy mocking.
58
+
59
+ ### Advanced
60
+
61
+ * **AOP / Interceptors** — Intercept method calls with `@intercepted_by`.
62
+ * **Qualifiers** — Inject subsets of components with `Annotated[List[T], Qualifier(...)]`.
63
+ * **Async Event Bus** — Built-in `EventBus` for decoupled, event-driven architecture.
64
+ * **Conditional Registration** — `@conditional` (by profile, env var) and `@on_missing` (fallbacks).
65
+ * **Lifecycle Hooks** — `@configure` (post-init) and `@cleanup` (on shutdown).
66
+ * **Health Checks** — Built-in `@health` decorator and `container.health_check()`.
67
+ * **Serializable Proxies** — Lazy (`@lazy`) and AOP proxies are `pickle`-safe.
68
+
69
+ ---
70
+
71
+ ## 📦 Installation
72
+
73
+ ```bash
74
+ # Requires Python 3.10+
75
+ pip install pico-ioc
76
+ ````
77
+
78
+ -----
79
+
80
+ ## 🚀 Quick Start
81
+
82
+ ```python
83
+ from pico_ioc import component, init, configuration
84
+ from dataclasses import dataclass
85
+
86
+ @configuration
87
+ @dataclass
88
+ class Config:
89
+ url: str = "sqlite:///demo.db"
90
+
91
+ @component
92
+ class Repo:
93
+ def __init__(self, cfg: Config):
94
+ self.url = cfg.url
95
+ def fetch(self):
96
+ return f"fetching from {self.url}"
97
+
98
+ @component
99
+ class Service:
100
+ def __init__(self, repo: Repo):
101
+ self.repo = repo
102
+ def run(self):
103
+ return self.repo.fetch()
104
+
105
+ # Bootstrap the container by scanning modules
106
+ # We use __name__ to scan the current module
107
+ container = init(modules=[__name__])
108
+
109
+ # Resolve the service and run
110
+ svc = container.get(Service)
111
+ print(svc.run())
112
+ ```
113
+
114
+ **Output:**
115
+
116
+ ```
117
+ fetching from sqlite:///demo.db
118
+ ```
119
+
120
+ -----
121
+
122
+ ### Quick Overrides for Testing
123
+
124
+ The `init` function accepts `overrides` to replace any component for testing.
125
+
126
+ ```python
127
+ import my_app_module
128
+ from pico_ioc import init
129
+
130
+ # Define a fake repository
131
+ class FakeRepo:
132
+ def fetch(self):
133
+ return "fake-data"
134
+
135
+ # Initialize the container, overriding the real Repo
136
+ container = init(
137
+ modules=[my_app_module],
138
+ overrides={
139
+ Repo: FakeRepo() # Override by type
140
+ }
141
+ )
142
+
143
+ # The service now receives FakeRepo instead of the real one
144
+ svc = container.get(Service)
145
+ assert svc.run() == "fake-data"
146
+ ```
147
+
148
+ -----
149
+
150
+ ## 📖 Documentation
151
+
152
+ * **🚀 New to pico-ioc? Start with the User Guide.**
153
+
154
+ * [**guide.md**](.docs/guide.md) — Learn with practical examples: testing, configuration, AOP, async, and web framework integration.
155
+
156
+ * **🏗️ Want to understand the internals? See the Architecture.**
157
+
158
+ * [**architecture.md**](./docs/architecture.md) — A deep dive into the resolution algorithm, lifecycle, and internal design.
159
+
160
+ -----
161
+
162
+ ## 🧪 Development
163
+
164
+ ```bash
165
+ pip install tox
166
+ tox
167
+ ```
168
+
169
+ -----
170
+
171
+ ## 📜 Changelog
172
+
173
+ See [CHANGELOG.md](./CHANGELOG.md) for version history.
174
+
175
+ -----
176
+
177
+ ## 📜 License
178
+
179
+ MIT — see [LICENSE](https://opensource.org/licenses/MIT)
180
+
181
+ ```
182
+ ```
183
+
184
+
@@ -0,0 +1,156 @@
1
+ # DECISIONS.md — pico-ioc
2
+
3
+ This document records **technical and architectural decisions** for pico-ioc.
4
+ Each entry includes a rationale and implications. If a decision is later changed, mark it **[REVOKED]** and link to the replacement.
5
+
6
+ ---
7
+
8
+ ## ✅ Current Decisions (Reflecting v2 Architecture)
9
+
10
+ ### 1) Minimum Python version: **3.10**
11
+ **Decision**: Require Python **3.10+**.
12
+ **Rationale**: `typing.Annotated` and improved `get_type_hints` are crucial for qualifiers, list injection, and clean internal implementation.
13
+ **Implications**: Users must use Python 3.10 or newer. CI/CD targets 3.10+.
14
+
15
+ ---
16
+
17
+ ### 2) Keys: **Typed keys preferred**
18
+ **Decision**: Primarily use class/type keys (e.g., `UserService`) for registration and resolution. String keys are supported but discouraged.
19
+ **Rationale**: Enhances type safety, IDE support, and reduces potential collisions.
20
+ **Implications**: Documentation emphasizes type-based injection. String keys remain for specific cases (e.g., configuration values, legacy integration).
21
+
22
+ ---
23
+
24
+ ### 3) Default Lifecycle: **Singleton per container**
25
+ **Decision**: The default scope for components (`@component`) is `singleton`. One instance is created per container and cached.
26
+ **Rationale**: Simple, fast, and matches common use cases for services and clients.
27
+ **Implications**: Users must explicitly use `@scope("prototype")` or other scope decorators for different lifecycles.
28
+
29
+ ---
30
+
31
+ ### 4) Fail-Fast Bootstrap: **Eager Validation**
32
+ **Decision**: Perform **eager validation** of component dependencies during `init()`. Check if a provider exists for every required dependency (excluding `@lazy` components by default).
33
+ **Rationale**: Surface wiring errors (missing providers) immediately at startup, enhancing reliability over runtime failures.
34
+ **Implications**: Increases startup time slightly. Potential `ProviderNotFoundError` for dependencies only used by `@lazy` components may be deferred until first access. *(See ADR-006)*
35
+
36
+ ---
37
+
38
+ ### 5) Qualifiers & Collection Injection: **First-class via `Annotated`**
39
+ **Decision**: Support `Qualifier` tags via `@qualifier(...)` and inject filtered lists using `typing.Annotated[List[Type], Qualifier(...)]`.
40
+ **Rationale**: Provides a standard, type-safe mechanism for managing multiple implementations of an interface without custom registries.
41
+ **Implications**: Requires Python 3.9+ for `Annotated`. Preserves registration order in injected lists.
42
+
43
+ ---
44
+
45
+ ### 6) Overrides in `init(...)`
46
+ **Decision**: Allow replacing components at bootstrap via `init(..., overrides={...})`.
47
+ **Rationale**: Simplifies unit testing and mocking without needing complex setup or separate modules.
48
+ **Implications**: Overrides are applied *before* any instances are created. Supports overriding with instances, callables (providers), or `(callable, lazy_bool)`.
49
+
50
+ ---
51
+
52
+ ### 7) Conditional Providers: **Profiles, Env Vars, Predicates**
53
+ **Decision**: Support conditional registration using `@conditional(profiles=..., require_env=..., predicate=...)`.
54
+ **Rationale**: Enables environment-specific configurations (prod vs. test vs. dev), feature flags, and optional integrations declaratively.
55
+ **Implications**: Components might not be registered if conditions aren't met, potentially leading to `ProviderNotFoundError` if depended upon. Bootstrap error occurs if a required *eager* dependency is inactive. *(See ADR-006)*
56
+
57
+ ---
58
+
59
+ ### 8) Deterministic Provider Selection: **Prefer `@primary`**
60
+ **Decision**: When multiple providers implement the same key (type), select the one marked `@primary`. If ambiguity remains, raise `InvalidBindingError`. `@on_missing` acts as a fallback if no primary or direct provider is found.
61
+ **Rationale**: Provides explicit control over default implementations, making wiring predictable. Avoids reliance on implicit scan order.
62
+ **Implications**: Developers must use `@primary` (or qualifiers/overrides) to resolve ambiguity between multiple implementations.
63
+
64
+ ---
65
+
66
+ ### 9) Concurrency & Safety: **Immutable Container, Context-Aware Scopes**
67
+ **Decision**: The container's configuration (providers, metadata) is **immutable** after `init()`. Caches (`singleton`, `request`, etc.) are isolated and thread/task-safe using appropriate locking or `contextvars`.
68
+ **Rationale**: Ensure safe usage in multi-threaded and asynchronous applications without external locking.
69
+ **Implications**: Components themselves must be thread/task-safe if used concurrently across scopes. `contextvars` require proper context propagation in complex threading/async scenarios.
70
+
71
+ ---
72
+
73
+ ### 10) Configuration: **Dual System (`@configuration` and `@configured`)**
74
+ **Decision**: Support two configuration injection mechanisms:
75
+ 1. **`@configuration`**: For simple, flat key-value settings populated from ordered `ConfigSource`s (`EnvSource`, `FileSource`).
76
+ 2. **`@configured`**: For complex, nested configuration trees populated from ordered `TreeSource`s (`YamlTreeSource`, `JsonTreeSource`), mapping directly to `dataclass` graphs.
77
+ **Rationale**: `@configuration` handles simple cases easily. `@configured` provides a powerful, type-safe solution for modern, structured configuration practices, inspired by frameworks like Spring Boot.
78
+ **Implications**: Developers choose the system appropriate for their needs. `@configured` is generally recommended for new, complex applications. *(See ADR-002)*
79
+
80
+ ---
81
+
82
+ ### 11) AOP: **Explicit Proxy via `@intercepted_by`**
83
+ **Decision**: Implement AOP using **method interception** via a dynamic **`UnifiedComponentProxy`**. Interceptors are defined using the `MethodInterceptor` protocol and applied explicitly with `@intercepted_by(...)`. Rejected alternatives involving metaclass programming or bytecode manipulation.
84
+ **Rationale**: Provides powerful AOP capabilities using standard Python features (decorators, proxies). Explicit application (`@intercepted_by`) is clearer and more controllable than global or rule-based interception. Avoids the complexity and potential fragility of metaprogramming/bytecode.
85
+ **Implications**: Adds a proxy layer (minor performance overhead, potential debug complexity). Developers must explicitly decorate methods to apply aspects. *(See ADR-005)*
86
+
87
+ ---
88
+
89
+ ### 12) Async Support: **Native Integration**
90
+ **Decision**: Integrate `asyncio` support deeply throughout the container. Provide `container.aget()`, support `async def` providers, `__ainit__`, async lifecycle hooks (`@configure`, `@cleanup`), async AOP, and an async Event Bus.
91
+ **Rationale**: Essential for modern I/O-bound Python applications. Avoids blocking the event loop during component resolution or lifecycle management.
92
+ **Implications**: Dual API (`get`/`aget`). Developers must use `aget` and `cleanup_all_async` in async contexts. *(See ADR-001)*
93
+
94
+ ---
95
+
96
+ ### 13) Context-Aware Scopes: **`contextvars`-Based**
97
+ **Decision**: Implement dynamic scopes (`request`, `session`, custom) using `contextvars`. Provide `ScopeProtocol`, `ContextVarScope`, `ScopeManager`, `ScopedCaches` (with LRU), and `with container.scope(...)`.
98
+ **Rationale**: `contextvars` provide a robust mechanism for managing context-local state in both threaded and async environments. Enables per-request or other contextual lifecycles.
99
+ **Implications**: Requires explicit scope management (e.g., via middleware) using `container.scope()` or `activate/deactivate`. Potential complexity with context propagation in advanced scenarios. *(See ADR-003)*
100
+
101
+ ---
102
+
103
+ ### 14) Observability: **Built-in Features**
104
+ **Decision**: Include features for monitoring and debugging: `container_id`, `container context` (`as_current`), `container.stats()`, `ContainerObserver` protocol, and `container.export_graph()`.
105
+ **Rationale**: Essential for understanding and managing complex applications, especially multi-container setups. Makes the container less of a "black box".
106
+ **Implications**: Slight overhead for context tracking. `ContainerObserver` and `export_graph` are optional features. *(See ADR-004)*
107
+
108
+ ---
109
+
110
+ ### 15) Event Bus: **Integrated Async Pub/Sub**
111
+ **Decision**: Provide a built-in, asynchronous `EventBus` component with `@subscribe` decorator and `AutoSubscriberMixin`.
112
+ **Rationale**: Facilitates decoupled, event-driven architectures directly within the container ecosystem. Provides a standard mechanism over ad-hoc solutions.
113
+ **Implications**: Adds functionality beyond core DI. Requires registering the `pico_ioc.event_bus` module. Bus is in-process, not a distributed queue replacement. *(See ADR-007)*
114
+
115
+ ---
116
+
117
+ ## ❌ Won’t-Do Decisions (Confirmed for v2)
118
+
119
+ ### A) Alternative scopes (request/session) beyond `contextvars`
120
+ **Decision**: Stick to `contextvars` for built-in dynamic scopes. Do not add framework-specific scope implementations (e.g., Flask `g`, Django `request`) directly into the core library.
121
+ **Rationale**: Keep `pico-ioc` framework-agnostic. `contextvars` provide a universal mechanism. Framework integrations can bridge framework contexts to `pico-ioc` scopes if needed.
122
+ **Implications**: Integration recipes (like for Flask/FastAPI) show how to manage `contextvars`-based scopes using middleware or request hooks.
123
+
124
+ ### B) Hot reload / dynamic re-scan
125
+ **Decision**: The container configuration remains **immutable** after `init()`. No built-in support for watching files and automatically reloading the container.
126
+ **Rationale**: Conflicts with fail-fast validation and immutability principles. Adds significant complexity and potential for inconsistent states. Hot-reload is better handled by development server tools (like `uvicorn --reload` or the `watchdog` pattern shown in the cookbook).
127
+ **Implications**: Developers use external tools or patterns (like the cookbook example) for development-time hot-reloading.
128
+
129
+ ---
130
+
131
+ ## 🗃️ Deprecated / Revoked
132
+
133
+ * **[REVOKED] Decision #11 (Old)**: Infrastructure-based Interceptor API via `@infrastructure`.
134
+ * **Reason:** Replaced by the simpler, more explicit `@intercepted_by` AOP mechanism using `UnifiedComponentProxy` (ADR-005). The `@infrastructure` role might be repurposed or removed in future versions.
135
+
136
+ ---
137
+
138
+ ## 📜 Changelog of Decisions (v2 Focus)
139
+
140
+ * **v2.0**: Minimum Python **3.10** adopted.
141
+ * **v2.0**: **Native Async Support** added (`aget`, `__ainit__`, async hooks/AOP/EventBus - ADR-001).
142
+ * **v2.0**: **Tree-Based Configuration Binding** added (`@configured`, `TreeSource`, `ConfigResolver`, `ObjectGraphBuilder` - ADR-002).
143
+ * **v2.0**: **Context-Aware Scopes** implemented (`@scope("request")`, `contextvars`, `container.scope()` - ADR-003).
144
+ * **v2.0**: **Observability Features** added (`container_id`, `as_current`, `stats`, `ContainerObserver`, `export_graph` - ADR-004).
145
+ * **v2.0**: **AOP Implementation** finalized using `@intercepted_by` and `UnifiedComponentProxy` (ADR-005). Explicit decision against metaprogramming. Old `@infrastructure`-based interceptor plan revoked.
146
+ * **v2.0**: **Eager Startup Validation** confirmed as core principle (ADR-006).
147
+ * **v2.0**: **Built-in Async Event Bus** added (ADR-007).
148
+ * **v2.0**: **`@primary`** confirmed as the primary mechanism for resolving ambiguity (Decision #8 refined).
149
+ * **v2.0**: **Configuration Injection** clarified as a dual system (`@configuration` + `@configured`) (Decision #10 updated).
150
+
151
+ ---
152
+
153
+ **Summary**: `pico-ioc` v2 prioritizes **robustness, async-native operation, powerful configuration, observability, and explicit AOP** using standard Python features. It remains deterministic and aims to fail fast at startup.
154
+ ```
155
+
156
+ How does this look? It incorporates the key decisions from the ADRs and clarifies the v2 architecture.