pico-ioc 1.5.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.
pico_ioc/exceptions.py ADDED
@@ -0,0 +1,66 @@
1
+ # src/pico_ioc/exceptions.py
2
+ from typing import Any, Iterable
3
+
4
+ class PicoError(Exception):
5
+ pass
6
+
7
+ class ProviderNotFoundError(PicoError):
8
+ def __init__(self, key: Any):
9
+ super().__init__(f"Provider not found for key: {getattr(key, '__name__', key)}")
10
+ self.key = key
11
+
12
+ class CircularDependencyError(PicoError):
13
+ def __init__(self, chain: Iterable[Any], current: Any):
14
+ chain_str = " -> ".join(getattr(k, "__name__", str(k)) for k in chain)
15
+ cur_str = getattr(current, "__name__", str(current))
16
+ super().__init__(f"Circular dependency detected: {chain_str} -> {cur_str}")
17
+ self.chain = tuple(chain)
18
+ self.current = current
19
+
20
+ class ComponentCreationError(PicoError):
21
+ def __init__(self, key: Any, cause: Exception):
22
+ k = getattr(key, "__name__", key)
23
+ super().__init__(f"Failed to create component for key: {k}; cause: {cause.__class__.__name__}: {cause}")
24
+ self.key = key
25
+ self.cause = cause
26
+
27
+ class ScopeError(PicoError):
28
+ def __init__(self, msg: str):
29
+ super().__init__(msg)
30
+
31
+ class ConfigurationError(PicoError):
32
+ def __init__(self, msg: str):
33
+ super().__init__(msg)
34
+
35
+ class SerializationError(PicoError):
36
+ def __init__(self, msg: str):
37
+ super().__init__(msg)
38
+
39
+ class ValidationError(PicoError):
40
+ def __init__(self, msg: str):
41
+ super().__init__(msg)
42
+
43
+ class InvalidBindingError(ValidationError):
44
+ def __init__(self, errors: list[str]):
45
+ super().__init__("Invalid bindings:\n" + "\n".join(f"- {e}" for e in errors))
46
+ self.errors = errors
47
+
48
+ class EventBusError(PicoError):
49
+ def __init__(self, msg: str):
50
+ super().__init__(msg)
51
+
52
+ class EventBusClosedError(EventBusError):
53
+ def __init__(self):
54
+ super().__init__("EventBus is closed")
55
+
56
+ class EventBusQueueFullError(EventBusError):
57
+ def __init__(self):
58
+ super().__init__("Event queue is full")
59
+
60
+ class EventBusHandlerError(EventBusError):
61
+ def __init__(self, event_name: str, handler_name: str, cause: Exception):
62
+ super().__init__(f"Handler {handler_name} failed for event {event_name}: {cause.__class__.__name__}: {cause}")
63
+ self.event_name = event_name
64
+ self.handler_name = handler_name
65
+ self.cause = cause
66
+
pico_ioc/factory.py ADDED
@@ -0,0 +1,48 @@
1
+ # src/pico_ioc/factory.py
2
+ from dataclasses import dataclass
3
+ from typing import Any, Callable, Dict, Optional, Set, Tuple, Union
4
+ from .exceptions import ProviderNotFoundError
5
+
6
+ KeyT = Union[str, type]
7
+ Provider = Callable[[], Any]
8
+
9
+ @dataclass(frozen=True)
10
+ class ProviderMetadata:
11
+ key: KeyT
12
+ provided_type: Optional[type]
13
+ concrete_class: Optional[type]
14
+ factory_class: Optional[type]
15
+ factory_method: Optional[str]
16
+ qualifiers: Set[str]
17
+ primary: bool
18
+ lazy: bool
19
+ infra: Optional[str]
20
+ pico_name: Optional[Any]
21
+ override: bool = False
22
+ scope: str = "singleton"
23
+
24
+ class ComponentFactory:
25
+ def __init__(self) -> None:
26
+ self._providers: Dict[KeyT, Provider] = {}
27
+ def bind(self, key: KeyT, provider: Provider) -> None:
28
+ self._providers[key] = provider
29
+ def has(self, key: KeyT) -> bool:
30
+ return key in self._providers
31
+ def get(self, key: KeyT) -> Provider:
32
+ if key not in self._providers:
33
+ raise ProviderNotFoundError(key)
34
+ return self._providers[key]
35
+
36
+ class DeferredProvider:
37
+ def __init__(self, builder: Callable[[Any, Any], Any]) -> None:
38
+ self._builder = builder
39
+ self._pico: Any = None
40
+ self._locator: Any = None
41
+ def attach(self, pico, locator) -> None:
42
+ self._pico = pico
43
+ self._locator = locator
44
+ def __call__(self) -> Any:
45
+ if self._pico is None or self._locator is None:
46
+ raise RuntimeError("DeferredProvider must be attached before use")
47
+ return self._builder(self._pico, self._locator)
48
+
pico_ioc/locator.py ADDED
@@ -0,0 +1,53 @@
1
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union
2
+ from .factory import ProviderMetadata
3
+
4
+ KeyT = Union[str, type]
5
+
6
+ class ComponentLocator:
7
+ def __init__(self, metadata: Dict[KeyT, ProviderMetadata], indexes: Dict[str, Dict[Any, List[KeyT]]]) -> None:
8
+ self._metadata = metadata
9
+ self._indexes = indexes
10
+ self._candidates: Optional[Set[KeyT]] = None
11
+ def _ensure(self) -> Set[KeyT]:
12
+ return set(self._metadata.keys()) if self._candidates is None else set(self._candidates)
13
+ def _select_index(self, name: str, values: Iterable[Any]) -> Set[KeyT]:
14
+ out: Set[KeyT] = set()
15
+ idx = self._indexes.get(name, {})
16
+ for v in values:
17
+ out.update(idx.get(v, []))
18
+ return out
19
+ def _new(self, candidates: Set[KeyT]) -> "ComponentLocator":
20
+ nl = ComponentLocator(self._metadata, self._indexes)
21
+ nl._candidates = candidates
22
+ return nl
23
+ def with_index_any(self, name: str, *values: Any) -> "ComponentLocator":
24
+ base = self._ensure()
25
+ sel = self._select_index(name, values)
26
+ return self._new(base & sel)
27
+ def with_index_all(self, name: str, *values: Any) -> "ComponentLocator":
28
+ base = self._ensure()
29
+ cur = base
30
+ for v in values:
31
+ cur = cur & set(self._indexes.get(name, {}).get(v, []))
32
+ return self._new(cur)
33
+ def with_qualifier_any(self, *qs: Any) -> "ComponentLocator":
34
+ return self.with_index_any("qualifier", *qs)
35
+ def primary_only(self) -> "ComponentLocator":
36
+ return self.with_index_any("primary", True)
37
+ def lazy(self, is_lazy: bool = True) -> "ComponentLocator":
38
+ return self.with_index_any("lazy", True) if is_lazy else self.with_index_any("lazy", False)
39
+ def infra(self, *names: Any) -> "ComponentLocator":
40
+ return self.with_index_any("infra", *names)
41
+ def pico_name(self, *names: Any) -> "ComponentLocator":
42
+ return self.with_index_any("pico_name", *names)
43
+ def by_key_type(self, t: type) -> "ComponentLocator":
44
+ base = self._ensure()
45
+ if t is str:
46
+ c = {k for k in base if isinstance(k, str)}
47
+ elif t is type:
48
+ c = {k for k in base if isinstance(k, type)}
49
+ else:
50
+ c = {k for k in base if isinstance(k, t)}
51
+ return self._new(c)
52
+ def keys(self) -> List[KeyT]:
53
+ return list(self._ensure())
pico_ioc/scope.py CHANGED
@@ -1,41 +1,112 @@
1
- from __future__ import annotations
1
+ import contextvars
2
+ from typing import Any, Dict, Optional, Tuple
3
+ from collections import OrderedDict
2
4
 
