pico-ioc 1.4.0__py3-none-any.whl → 2.0.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.
@@ -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,17 @@
1
+ pico_ioc/__init__.py,sha256=sfAtaueMwYKztdJOmU_0-lkMQ_1Lr196KOZE__mzQXI,2373
2
+ pico_ioc/_version.py,sha256=hwOJuFUEKtsgiOt4l6op9s-hviovM6TK1uCdtRNWY4E,22
3
+ pico_ioc/aop.py,sha256=YBvwPwSw8lbXxr_zGbJ8SyxSMh_1kwTFmaB9ezKIDrM,11602
4
+ pico_ioc/api.py,sha256=iu61f3RAqGZ6W4B8JtF3CVkGVukF708O41rx46Q29Ro,32685
5
+ pico_ioc/config_runtime.py,sha256=z1cHDb5PbM8PMLYRFf5c2dmze8V22xwEzpWcBhtmMpA,11950
6
+ pico_ioc/constants.py,sha256=AhIt0ieDZ9Turxb_YbNzj11wUbBbzjKfWh1BDlSx2Nw,183
7
+ pico_ioc/container.py,sha256=xNO1boVXuiMxjJGk8uZdFpLPGugQn1Hyvk1OO0ZcUBk,12509
8
+ pico_ioc/event_bus.py,sha256=0u-uAvniNWk22r3IRqONyeR74SH4Ekc6zb2ZlIJ4HFE,8348
9
+ pico_ioc/exceptions.py,sha256=IwhK7q28_cubG6yiD2mlBYwYPl5I4JAPyt4nss7WFJw,2254
10
+ pico_ioc/factory.py,sha256=Q3aLwZ-MWbXKjm8unr871vlWSeVUDmzFQZ1mXzPkY5I,1557
11
+ pico_ioc/locator.py,sha256=PBxZYO_xCOxG7aJZ0adDtINrJass_ZDNYmPD2O_oNqM,2401
12
+ pico_ioc/scope.py,sha256=BZVEklggnpiKBlE07Ec9NNhJQ6Wg5cnS7IYRAiDB3-E,4473
13
+ pico_ioc-2.0.0.dist-info/licenses/LICENSE,sha256=N1_nOvHTM6BobYnOTNXiQkroDqCEi6EzfGBv8lWtyZ0,1077
14
+ pico_ioc-2.0.0.dist-info/METADATA,sha256=ubMhg9j-hhpzo3Ok5ySrfRMudhgnJol-7SIDKgCbNsE,9624
15
+ pico_ioc-2.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
16
+ pico_ioc-2.0.0.dist-info/top_level.txt,sha256=_7_RLu616z_dtRw16impXn4Mw8IXe2J4BeX5912m5dQ,9
17
+ pico_ioc-2.0.0.dist-info/RECORD,,
pico_ioc/_state.py DELETED
@@ -1,75 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from dataclasses import dataclass
4
- from threading import RLock
5
- from contextvars import ContextVar
6
- from contextlib import contextmanager
7
- from typing import Optional, TYPE_CHECKING
8
-
9
- # Type-only import to avoid cycles
10
- if TYPE_CHECKING:
11
- from .container import PicoContainer
12
-
13
-
14
- # ---- Task/process context for the active container ----
15
-
16
- @dataclass(frozen=True, slots=True)
17
- class ContainerContext:
18
- """Immutable snapshot for the active container state."""
19
- container: "PicoContainer"
20
- fingerprint: tuple
21
- root_name: Optional[str]
22
-
23
-
24
- # Process-wide fallback (for non-async code) guarded by a lock
25
- _lock = RLock()
26
- _current_context: Optional[ContainerContext] = None
27
-
28
- # Task-local context (for async isolation)
29
- _ctxvar: ContextVar[Optional[ContainerContext]] = ContextVar("pico_ioc_ctx", default=None)
30
-
31
-
32
- def get_context() -> Optional[ContainerContext]:
33
- """Return the current context (task-local first, then process-global)."""
34
- ctx = _ctxvar.get()
35
- return ctx if ctx is not None else _current_context
36
-
37
-
38
- def set_context(ctx: Optional[ContainerContext]) -> None:
39
- """Atomically set both task-local and process-global context."""
40
- with _lock:
41
- _ctxvar.set(ctx)
42
- globals()["_current_context"] = ctx
43
-
44
-
45
- # Optional compatibility helpers (only used by legacy API paths)
46
- def get_fingerprint() -> Optional[tuple]:
47
- ctx = get_context()
48
- return ctx.fingerprint if ctx else None
49
-
50
-
51
- def set_fingerprint(fp: Optional[tuple]) -> None:
52
- """Compatibility shim: setting None clears the active context."""
53
- if fp is None:
54
- set_context(None)
55
- return
56
- ctx = get_context()
57
- if ctx is not None:
58
- set_context(ContainerContext(container=ctx.container, fingerprint=fp, root_name=ctx.root_name))
59
-
60
-
61
- # ---- Scan/resolve guards (kept as-is) ----
62
-
63
- _scanning: ContextVar[bool] = ContextVar("pico_scanning", default=False)
64
- _resolving: ContextVar[bool] = ContextVar("pico_resolving", default=False)
65
-
66
-
67
- @contextmanager
68
- def scanning_flag():
69
- """Mark scanning=True within the block."""
70
- tok = _scanning.set(True)
71
- try:
72
- yield
73
- finally:
74
- _scanning.reset(tok)
75
-
pico_ioc/builder.py DELETED
@@ -1,294 +0,0 @@
1
- # src/pico_ioc/builder.py
2
- from __future__ import annotations
3
-
4
- import inspect as _inspect
5
- import logging
6
- import os
7
- from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
8
- from typing import get_origin, get_args, Annotated
9
-
10
- from .interceptors import MethodInterceptor, ContainerInterceptor
11
- from .container import PicoContainer, _is_compatible
12
- from .policy import apply_policy, _conditional_active
13
- from .plugins import PicoPlugin, run_plugin_hook
14
- from .scanner import scan_and_configure
15
- from .resolver import Resolver, _get_hints
16
- from . import _state
17
- from .config import ConfigRegistry
18
-
19
- class PicoContainerBuilder:
20
- """Configures and builds a PicoContainer. Does not touch global context."""
21
-
22
- def __init__(self):
23
- self._scan_plan: List[Tuple[Any, Optional[Callable[[str], bool]], Tuple[PicoPlugin, ...]]] = []
24
- self._overrides: Dict[Any, Any] = {}
25
- self._profiles: Optional[List[str]] = None
26
- self._plugins: Tuple[PicoPlugin, ...] = ()
27
- self._include_tags: Optional[set[str]] = None
28
- self._exclude_tags: Optional[set[str]] = None
29
- self._roots: Iterable[type] = ()
30
- self._providers: Dict[Any, Dict] = {}
31
- self._interceptor_decls: List[Tuple[Any, dict]] = []
32
- self._eager: bool = True
33
- self._config_registry: ConfigRegistry | None = None
34
-
35
- # -------- fluent config --------
36
-
37
- def with_config(self, registry: ConfigRegistry) -> "PicoContainerBuilder":
38
- self._config_registry = registry
39
- return self
40
-
41
- def with_plugins(self, plugins: Tuple[PicoPlugin, ...]) -> "PicoContainerBuilder":
42
- self._plugins = plugins or ()
43
- return self
44
-
45
- def with_profiles(self, profiles: Optional[List[str]]) -> "PicoContainerBuilder":
46
- self._profiles = profiles
47
- return self
48
-
49
- def add_scan_package(self, package: Any, exclude: Optional[Callable[[str], bool]] = None) -> "PicoContainerBuilder":
50
- self._scan_plan.append((package, exclude, self._plugins))
51
- return self
52
-
53
- def with_overrides(self, overrides: Optional[Dict[Any, Any]]) -> "PicoContainerBuilder":
54
- self._overrides = overrides or {}
55
- return self
56
-
57
- def with_tag_filters(self, include: Optional[set[str]], exclude: Optional[set[str]]) -> "PicoContainerBuilder":
58
- self._include_tags = include
59
- self._exclude_tags = exclude
60
- return self
61
-
62
- def with_roots(self, roots: Iterable[type]) -> "PicoContainerBuilder":
63
- self._roots = roots or ()
64
- return self
65
-
66
- def with_eager(self, eager: bool) -> "PicoContainerBuilder":
67
- self._eager = bool(eager)
68
- return self
69
-
70
- # -------- build --------
71
-
72
- def build(self) -> PicoContainer:
73
- """Build and return a fully configured container."""
74
- requested_profiles = _resolve_profiles(self._profiles)
75
-
76
- container = PicoContainer(providers=self._providers)
77
- container._active_profiles = tuple(requested_profiles)
78
- setattr(container, "_config_registry", self._config_registry)
79
-
80
- for pkg, exclude, scan_plugins in self._scan_plan:
81
- with _state.scanning_flag():
82
- c, f, decls = scan_and_configure(pkg, container, exclude=exclude, plugins=scan_plugins)
83
- logging.info("Scanned '%s' (components: %d, factories: %d)", getattr(pkg, "__name__", pkg), c, f)
84
- self._interceptor_decls.extend(decls)
85
-
86
- _activate_and_build_interceptors(
87
- container=container,
88
- interceptor_decls=self._interceptor_decls,
89
- profiles=requested_profiles,
90
- )
91
-
92
- binder = container.binder()
93
-
94
- if self._overrides:
95
- _apply_overrides(container, self._overrides)
96
-
97
- run_plugin_hook(self._plugins, "after_bind", container, binder)
98
- run_plugin_hook(self._plugins, "before_eager", container, binder)
99
-
100
- apply_policy(container, profiles=requested_profiles)
101
- _filter_by_tags(container, self._include_tags, self._exclude_tags)
102
-
103
- if self._roots:
104
- _restrict_to_subgraph(container, self._roots, self._overrides)
105
-
106
- run_plugin_hook(self._plugins, "after_ready", container, binder)
107
-
108
- if self._eager:
109
- container.eager_instantiate_all()
110
- logging.info("Container configured and ready.")
111
- return container
112
-
113
-
114
- # ---------------- helpers ----------------
115
-
116
- def _resolve_profiles(profiles: Optional[List[str]]) -> List[str]:
117
- if profiles is not None:
118
- return list(profiles)
119
- env_val = os.getenv("PICO_PROFILE", "")
120
- return [p.strip() for p in env_val.split(",") if p.strip()]
121
-
122
-
123
- def _as_provider(val):
124
- if isinstance(val, tuple) and len(val) == 2 and callable(val[0]) and isinstance(val[1], bool):
125
- return val[0], val[1]
126
- if callable(val):
127
- return val, False
128
- return (lambda v=val: v), False
129
-
130
-
131
- def _apply_overrides(container: PicoContainer, overrides: Dict[Any, Any]) -> None:
132
- for key, val in overrides.items():
133
- provider, lazy = _as_provider(val)
134
- container.bind(key, provider, lazy=lazy)
135
-
136
-
137
- def _filter_by_tags(container: PicoContainer, include_tags: Optional[set[str]], exclude_tags: Optional[set[str]]) -> None:
138
- if not include_tags and not exclude_tags:
139
- return
140
-
141
- def _tag_ok(meta: dict) -> bool:
142
- tags = set(meta.get("tags", ()))
143
- if include_tags and not tags.intersection(include_tags):
144
- return False
145
- if exclude_tags and tags.intersection(exclude_tags):
146
- return False
147
- return True
148
-
149
- container._providers = {k: v for k, v in container._providers.items() if _tag_ok(v)}
150
-
151
-
152
- def _compute_allowed_subgraph(container: PicoContainer, roots: Iterable[type]) -> set:
153
- allowed: set[Any] = set(roots)
154
- stack = list(roots or ())
155
-
156
- def _add_impls_for_base(base_t):
157
- for prov_key, meta in container._providers.items():
158
- cls = prov_key if isinstance(prov_key, type) else None
159
- if cls is not None and _is_compatible(cls, base_t):
160
- if prov_key not in allowed:
161
- allowed.add(prov_key)
162
- stack.append(prov_key)
163
-
164
- while stack:
165
- k = stack.pop()
166
- allowed.add(k)
167
- if isinstance(k, type):
168
- _add_impls_for_base(k)
169
-
170
- cls = k if isinstance(k, type) else None
171
- if cls is None or not container.has(k):
172
- continue
173
-
174
- try:
175
- sig = _inspect.signature(cls.__init__)
176
- hints = _get_hints(cls.__init__, owner_cls=cls)
177
- except Exception:
178
- continue
179
-
180
- for pname, param in sig.parameters.items():
181
- if pname == "self":
182
- continue
183
- ann = hints.get(pname, param.annotation)
184
- origin = get_origin(ann) or ann
185
- if origin in (list, tuple):
186
- inner = (get_args(ann) or (object,))[0]
187
- if get_origin(inner) is Annotated:
188
- inner = (get_args(inner) or (object,))[0]
189
- if isinstance(inner, type):
190
- if inner not in allowed:
191
- stack.append(inner)
192
- continue
193
- if isinstance(ann, type) and ann not in allowed:
194
- stack.append(ann)
195
- elif container.has(pname) and pname not in allowed:
196
- stack.append(pname)
197
- return allowed
198
-
199
-
200
- def _restrict_to_subgraph(container: PicoContainer, roots: Iterable[type], overrides: Optional[Dict[Any, Any]]) -> None:
201
- allowed = _compute_allowed_subgraph(container, roots)
202
- keep_keys: set[Any] = allowed | (set(overrides.keys()) if overrides else set())
203
- container._providers = {k: v for k, v in container._providers.items() if k in keep_keys}
204
-
205
-
206
- def _activate_and_build_interceptors(
207
- *, container: PicoContainer, interceptor_decls: List[Tuple[Any, dict]], profiles: List[str],
208
- ) -> None:
209
- resolver = Resolver(container)
210
- active: List[Tuple[int, str, str, Any]] = []
211
- activated_method_names: List[str] = []
212
- activated_container_names: List[str] = []
213
- skipped_debug: List[str] = []
214
-
215
- def _interceptor_meta_active(meta: dict) -> bool:
216
- profs = tuple(meta.get("profiles", ())) or ()
217
- if profs and (not profiles or not any(p in profs for p in profiles)):
218
- return False
219
- req_env = tuple(meta.get("require_env", ())) or ()
220
- if req_env and not all(os.getenv(k) not in (None, "") for k in req_env):
221
- return False
222
- pred = meta.get("predicate", None)
223
- if callable(pred):
224
- try:
225
- if not bool(pred()):
226
- return False
227
- except Exception:
228
- logging.exception("Interceptor predicate failed; skipping")
229
- return False
230
- return True
231
-
232
- def _looks_like_container_interceptor(inst: Any) -> bool:
233
- return all(
234
- hasattr(inst, m) for m in ("on_resolve", "on_before_create", "on_after_create", "on_exception")
235
- )
236
-
237
- for raw_obj, meta in interceptor_decls:
238
- owner_cls, obj = (raw_obj[0], raw_obj[1]) if isinstance(raw_obj, tuple) and len(raw_obj) == 2 else (None, raw_obj)
239
- qn = getattr(obj, "__qualname__", repr(obj))
240
-
241
- if not _conditional_active(obj, profiles=profiles) or not _interceptor_meta_active(meta):
242
- skipped_debug.append(f"skip:{qn}")
243
- continue
244
-
245
- try:
246
- if isinstance(obj, type):
247
- inst = resolver.create_instance(obj)
248
- elif owner_cls is not None:
249
- owner_inst = resolver.create_instance(owner_cls)
250
- bound = obj.__get__(owner_inst, owner_cls)
251
- kwargs = resolver.kwargs_for_callable(bound, owner_cls=owner_cls)
252
- inst = bound(**kwargs)
253
- else:
254
- kwargs = resolver.kwargs_for_callable(obj, owner_cls=None)
255
- inst = obj(**kwargs)
256
- except Exception:
257
- logging.exception("Failed to construct interceptor %r", obj)
258
- continue
259
-
260
- kind = meta.get("kind", "method")
261
- if kind == "method" and not callable(inst):
262
- logging.error("Interceptor %s is not valid for kind %s; skipping", qn, kind)
263
- continue
264
- if kind == "container" and not _looks_like_container_interceptor(inst):
265
- logging.error("Container interceptor %s lacks required methods; skipping", qn)
266
- continue
267
-
268
- order = int(meta.get("order", 0))
269
- active.append((order, qn, kind, inst))
270
-
271
- active.sort(key=lambda t: (t[0], t[1]))
272
-
273
- for _order, _qn, kind, inst in active:
274
- if kind == "container":
275
- container.add_container_interceptor(inst) # type: ignore[arg-type]
276
- activated_container_names.append(_qn)
277
- else:
278
- container.add_method_interceptor(inst) # type: ignore[arg-type]
279
- activated_method_names.append(_qn)
280
-
281
- if activated_method_names or activated_container_names:
282
- logging.info(
283
- "Interceptors activated: method=%d, container=%d",
284
- len(activated_method_names),
285
- len(activated_container_names),
286
- )
287
- logging.debug(
288
- "Activated method=%s; Activated container=%s",
289
- ", ".join(activated_method_names) or "-",
290
- ", ".join(activated_container_names) or "-",
291
- )
292
- if skipped_debug:
293
- logging.debug("Skipped interceptors: %s", ", ".join(skipped_debug))
294
-