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/public_api.py DELETED
@@ -1,76 +0,0 @@
1
- # pico_ioc/public_api.py
2
-
3
- from __future__ import annotations
4
- import importlib
5
- import inspect
6
- import pkgutil
7
- import sys
8
- from types import ModuleType
9
- from typing import Dict, Iterable, Optional, Tuple
10
-
11
- from .decorators import COMPONENT_FLAG, FACTORY_FLAG, PLUGIN_FLAG
12
-
13
-
14
- def export_public_symbols_decorated(
15
- *packages: str,
16
- include_also: Optional[Iterable[str]] = None,
17
- include_plugins: bool = True,
18
- ):
19
- index: Dict[str, Tuple[str, str]] = {}
20
-
21
- def _collect(m: ModuleType):
22
- names = getattr(m, "__all__", None)
23
- if isinstance(names, (list, tuple, set)):
24
- for n in names:
25
- if hasattr(m, n):
26
- index.setdefault(n, (m.__name__, n))
27
- return
28
-
29
- for n, obj in m.__dict__.items():
30
- if not inspect.isclass(obj):
31
- continue
32
- is_component = getattr(obj, COMPONENT_FLAG, False)
33
- is_factory = getattr(obj, FACTORY_FLAG, False)
34
- is_plugin = include_plugins and getattr(obj, PLUGIN_FLAG, False)
35
- if is_component or is_factory or is_plugin:
36
- index.setdefault(n, (m.__name__, n))
37
-
38
- for pkg_name in packages:
39
- try:
40
- base = importlib.import_module(pkg_name)
41
- except Exception:
42
- continue
43
- if hasattr(base, "__path__"):
44
- prefix = base.__name__ + "."
45
- for _, modname, _ in pkgutil.walk_packages(base.__path__, prefix):
46
- try:
47
- m = importlib.import_module(modname)
48
- except Exception:
49
- continue
50
- _collect(m)
51
- else:
52
- _collect(base)
53
-
54
- for qual in tuple(include_also or ()):
55
- modname, _, attr = qual.partition(":")
56
- if modname and attr:
57
- try:
58
- m = importlib.import_module(modname)
59
- if hasattr(m, attr):
60
- index.setdefault(attr, (m.__name__, attr))
61
- except Exception:
62
- pass
63
-
64
- def __getattr__(name: str):
65
- try:
66
- modname, attr = index[name]
67
- except KeyError as e:
68
- raise AttributeError(f"module has no attribute {name!r}") from e
69
- mod = sys.modules.get(modname) or importlib.import_module(modname)
70
- return getattr(mod, attr)
71
-
72
- def __dir__():
73
- return sorted(index.keys())
74
-
75
- return __getattr__, __dir__
76
-
pico_ioc/resolver.py DELETED
@@ -1,101 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import inspect
4
- from typing import Any, Annotated, Callable, get_args, get_origin, get_type_hints
5
- from contextvars import ContextVar
6
-
7
- _path: ContextVar[list[tuple[str, str]]] = ContextVar("pico_resolve_path", default=[])
8
-
9
- def _get_hints(obj, owner_cls=None) -> dict:
10
- mod = inspect.getmodule(obj)
11
- g = getattr(mod, "__dict__", {})
12
- l = vars(owner_cls) if owner_cls is not None else None
13
- return get_type_hints(obj, globalns=g, localns=l, include_extras=True)
14
-
15
- def _is_collection_hint(tp) -> bool:
16
- origin = get_origin(tp) or tp
17
- return origin in (list, tuple)
18
-
19
- def _base_and_qualifiers_from_hint(tp):
20
- origin = get_origin(tp) or tp
21
- args = get_args(tp) or ()
22
- container_kind = list if origin is list else tuple
23
- if not args:
24
- return (object, (), container_kind)
25
- inner = args[0]
26
- if get_origin(inner) is Annotated:
27
- base, *extras = get_args(inner)
28
- quals = tuple(a for a in extras if isinstance(a, str))
29
- return (base, quals, container_kind)
30
- return (inner, (), container_kind)
31
-
32
- class Resolver:
33
- def __init__(self, container, *, prefer_name_first: bool = True):
34
- self.c = container
35
- self._prefer_name_first = bool(prefer_name_first)
36
-
37
- def _resolve_dependencies_for_callable(self, fn: Callable, owner_cls: Any = None) -> dict:
38
- sig = inspect.signature(fn)
39
- hints = _get_hints(fn, owner_cls=owner_cls)
40
- kwargs = {}
41
- path_owner = getattr(owner_cls, "__name__", getattr(fn, "__qualname__", "callable"))
42
- if fn.__name__ == "__init__" and owner_cls:
43
- path_owner = f"{path_owner}.__init__"
44
- for name, param in sig.parameters.items():
45
- if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD) or name == "self":
46
- continue
47
- ann = hints.get(name, param.annotation)
48
- st = _path.get()
49
- _path.set(st + [(path_owner, name)])
50
- try:
51
- kwargs[name] = self._resolve_param(name, ann)
52
- except NameError as e:
53
- if param.default is not inspect.Parameter.empty:
54
- _path.set(st)
55
- continue
56
- if "(required by" in str(e):
57
- raise
58
- chain = " -> ".join(f"{owner}.{param}" for owner, param in _path.get())
59
- raise NameError(f"{e} (required by {chain})") from e
60
- finally:
61
- cur = _path.get()
62
- if cur:
63
- _path.set(cur[:-1])
64
- return kwargs
65
-
66
- def create_instance(self, cls: type) -> Any:
67
- ctor_kwargs = self._resolve_dependencies_for_callable(cls.__init__, owner_cls=cls)
68
- return cls(**ctor_kwargs)
69
-
70
- def kwargs_for_callable(self, fn: Callable, *, owner_cls: Any = None) -> dict:
71
- return self._resolve_dependencies_for_callable(fn, owner_cls=owner_cls)
72
-
73
- def _notify_resolve(self, key, ann, quals=()):
74
- try:
75
- self.c._notify_resolve(key, ann, quals)
76
- except Exception:
77
- pass
78
-
79
- def _resolve_param(self, name: str, ann: Any):
80
- if _is_collection_hint(ann):
81
- base, quals, kind = _base_and_qualifiers_from_hint(ann)
82
- self._notify_resolve(base, ann, quals)
83
- items = self.c._resolve_all_for_base(base, qualifiers=quals)
84
- return list(items) if kind is list else tuple(items)
85
- if self._prefer_name_first and self.c.has(name):
86
- self._notify_resolve(name, ann, ())
87
- return self.c.get(name)
88
- if ann is not inspect._empty and self.c.has(ann):
89
- self._notify_resolve(ann, ann, ())
90
- return self.c.get(ann)
91
- if ann is not inspect._empty and isinstance(ann, type):
92
- for base in ann.__mro__[1:]:
93
- if self.c.has(base):
94
- self._notify_resolve(base, ann, ())
95
- return self.c.get(base)
96
- if self.c.has(name):
97
- self._notify_resolve(name, ann, ())
98
- return self.c.get(name)
99
- missing = ann if ann is not inspect._empty else name
100
- raise NameError(f"No provider found for key {missing!r}")
101
-
pico_ioc/scanner.py DELETED
@@ -1,178 +0,0 @@
1
- from __future__ import annotations
2
- import importlib
3
- import inspect
4
- import logging
5
- import pkgutil
6
- from types import ModuleType
7
- from typing import Any, Callable, Optional, Tuple, List, Iterable
8
-
9
- from .plugins import run_plugin_hook, PicoPlugin
10
- from .container import PicoContainer, Binder
11
- from .decorators import (
12
- COMPONENT_FLAG,
13
- COMPONENT_KEY,
14
- COMPONENT_LAZY,
15
- FACTORY_FLAG,
16
- PROVIDES_KEY,
17
- PROVIDES_LAZY,
18
- COMPONENT_TAGS,
19
- PROVIDES_TAGS,
20
- INFRA_META,
21
- )
22
- from .proxy import ComponentProxy
23
- from .resolver import Resolver
24
- from . import _state
25
- from .utils import _provider_from_class, _provider_from_callable
26
- from .config import is_config_component, build_component_instance, ConfigRegistry
27
-
28
- def scan_and_configure(
29
- package_or_name: Any,
30
- container: PicoContainer,
31
- *,
32
- exclude: Optional[Callable[[str], bool]] = None,
33
- plugins: Tuple[PicoPlugin, ...] = (),
34
- ) -> tuple[int, int, list[tuple[type, dict]]]:
35
- package = _as_module(package_or_name)
36
- logging.info("Scanning in '%s'...", getattr(package, "__name__", repr(package)))
37
- binder = Binder(container)
38
- resolver = Resolver(container)
39
- run_plugin_hook(plugins, "before_scan", package, binder)
40
- comp_classes, factory_classes, infra_decls = _collect_decorated(
41
- package=package,
42
- exclude=exclude,
43
- plugins=plugins,
44
- binder=binder,
45
- )
46
- run_plugin_hook(plugins, "after_scan", package, binder)
47
- _register_component_classes(classes=comp_classes, container=container, resolver=resolver)
48
- _register_factory_classes(factory_classes=factory_classes, container=container, resolver=resolver)
49
- return len(comp_classes), len(factory_classes), infra_decls
50
-
51
- def _as_module(package_or_name: Any) -> ModuleType:
52
- if isinstance(package_or_name, str):
53
- return importlib.import_module(package_or_name)
54
- if hasattr(package_or_name, "__spec__"):
55
- return package_or_name
56
- raise TypeError("package_or_name must be a module or importable package name (str).")
57
-
58
- def _iter_package_modules(package: ModuleType) -> Iterable[str]:
59
- try:
60
- pkg_path = package.__path__
61
- except Exception:
62
- return
63
- prefix = package.__name__ + "."
64
- for _finder, name, _is_pkg in pkgutil.walk_packages(pkg_path, prefix):
65
- yield name
66
-
67
- def _collect_decorated(
68
- *,
69
- package: ModuleType,
70
- exclude: Optional[Callable[[str], bool]],
71
- plugins: Tuple[PicoPlugin, ...],
72
- binder: Binder,
73
- ) -> Tuple[List[type], List[type], List[tuple[type, dict]]]:
74
- comps: List[type] = []
75
- facts: List[type] = []
76
- infras: List[tuple[type, dict]] = []
77
-
78
- def _collect_from_class(cls: type):
79
- if getattr(cls, COMPONENT_FLAG, False):
80
- comps.append(cls)
81
- elif getattr(cls, FACTORY_FLAG, False):
82
- facts.append(cls)
83
- infra_m = getattr(cls, INFRA_META, None)
84
- if infra_m:
85
- infras.append((cls, dict(infra_m)))
86
- for _nm, _fn in inspect.getmembers(cls, predicate=inspect.isfunction):
87
- pass
88
-
89
- def _visit_module(module: ModuleType):
90
- for _name, obj in inspect.getmembers(module, inspect.isclass):
91
- run_plugin_hook(plugins, "visit_class", module, obj, binder)
92
- _collect_from_class(obj)
93
-
94
- for mod_name in _iter_package_modules(package):
95
- if exclude and exclude(mod_name):
96
- logging.info("Skipping module %s (excluded)", mod_name)
97
- continue
98
- try:
99
- module = importlib.import_module(mod_name)
100
- except Exception as e:
101
- logging.warning("Module %s not processed: %s", mod_name, e)
102
- continue
103
- _visit_module(module)
104
-
105
- if not hasattr(package, "__path__"):
106
- _visit_module(package)
107
-
108
- return comps, facts, infras
109
-
110
- def _register_component_classes(
111
- *,
112
- classes: List[type],
113
- container: PicoContainer,
114
- resolver: Resolver,
115
- ) -> None:
116
- for cls in classes:
117
- key = getattr(cls, COMPONENT_KEY, cls)
118
- is_lazy = bool(getattr(cls, COMPONENT_LAZY, False))
119
- tags = tuple(getattr(cls, COMPONENT_TAGS, ()))
120
- if is_config_component(cls):
121
- registry: ConfigRegistry | None = getattr(container, "_config_registry", None)
122
- def _prov(_c=cls, _reg=registry):
123
- if _reg is None:
124
- raise RuntimeError(f"No config registry found to build {_c.__name__}")
125
- return build_component_instance(_c, _reg)
126
- provider = (lambda p=_prov: ComponentProxy(p)) if is_lazy else _prov
127
- else:
128
- provider = _provider_from_class(cls, resolver=resolver, lazy=is_lazy)
129
- container.bind(key, provider, lazy=is_lazy, tags=tags)
130
-
131
- def _register_factory_classes(
132
- *,
133
- factory_classes: List[type],
134
- container: PicoContainer,
135
- resolver: Resolver,
136
- ) -> None:
137
- for fcls in factory_classes:
138
- try:
139
- tok_res = _state._resolving.set(True)
140
- try:
141
- finst = resolver.create_instance(fcls)
142
- finally:
143
- _state._resolving.reset(tok_res)
144
- except Exception:
145
- logging.exception("Error in factory %s", fcls.__name__)
146
- continue
147
- raw_dict = getattr(fcls, "__dict__", {})
148
- for attr_name, attr in inspect.getmembers(fcls):
149
- func = None
150
- raw = raw_dict.get(attr_name, None)
151
- if isinstance(raw, classmethod):
152
- func = raw.__func__
153
- elif isinstance(raw, staticmethod):
154
- func = raw.__func__
155
- elif inspect.isfunction(attr):
156
- func = attr
157
- if func is None:
158
- continue
159
- provided_key = getattr(func, PROVIDES_KEY, None)
160
- if provided_key is None:
161
- continue
162
- is_lazy = bool(getattr(func, PROVIDES_LAZY, False))
163
- tags = tuple(getattr(func, PROVIDES_TAGS, ()))
164
- if isinstance(raw, (classmethod, staticmethod)):
165
- bound = getattr(fcls, attr_name)
166
- else:
167
- bound = getattr(finst, attr_name, func.__get__(finst, fcls))
168
- prov = _provider_from_callable(bound, owner_cls=fcls, resolver=resolver, lazy=is_lazy)
169
- if isinstance(provided_key, type):
170
- try:
171
- setattr(prov, "_pico_alias_for", provided_key)
172
- except Exception:
173
- pass
174
- unique_key = (provided_key, f"{fcls.__name__}.{attr_name}")
175
- container.bind(unique_key, prov, lazy=is_lazy, tags=tags)
176
- else:
177
- container.bind(provided_key, prov, lazy=is_lazy, tags=tags)
178
-
pico_ioc/utils.py DELETED
@@ -1,25 +0,0 @@
1
- # src/pico_ioc/utils.py
2
- from typing import Any, Callable
3
- from .container import PicoContainer
4
- from .proxy import ComponentProxy
5
-
6
- def _wrap_if_lazy(provider: Callable, is_lazy: bool) -> Callable:
7
- """Wraps a provider in a ComponentProxy if it's marked as lazy."""
8
- return (lambda: ComponentProxy(provider)) if is_lazy else provider
9
-
10
- def _provider_from_class(cls: type, *, resolver, lazy: bool):
11
- def _new():
12
- return resolver.create_instance(cls)
13
- return _wrap_if_lazy(_new, lazy)
14
-
15
- def _provider_from_callable(fn, *, owner_cls, resolver, lazy: bool):
16
- def _invoke():
17
- kwargs = resolver.kwargs_for_callable(fn, owner_cls=owner_cls)
18
- return fn(**kwargs)
19
- return _wrap_if_lazy(_invoke, lazy)
20
-
21
- def create_alias_provider(container: PicoContainer, target_key: Any) -> Callable[[], Any]:
22
- """Creates a provider that delegates the get() call to the container for another key."""
23
- def _provider():
24
- return container.get(target_key)
25
- return _provider
@@ -1,249 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: pico-ioc
3
- Version: 1.5.0
4
- Summary: A minimalist, zero-dependency Inversion of Control (IoC) container for Python.
5
- Author-email: David Perez Cabrera <dperezcabrera@gmail.com>
6
- License: MIT License
7
-
8
- Copyright (c) 2025 David Pérez Cabrera
9
-
10
- Permission is hereby granted, free of charge, to any person obtaining a copy
11
- of this software and associated documentation files (the "Software"), to deal
12
- in the Software without restriction, including without limitation the rights
13
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
- copies of the Software, and to permit persons to whom the Software is
15
- furnished to do so, subject to the following conditions:
16
-
17
- The above copyright notice and this permission notice shall be included in all
18
- copies or substantial portions of the Software.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
- SOFTWARE.
27
-
28
- Project-URL: Homepage, https://github.com/dperezcabrera/pico-ioc
29
- Project-URL: Repository, https://github.com/dperezcabrera/pico-ioc
30
- Project-URL: Issue Tracker, https://github.com/dperezcabrera/pico-ioc/issues
31
- Keywords: ioc,di,dependency injection,inversion of control,decorator
32
- Classifier: Development Status :: 4 - Beta
33
- Classifier: Programming Language :: Python :: 3
34
- Classifier: Programming Language :: Python :: 3 :: Only
35
- Classifier: Programming Language :: Python :: 3.10
36
- Classifier: Programming Language :: Python :: 3.11
37
- Classifier: Programming Language :: Python :: 3.12
38
- Classifier: Programming Language :: Python :: 3.13
39
- Classifier: License :: OSI Approved :: MIT License
40
- Classifier: Operating System :: OS Independent
41
- Requires-Python: >=3.8
42
- Description-Content-Type: text/markdown
43
- License-File: LICENSE
44
- Dynamic: license-file
45
-
46
- # 📦 Pico-IoC: A Minimalist IoC Container for Python
47
-
48
- [![PyPI](https://img.shields.io/pypi/v/pico-ioc.svg)](https://pypi.org/project/pico-ioc/)
49
- [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/dperezcabrera/pico-ioc)
50
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
51
- ![CI (tox matrix)](https://github.com/dperezcabrera/pico-ioc/actions/workflows/ci.yml/badge.svg)
52
- [![codecov](https://codecov.io/gh/dperezcabrera/pico-ioc/branch/main/graph/badge.svg)](https://codecov.io/gh/dperezcabrera/pico-ioc)
53
- [![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)
54
- [![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)
55
- [![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)
56
-
57
- **pico-ioc** is a **tiny, zero-dependency, decorator-based IoC container for Python**.
58
- It helps you build loosely-coupled, testable apps without manual wiring. Inspired by the Spring ecosystem, but minimal.
59
-
60
- > ⚠️ **Requires Python 3.10+** (uses `typing.Annotated` and `include_extras=True`).
61
-
62
- ---
63
-
64
- ## ⚖️ Principles
65
-
66
- * **Focus & Simplicity**: A minimal core for one job: managing dependencies. It avoids accidental complexity by doing one thing well.
67
- * **Predictable & Explicit**: No magic. Behavior is deterministic, relying on explicit decorators and a clear resolution order.
68
- * **Unified Composition Root**: The application is assembled from a single entry point (`init`) which defines a clear, predictable boundary. This ensures a stable and understandable bootstrap process.
69
- * **Fail-Fast Bootstrap**: Catches dependency graph errors at startup, not in production. If the application runs, it's wired correctly.
70
- * **Testability First**: Features like `scope()` and `overrides` are first-class citizens, enabling fast and isolated testing.
71
- * **Extensible by Design**: Lifecycle hooks and AOP are available through a clean Plugin and Interceptor API without altering the core.
72
- * **Framework Agnostic**: Zero hard dependencies. It works with any Python application, from simple scripts to complex web servers.
73
-
74
- ---
75
-
76
- ## ✨ Why Pico-IoC?
77
-
78
- `pico-ioc` exists to solve a common problem that arises as Python applications grow: managing how objects are created and connected becomes complex and brittle. This manual wiring, where a change deep in the application can cause a cascade of updates, makes the code hard to test and maintain. `pico-ioc` introduces the principle of Inversion of Control (IoC) in a simple, Pythonic way. Instead of you creating and connecting every object, you declare your components with a simple `@component` decorator, and the container automatically wires them together based on their type hints. It brings the architectural robustness and testability of mature frameworks like Spring to the Python ecosystem, but without the heavy boilerplate, allowing you to build complex, loosely-coupled applications that remain simple to manage.
79
-
80
-
81
- | Feature | Manual Wiring | With Pico-IoC |
82
- | :------------------ | :------------------------------------------------ | :------------------------------ |
83
- | **Object Creation** | `service = Service(Repo(Config()))` | `svc = container.get(Service)` |
84
- | **Testing** | Manual replacement or monkey-patching | `overrides={Repo: FakeRepo()}` |
85
- | **Coupling** | High (code knows about constructors) | Low (code just asks for a type) |
86
- | **Maintenance** | Brittle (changing a constructor breaks consumers) | Robust (changes are isolated) |
87
- | **Learning Curve** | Ad-hoc, implicit patterns | Uniform, explicit, documented |
88
-
89
-
90
- ---
91
-
92
- ## 🧩 Features
93
-
94
- ### Core
95
-
96
- * **Zero dependencies** — pure Python, framework-agnostic.
97
- * **Single Entry Point (`init`)** — Robustly bootstrap your entire application from a single root package, enforcing a clean "Composition Root" pattern.
98
- * **Decorator API** — `@component`, `@factory_component`, `@provides`, `@plugin`.
99
- * **Fail-fast bootstrap** — eager by default; missing deps surface at startup.
100
- * **Opt-in lazy** — `lazy=True` wraps with `ComponentProxy`.
101
- * **Smart resolution order** — parameter name → type annotation → MRO → string.
102
- * **Overrides for testing** — inject mocks/fakes directly via `init(overrides={...})`.
103
- * **Public API helper** — auto-export decorated symbols in `__init__.py`.
104
- * **Thread/async safe** — isolation via `ContextVar`.
105
-
106
- ### Advanced
107
-
108
- * **Qualifiers & collections** — `list[Annotated[T, Q]]` filters by qualifier.
109
- * **Flexible Scopes (`scope`)** — Create lightweight, temporary containers from multiple modules, ideal for testing, scripting, or modular tasks.
110
- * **Interceptors API** — observe/modify resolution, instantiation, invocation, errors.
111
- * **Conditional providers** — activate components by env vars or predicates.
112
- * **Plugins** — lifecycle hooks (`before_scan`, `after_ready`).
113
-
114
- ---
115
-
116
- ## 📦 Installation
117
-
118
- ```bash
119
- # Requires Python 3.10+
120
- pip install pico-ioc
121
- ````
122
-
123
- ---
124
-
125
- ## 🚀 Quick start
126
-
127
- ```python
128
- from pico_ioc import component, init
129
-
130
- @component
131
- class Config:
132
- url = "sqlite:///demo.db"
133
-
134
- @component
135
- class Repo:
136
- def __init__(self, cfg: Config):
137
- self.url = cfg.url
138
- def fetch(self): return f"fetching from {self.url}"
139
-
140
- @component
141
- class Service:
142
- def __init__(self, repo: Repo):
143
- self.repo = repo
144
- def run(self): return self.repo.fetch()
145
-
146
- # bootstrap
147
- import myapp
148
- c = init(myapp)
149
- svc = c.get(Service)
150
- print(svc.run())
151
- ```
152
-
153
- **Output:**
154
-
155
- ```
156
- fetching from sqlite:///demo.db
157
- ```
158
- ---
159
-
160
- ### Quick overrides for testing
161
-
162
- ```python
163
- from pico_ioc import init
164
- import myapp
165
-
166
- fake = {"repo": "fake-data"}
167
- c = init(myapp, overrides={
168
- "fast_model": fake, # constant instance
169
- "user_service": lambda: {"id": 1}, # provider
170
- })
171
- assert c.get("fast_model") == {"repo": "fake-data"}
172
- ```
173
- ---
174
-
175
- ### Scoped subgraphs
176
-
177
- For unit tests or lightweight integration, you can bootstrap **only a subset of the graph**.
178
-
179
- ```python
180
- from pico_ioc
181
- from src.runner_service import RunnerService
182
- from tests.fakes import FakeDocker
183
- import src
184
-
185
- c = pico_ioc.scope(
186
- modules=[src],
187
- roots=[RunnerService], # only RunnerService and its deps
188
- overrides={
189
- "docker.DockerClient": FakeDocker(),
190
- },
191
- strict=True, # fail if something is missing
192
- lazy=True, # instantiate on demand
193
- )
194
- svc = c.get(RunnerService)
195
- ```
196
-
197
- This way you don’t need to bootstrap your entire app (`controllers`, `http`, …) just to test one service.
198
-
199
- ---
200
- ## 📖 Documentation
201
-
202
- * **🚀 New to pico-ioc? Start with the User Guide.**
203
- * [**GUIDE.md**](.llm/GUIDE.md) — Learn with practical examples: testing, configuration, collection injection, and web framework integration.
204
-
205
- * **🏗️ Want to understand the internals? See the Architecture.**
206
- * [**ARCHITECTURE.md**](.llm/ARCHITECTURE.md) — A deep dive into the algorithms, lifecycle, and internal diagrams. Perfect for contributors.
207
-
208
- * **🤔 Want to know *why* it's designed this way? Read the Decisions.**
209
- * [**DECISIONS.md**](.llm/DECISIONS.md) — The history and rationale behind key technical decisions.
210
-
211
- * **💡 Just need a quick summary?**
212
- * [**OVERVIEW.md**](.llm/OVERVIEW.md) — What pico-ioc is and why you should use it.
213
- ---
214
-
215
- ## 🧪 Development
216
-
217
- ```bash
218
- pip install tox
219
- tox
220
- ```
221
-
222
- ---
223
-
224
- ## 📜 Overview
225
-
226
- See [OVERVIEW.md](.llm/OVERVIEW.md) Just need a quick summary?
227
- ---
228
-
229
- ## 🔔 Important Changes
230
-
231
- ### 1.5.0 (2025-09-17)
232
- - Introduced **`@infrastructure`** classes for bootstrap-time configuration.
233
- → They can query the model, add interceptors, wrap/replace providers, and adjust tags/qualifiers.
234
- - Added new **around-style interceptors** (`MethodInterceptor.invoke`, `ContainerInterceptor.around_*`) with deterministic ordering.
235
- - **Removed legacy `@interceptor` API** (before/after/error style). All interceptors must be migrated to the new contracts.
236
-
237
- ---
238
- ## 📜 Changelog
239
-
240
- See [CHANGELOG.md](./CHANGELOG.md) for version history.
241
-
242
- ---
243
-
244
- ## 📜 License
245
-
246
- MIT — see [LICENSE](https://opensource.org/licenses/MIT)
247
-
248
-
249
-
@@ -1,23 +0,0 @@
1
- pico_ioc/__init__.py,sha256=Nlj8wsCtOz1uGC9eg7GICsGc4EecU2t9AkY74E1hx_s,1400
2
- pico_ioc/_state.py,sha256=C98XQZIfKy98j8fzR730eUCoqSnCkRkxUS4bH7mp73c,2154
3
- pico_ioc/_version.py,sha256=wShy9YfBfroz0HjRH_aNNehkEu1_PLsd_GjTU5aCDPk,22
4
- pico_ioc/api.py,sha256=-zouzi8Uel7IXpiBYwra6ctqT71LLslcvU1trS4kKh8,8359
5
- pico_ioc/builder.py,sha256=lwhKliYYonar4JOUi-Nfa8sej06mwSUp0bvKBJLAYes,9007
6
- pico_ioc/config.py,sha256=J3k7_2vRB2HCpikzeMzT4Ut9COFM4kcydkwZorncqSk,12317
7
- pico_ioc/container.py,sha256=Chbi8Mhz_OlhD03tf1l4hQq2yGDpELL0eNKtjyjn0us,6389
8
- pico_ioc/decorators.py,sha256=LSMW5DYfQIV2y60E4tIVprMDUc4M7qCNCe7Pz5nN0Hg,3448
9
- pico_ioc/infra.py,sha256=IvYA2kliG6opMG8SXX6eneWCQ6tBfSeSCiLq0-f9rJ8,7924
10
- pico_ioc/interceptors.py,sha256=ZJjIRyTgHh9CTRpNZwTjM8iKvMLIw5OBQ7DrpF29HHY,3465
11
- pico_ioc/plugins.py,sha256=GP7WEMshggQ-FEjiShkcuLrSMxfueUnhbY9I8PcIyPU,1039
12
- pico_ioc/policy.py,sha256=p7maTHNfU-zoaz3j7CY4P3ry-bYfaGxAOklcTAuF6dY,8648
13
- pico_ioc/proxy.py,sha256=2XR5mwNTEpYzZFUCcFJW1psSgOgEFooeO91_2wdnRnk,6403
14
- pico_ioc/public_api.py,sha256=E3sArCoI1xxkIw7xQBvLYAWcIoVJjcq1s0kH-0qIVDE,2383
15
- pico_ioc/resolver.py,sha256=Fi4dHY4NuqxNxZwVVtBR1lBnhZSTBd3dDXzr8lRNe-g,4191
16
- pico_ioc/scanner.py,sha256=ieJ1A2UPWLqfybjPdWQowEx7ZCkN9693pa8sUc83LGE,6612
17
- pico_ioc/scope.py,sha256=pdSKcO14jt7_rB5ymLpbBI9qS9FbdvTGZfPj3Mc0Znc,1705
18
- pico_ioc/utils.py,sha256=OyhOKnyepwGQ_uQKlQLt-fymEV1bQ6hCq4Me7h3dfco,1002
19
- pico_ioc-1.5.0.dist-info/licenses/LICENSE,sha256=N1_nOvHTM6BobYnOTNXiQkroDqCEi6EzfGBv8lWtyZ0,1077
20
- pico_ioc-1.5.0.dist-info/METADATA,sha256=11GMlO6Z1S-PhiLBBHD5gTLfrpTxAR8q-HC6zFfHDwk,10844
21
- pico_ioc-1.5.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
22
- pico_ioc-1.5.0.dist-info/top_level.txt,sha256=_7_RLu616z_dtRw16impXn4Mw8IXe2J4BeX5912m5dQ,9
23
- pico_ioc-1.5.0.dist-info/RECORD,,