3
- from typing import Any, Optional
5
+ class ScopeProtocol:
6
+ def get_id(self) -> Any | None: ...
4
7
 
5
- from .container import PicoContainer
8
+ class ContextVarScope(ScopeProtocol):
9
+ def __init__(self, var: contextvars.ContextVar) -> None:
10
+ self._var = var
11
+ def get_id(self) -> Any | None:
12
+ return self._var.get()
13
+ def activate(self, scope_id: Any) -> contextvars.Token:
14
+ return self._var.set(scope_id)
15
+ def deactivate(self, token: contextvars.Token) -> None:
16
+ self._var.reset(token)
6
17
 
7
- class ScopedContainer(PicoContainer):
8
- def __init__(self, built_container: PicoContainer, base: Optional[PicoContainer], strict: bool):
9
- super().__init__(providers=getattr(built_container, "_providers", {}).copy())
10
- self._active_profiles = getattr(built_container, "_active_profiles", ())
11
- base_method_its = getattr(base, "_method_interceptors", ()) if base else ()
12
- base_container_its = getattr(base, "_container_interceptors", ()) if base else ()
13
- self._method_interceptors = base_method_its
14
- self._container_interceptors = base_container_its
15
- self._seen_interceptor_types = {type(it) for it in base_container_its}
16
- for it in getattr(built_container, "_method_interceptors", ()):
17
- self.add_method_interceptor(it)
18
- for it in getattr(built_container, "_container_interceptors", ()):
19
- self.add_container_interceptor(it)
20
- self._base = base
21
- self._strict = strict
22
- if base:
23
- self._singletons.update(getattr(base, "_singletons", {}))
18
+ class ComponentContainer:
19
+ def __init__(self) -> None:
20
+ self._instances: Dict[object, object] = {}
21
+ def get(self, key):
22
+ return self._instances.get(key)
23
+ def put(self, key, value):
24
+ self._instances[key] = value
25
+ def items(self):
26
+ return list(self._instances.items())
24
27
 
25
- def __enter__(self): return self
26
- def __exit__(self, exc_type, exc, tb): return False
28
+ class _NoCacheContainer(ComponentContainer):
29
+ def __init__(self) -> None:
30
+ pass
31
+ def get(self, key):
32
+ return None
33
+ def put(self, key, value):
34
+ return
35
+ def items(self):
36
+ return []
27
37
 
28
- def has(self, key: Any) -> bool:
29
- if super().has(key): return True
30
- if not self._strict and self._base is not None:
31
- return self._base.has(key)
32
- return False
33
-
34
- def get(self, key: Any):
35
- try:
36
- return super().get(key)
37
- except NameError as e:
38
- if not self._strict and self._base is not None and self._base.has(key):
39
- return self._base.get(key)
40
- raise e
38
+ class ScopeManager:
39
+ def __init__(self) -> None:
40
+ self._scopes: Dict[str, ScopeProtocol] = {
41
+ "request": ContextVarScope(contextvars.ContextVar("pico_request_id", default=None)),
42
+ "session": ContextVarScope(contextvars.ContextVar("pico_session_id", default=None)),
43
+ "transaction": ContextVarScope(contextvars.ContextVar("pico_tx_id", default=None)),
44
+ }
45
+ def register_scope(self, name: str, implementation: ScopeProtocol) -> None:
46
+ if not isinstance(name, str) or not name:
47
+ from .exceptions import ScopeError
48
+ raise ScopeError("Scope name must be a non-empty string")
49
+ if name in ("singleton", "prototype"):
50
+ from .exceptions import ScopeError
51
+ raise ScopeError("Cannot register or override reserved scopes: 'singleton' or 'prototype'")
52
+ self._scopes[name] = implementation
53
+ def get_id(self, name: str) -> Any | None:
54
+ if name in ("singleton", "prototype"):
55
+ return None
56
+ impl = self._scopes.get(name)
57
+ return impl.get_id() if impl else None
58
+ def activate(self, name: str, scope_id: Any) -> Optional[contextvars.Token]:
59
+ if name in ("singleton", "prototype"):
60
+ return None
61
+ impl = self._scopes.get(name)
62
+ if impl is None:
63
+ from .exceptions import ScopeError
64
+ raise ScopeError(f"Unknown scope: {name}")
65
+ if hasattr(impl, "activate"):
66
+ return getattr(impl, "activate")(scope_id)
67
+ return None
68
+ def deactivate(self, name: str, token: Optional[contextvars.Token]) -> None:
69
+ if name in ("singleton", "prototype"):
70
+ return
71
+ impl = self._scopes.get(name)
72
+ if impl is None:
73
+ from .exceptions import ScopeError
74
+ raise ScopeError(f"Unknown scope: {name}")
75
+ if token is not None and hasattr(impl, "deactivate"):
76
+ getattr(impl, "deactivate")(token)
77
+ def names(self) -> Tuple[str, ...]:
78
+ return tuple(n for n in self._scopes.keys() if n not in ("singleton", "prototype"))
79
+ def signature(self, names: Tuple[str, ...]) -> Tuple[Any, ...]:
80
+ return tuple(self.get_id(n) for n in names)
81
+ def signature_all(self) -> Tuple[Any, ...]:
82
+ return self.signature(self.names())
41
83
 
84
+ class ScopedCaches:
85
+ def __init__(self, max_scopes_per_type: int = 2048) -> None:
86
+ self._singleton = ComponentContainer()
87
+ self._by_scope: Dict[str, OrderedDict[Any, ComponentContainer]] = {}
88
+ self._max = int(max_scopes_per_type)
89
+ self._no_cache = _NoCacheContainer()
90
+ def for_scope(self, scopes: ScopeManager, scope: str) -> ComponentContainer:
91
+ if scope == "singleton":
92
+ return self._singleton
93
+ if scope == "prototype":
94
+ return self._no_cache
95
+ sid = scopes.get_id(scope)
96
+ bucket = self._by_scope.setdefault(scope, OrderedDict())
97
+ if sid in bucket:
98
+ c = bucket.pop(sid)
99
+ bucket[sid] = c
100
+ return c
101
+ if len(bucket) >= self._max:
102
+ bucket.popitem(last=False)
103
+ c = ComponentContainer()
104
+ bucket[sid] = c
105
+ return c
106
+ def all_items(self):
107
+ for item in self._singleton.items():
108
+ yield item
109
+ for b in self._by_scope.values():
110
+ for c in b.values():
111
+ for item in c.items():
112
+ yield item
@@ -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
-