Skip to content

PicoContainer API Reference

This page lists the public methods of the PicoContainer class and the top-level init() function.


init() Function

This is the main entry point for creating and configuring a container.

import logging
from typing import Any, Iterable, Optional, Dict, Tuple, List, Union
from pico_ioc import PicoContainer, ContainerObserver
from pico_ioc.config_builder import ContextConfig

KeyT = Union[str, type]

def init(
    modules: Union[Any, Iterable[Any]],
    *,
    profiles: Tuple[str, ...] = (),
    allowed_profiles: Optional[Iterable[str]] = None,
    environ: Optional[Dict[str, str]] = None,
    overrides: Optional[Dict[KeyT, Any]] = None,
    logger: Optional[logging.Logger] = None,
    config: Optional[ContextConfig] = None,
    custom_scopes: Optional[Iterable[str]] = None,
    validate_only: bool = False,
    container_id: Optional[str] = None,
    observers: Optional[List[ContainerObserver]] = None,
    custom_scanners: Optional[List[CustomScanner]] = None,
) -> PicoContainer: ...
  • modules: A module, package, or an iterable of modules/package names (strings) to scan for components.
  • profiles: A tuple of active profile names (e.g., "prod", "test"). Used by conditional decorators.
  • allowed_profiles: Optional. If set, raises ConfigurationError if any profile in profiles is not in this list.
  • environ: Optional. A dictionary to use instead of os.environ. Useful for testing conditionals.
  • overrides: Optional. A dictionary mapping Keys to specific instances or provider functions, replacing any discovered components for those keys. Used primarily for testing.
  • logger: Optional. A custom logger instance. Defaults to pico_ioc.LOGGER.
  • config: Optional. A ContextConfig object created by the configuration(...) builder. Encapsulates configuration sources (environment variables, files, dictionaries), overrides, and rules for mapping them to @configured classes.
  • custom_scopes: Optional. An iterable of custom scope names (strings) to register. Pico IOC will automatically create ContextVar-backed scope implementations for these names.
  • validate_only: Default False. If True, performs all scanning and validation steps but returns a container without creating instances or running lifecycle methods. Useful for quick startup checks.
  • container_id: Optional. A specific ID string to assign to this container. If None, a unique ID is automatically generated.
  • observers: Optional. A list of objects implementing the ContainerObserver protocol. Observers receive events such as on_resolve and on_cache_hit for monitoring and tracing.
  • custom_scanners: Optional. A list of objects implementing the CustomScanner protocol. Custom scanners can hook into the module scanning process to discover and register components based on custom rules (e.g., custom decorators, specific base classes not normally tracked by pico-ioc).
  • Returns: A configured PicoContainer instance ready to resolve components.

PicoContainer Instance Methods

get(key: KeyT) -> Any

Synchronously retrieves or creates a component instance for the given Key. Raises ProviderNotFoundError or ComponentCreationError. Instances are cached according to scope.

  • key: The class type or string name of the component to retrieve.
  • Returns: The component instance.

aget(key: KeyT) -> Any

Asynchronously retrieves or creates a component instance for the given Key. Correctly handles async def providers and ainit methods. Raises ProviderNotFoundError or ComponentCreationError. Instances are cached according to scope.

  • key: The class type or string name of the component to retrieve.
  • Returns: The component instance (awaitable).

has(key: KeyT) -> bool

Checks if a provider is registered for the given Key or if an instance exists in the cache for the current scope.

  • key: The class type or string name to check.
  • Returns: True if the key can be resolved, False otherwise.

activate() -> contextvars.Token

Manually activates this container in the current context. Returns a token needed for deactivate(). Prefer using with container.as_current():.

  • Returns: A contextvars.Token for restoring the context.

deactivate(token: contextvars.Token) -> None

Manually deactivates this container, restoring the previous context using the token from activate().

  • token: The token returned by activate().

as_current() -> ContextManager[PicoContainer]

Returns a context manager (with container.as_current(): ...) that activates this container for the duration of the with block. This is the preferred way to manage the Container Context.

  • Yields: The container instance (self).

activate_scope(name: str, scope_id: Any) -> Optional[contextvars.Token]

Activates a specific Scope (e.g., "request") with a given ID. Returns a token if the scope uses contextvars. Prefer with container.scope():.

  • name: The name of the scope to activate (e.g., "request").
  • scope_id: A unique identifier for this instance of the scope (e.g., a request ID string).
  • Returns: An optional contextvars.Token.

deactivate_scope(name: str, token: Optional[contextvars.Token]) -> None

Deactivates a specific Scope using the token returned by activate_scope.

  • name: The name of the scope to deactivate.
  • token: The token returned by activate_scope.

scope(name: str, scope_id: Any) -> ContextManager[PicoContainer]

Returns a context manager (with container.scope("request", "id-123"): ...) that activates a specific Scope for the duration of the with block. This is the preferred way to manage scopes like "request".

  • name: The name of the scope to activate.
  • scope_id: A unique identifier for this scope instance.
  • Yields: The container instance (self).

cleanup_all() -> None

Synchronously calls all methods decorated with @cleanup on all cached singleton and scoped components managed by this container.


cleanup_all_async() -> Awaitable[None]

Asynchronously calls all methods decorated with @cleanup (including async def methods) on all cached components.

  • Returns: An awaitable.

shutdown() -> None

Performs a full shutdown: 1. Calls cleanup_all(). 2. Removes the container from the global registry (making it inaccessible via PicoContainer.get_current() or all_containers()).


ashutdown() -> Awaitable[None]

Asynchronously performs a full shutdown: 1. Awaits cleanup_all_async() to release async resources (DB connections, pools). 2. Removes the container from the global registry.

Usage: Always use this method (instead of shutdown) if your application runs on asyncio.

  • Returns: An awaitable.

stats() -> Dict[str, Any]

Returns a dictionary containing runtime statistics and metrics about the container (e.g., uptime, resolve counts, cache hit rate).

  • Returns: A dictionary of stats.

health_check() -> Dict[str, bool]

Executes all methods decorated with @health on cached components and returns a status report. Methods raising exceptions are reported as False (unhealthy).

  • Returns: A dictionary mapping 'ClassName.method_name' to a boolean health status.

export_graph(path: str, *, include_scopes: bool = True, include_qualifiers: bool = False, rankdir: str = "LR", title: Optional[str] = None) -> None

Exports the container's component dependency graph to a .dot file (Graphviz format) for visualization. Note: This method generates the .dot file content; rendering it requires the Graphviz tool.

  • path: The full path (including filename, typically with a .dot extension) where the graph file will be saved.
  • include_scopes: Default True. If True, adds scope information (e.g., [scope=request]) to the node labels.
  • include_qualifiers: Default False. If True, adds qualifier information (e.g., \n⟨q⟩) to the node labels.
  • rankdir: Default "LR". Sets the layout direction for Graphviz (e.g., "LR" for Left-to-Right, "TB" for Top-to-Bottom).
  • title: Optional. A title string to display at the top of the graph.
  • Returns: None.

PicoContainer Class Attributes / Methods (Static)

get_current() -> Optional[PicoContainer]

(Class method) Returns the PicoContainer instance currently active in this context (set via as_current() or activate()), or None if no container is active.

  • Returns: The active PicoContainer or None.

get_current_id() -> Optional[str]

(Class method) Returns the container_id of the currently active container, or None.

  • Returns: The active container's ID string or None.

all_containers() -> Dict[str, PicoContainer]

(Class method) Returns a dictionary mapping all currently active (not shut down) container IDs to their PicoContainer instances.

  • Returns: A dictionary of all registered containers.

Notes

  • Keys: A Key identifies a component and is typically a class or a string alias. The KeyT type in signatures is Union[str, type].
  • Scopes: Components can be singleton, request-scoped, or belong to custom scopes you register via init(custom_scopes=...).
  • Lifecycle: Decorate methods with @cleanup to have them called during cleanup; use @health for health checks.
  • Observability: Register observers via init(..., observers=[...]) to receive events (e.g., on_resolve, on_cache_hit) for monitoring.

Auto-generated API

pico_ioc.container

The core dependency injection container.

:class:PicoContainer is the central facade of pico-ioc. It provides synchronous (get) and asynchronous (aget) resolution, scope management, health checks, statistics, lifecycle management, and dependency graph export.

PicoContainer

Bases: _ResolutionMixin

The pico-ioc dependency injection container.

Created by :func:init. Provides synchronous (get) and asynchronous (aget) resolution, scope management, lifecycle hooks, health checks, and dependency graph export.

Parameters:

Name Type Description Default
component_factory ComponentFactory

The :class:ComponentFactory holding all provider bindings.

required
caches ScopedCaches

The :class:ScopedCaches instance managing instance storage.

required
scopes ScopeManager

The :class:ScopeManager coordinating scope activation.

required
observers Optional[List[ContainerObserver]]

Optional list of :class:ContainerObserver instances.

None
container_id Optional[str]

Optional explicit container identifier.

None
profiles Tuple[str, ...]

Active profile names.

()
Source code in src/pico_ioc/container.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
class PicoContainer(_ResolutionMixin):
    """The pico-ioc dependency injection container.

    Created by :func:`init`. Provides synchronous (``get``) and asynchronous
    (``aget``) resolution, scope management, lifecycle hooks, health checks,
    and dependency graph export.

    Args:
        component_factory: The :class:`ComponentFactory` holding all provider
            bindings.
        caches: The :class:`ScopedCaches` instance managing instance storage.
        scopes: The :class:`ScopeManager` coordinating scope activation.
        observers: Optional list of :class:`ContainerObserver` instances.
        container_id: Optional explicit container identifier.
        profiles: Active profile names.
    """

    _container_id_var: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar("pico_container_id", default=None)
    _container_registry: Dict[str, "PicoContainer"] = {}

    class _Ctx:
        def __init__(self, container_id: str, profiles: Tuple[str, ...], created_at: float) -> None:
            self.container_id = container_id
            self.profiles = profiles
            self.created_at = created_at
            self.resolve_count = 0
            self.cache_hit_count = 0

    def __init__(
        self,
        component_factory: ComponentFactory,
        caches: ScopedCaches,
        scopes: ScopeManager,
        observers: Optional[List["ContainerObserver"]] = None,
        container_id: Optional[str] = None,
        profiles: Tuple[str, ...] = (),
    ) -> None:
        self._factory = component_factory
        self._caches = caches
        self.scopes = scopes
        self._locator: Optional[ComponentLocator] = None
        self._observers = list(observers or [])
        self.container_id = container_id or self._generate_container_id()
        import time as _t

        self.context = PicoContainer._Ctx(container_id=self.container_id, profiles=profiles, created_at=_t.time())
        PicoContainer._container_registry[self.container_id] = self

    @staticmethod
    def _generate_container_id() -> str:
        import secrets
        import time as _t

        return f"c{_t.time_ns():x}{secrets.randbits(16):04x}"

    @classmethod
    def get_current(cls) -> Optional["PicoContainer"]:
        """Return the container that is active in the current context, or ``None``."""
        cid = cls._container_id_var.get()
        return cls._container_registry.get(cid) if cid else None

    @classmethod
    def get_current_id(cls) -> Optional[str]:
        """Return the container ID that is active in the current context, or ``None``."""
        return cls._container_id_var.get()

    @classmethod
    def all_containers(cls) -> Dict[str, "PicoContainer"]:
        """Return a snapshot dict of all live containers, keyed by container ID."""
        return dict(cls._container_registry)

    def activate(self) -> contextvars.Token:
        return PicoContainer._container_id_var.set(self.container_id)

    def deactivate(self, token: contextvars.Token) -> None:
        PicoContainer._container_id_var.reset(token)

    @contextmanager
    def as_current(self):
        token = self.activate()
        try:
            yield self
        finally:
            self.deactivate(token)

    def attach_locator(self, locator: ComponentLocator) -> None:
        self._locator = locator

    def _cache_for(self, key: KeyT):
        md = self._locator._metadata.get(key) if self._locator else None
        sc = md.scope if md else SCOPE_SINGLETON
        return self._caches.for_scope(self.scopes, sc)

    def has(self, key: KeyT) -> bool:
        """Check whether a component is registered for *key*.

        Args:
            key: The resolution key (type or string).

        Returns:
            ``True`` if a provider or cached instance exists for *key*.
        """
        cache = self._cache_for(key)
        return cache.get(key) is not None or self._factory.has(key)

    def _canonical_key(self, key: KeyT) -> KeyT:
        if self._factory.has(key):
            return key

        if isinstance(key, type) and self._locator:
            cands: List[Tuple[bool, Any]] = []
            for k, md in self._locator._metadata.items():
                typ = md.provided_type or md.concrete_class
                if not isinstance(typ, type):
                    continue
                try:
                    if typ is not key and issubclass(typ, key):
                        cands.append((md.primary, k))
                except Exception:
                    continue
            if cands:
                prim = [k for is_p, k in cands if is_p]
                return prim[0] if prim else cands[0][1]

        if isinstance(key, str) and self._locator:
            for k, md in self._locator._metadata.items():
                if md.pico_name == key:
                    return k

        return key

    def _resolve_or_create_internal(self, key: KeyT) -> Tuple[Any, float, bool]:
        key = self._canonical_key(key)
        cache = self._cache_for(key)
        cached = cache.get(key)

        if cached is not None:
            self.context.cache_hit_count += 1
            for o in self._observers:
                o.on_cache_hit(key)
            return cached, 0.0, True

        import time as _tm

        t0 = _tm.perf_counter()

        token_container = self.activate()
        requester = None

        try:
            provider = self._factory.get(key, origin=requester)
            try:
                instance_or_awaitable = provider()
            except ProviderNotFoundError:
                raise
            except Exception as creation_error:
                raise ComponentCreationError(key, creation_error) from creation_error

            took_ms = (_tm.perf_counter() - t0) * 1000
            return instance_or_awaitable, took_ms, False

        finally:
            self.deactivate(token_container)

    def _run_configure_methods(self, instance: Any) -> Any:
        if not _needs_async_configure(instance):
            for m in _iter_configure_methods(instance):
                configure_deps = analyze_callable_dependencies(m)
                args = self._resolve_args(configure_deps)
                res = m(**args)
                if inspect.isawaitable(res):
                    raise AsyncResolutionError(
                        f"Component {type(instance).__name__} returned an awaitable from synchronous "
                        f"@configure method '{m.__name__}'. You must use 'await container.aget()' "
                        "or make the method synchronous."
                    )
            return instance

        async def runner():
            for m in _iter_configure_methods(instance):
                configure_deps = analyze_callable_dependencies(m)
                args = self._resolve_args(configure_deps)
                r = m(**args)
                if inspect.isawaitable(r):
                    await r
            return instance

        return runner()

    @overload
    def get(self, key: type) -> Any: ...
    @overload
    def get(self, key: str) -> Any: ...
    def get(self, key: KeyT) -> Any:
        """Resolve a component synchronously.

        Args:
            key: The type or string key to resolve.

        Returns:
            The component instance.

        Raises:
            ProviderNotFoundError: If no provider is bound to *key*.
            AsyncResolutionError: If the provider returns an awaitable
                (use :meth:`aget` instead).
            ComponentCreationError: If the provider fails during creation.
        """
        instance_or_awaitable, took_ms, was_cached = self._resolve_or_create_internal(key)

        if was_cached:
            return instance_or_awaitable

        instance = instance_or_awaitable
        if inspect.isawaitable(instance):
            raise AsyncResolutionError(key)

        md = self._locator._metadata.get(key) if self._locator else None
        scope = md.scope if md else SCOPE_SINGLETON
        if scope != SCOPE_SINGLETON:
            instance_or_awaitable_configured = self._run_configure_methods(instance)
            if inspect.isawaitable(instance_or_awaitable_configured):
                raise AsyncResolutionError(key)
            instance = instance_or_awaitable_configured

        final_instance = self._maybe_wrap_with_aspects(key, instance)
        cache = self._cache_for(key)
        cache.put(key, final_instance)
        self.context.resolve_count += 1
        for o in self._observers:
            o.on_resolve(key, took_ms)

        return final_instance

    async def aget(self, key: KeyT) -> Any:
        """Resolve a component asynchronously.

        Awaits any coroutine returned by the provider, ``__ainit__``, and
        async ``@configure`` methods. Always safe to use, even for sync
        components.

        Args:
            key: The type or string key to resolve.

        Returns:
            The component instance.

        Raises:
            ProviderNotFoundError: If no provider is bound to *key*.
            ComponentCreationError: If the provider fails during creation.
        """
        instance_or_awaitable, took_ms, was_cached = self._resolve_or_create_internal(key)

        instance = instance_or_awaitable
        if was_cached:
            if isinstance(instance, UnifiedComponentProxy):
                await instance._async_init_if_needed()
            return instance

        if inspect.isawaitable(instance_or_awaitable):
            instance = await instance_or_awaitable

        md = self._locator._metadata.get(key) if self._locator else None
        scope = md.scope if md else SCOPE_SINGLETON
        if scope != SCOPE_SINGLETON:
            instance_or_awaitable_configured = self._run_configure_methods(instance)
            if inspect.isawaitable(instance_or_awaitable_configured):
                instance = await instance_or_awaitable_configured
            else:
                instance = instance_or_awaitable_configured

        final_instance = self._maybe_wrap_with_aspects(key, instance)

        if isinstance(final_instance, UnifiedComponentProxy):
            await final_instance._async_init_if_needed()

        cache = self._cache_for(key)
        cache.put(key, final_instance)
        self.context.resolve_count += 1
        for o in self._observers:
            o.on_resolve(key, took_ms)

        return final_instance

    def _iterate_cleanup_targets(self) -> Iterable[Any]:
        yield from (obj for _, obj in self._caches.all_items())

        if self._locator:
            seen = set()
            for md in self._locator._metadata.values():
                fc = md.factory_class
                if fc and fc not in seen:
                    seen.add(fc)
                    inst = self.get(fc) if self._factory.has(fc) else fc()
                    yield inst

    def _call_cleanup_method(self, method: Callable[..., Any]) -> Any:
        deps_requests = analyze_callable_dependencies(method)
        return method(**self._resolve_args(deps_requests))

    def cleanup_all(self) -> None:
        """Invoke all ``@cleanup`` methods on cached components (sync)."""
        for obj in self._iterate_cleanup_targets():
            for _, m in inspect.getmembers(obj, predicate=inspect.ismethod):
                meta = getattr(m, PICO_META, {})
                if meta.get("cleanup", False):
                    res = self._call_cleanup_method(m)
                    if inspect.isawaitable(res):
                        LOGGER.warning(f"Async cleanup method {m} called during sync shutdown. Awaitable ignored.")

    async def cleanup_all_async(self) -> None:
        """Invoke all ``@cleanup`` methods on cached components (async).

        Awaits async cleanup methods and closes the :class:`EventBus` if present.
        """
        for obj in self._iterate_cleanup_targets():
            for _, m in inspect.getmembers(obj, predicate=inspect.ismethod):
                meta = getattr(m, PICO_META, {})
                if meta.get("cleanup", False):
                    res = self._call_cleanup_method(m)
                    if inspect.isawaitable(res):
                        await res

        try:
            from .event_bus import EventBus

            for _, obj in self._caches.all_items():
                if isinstance(obj, EventBus):
                    await obj.aclose()
        except Exception:
            pass

    def activate_scope(self, name: str, scope_id: Any):
        return self.scopes.activate(name, scope_id)

    def deactivate_scope(self, name: str, token: Optional[contextvars.Token]) -> None:
        self.scopes.deactivate(name, token)

    def info(self, msg: str) -> None:
        LOGGER.info(f"[{self.container_id[:8]}] {msg}")

    @contextmanager
    def scope(self, name: str, scope_id: Any):
        """Context manager that activates a scope for the duration of a block.

        Args:
            name: The scope name (e.g. ``"request"``).
            scope_id: A unique identifier for this scope instance.

        Yields:
            This container instance.

        Example:
            >>> with container.scope("request", request_id):
            ...     ctx = container.get(RequestContext)
        """
        tok = self.activate_scope(name, scope_id)
        try:
            yield self
        finally:
            self.deactivate_scope(name, tok)

    def health_check(self) -> Dict[str, bool]:
        """Run all ``@health``-decorated methods and return their results.

        Returns:
            Dict mapping ``"ClassName.method_name"`` to ``True``/``False``.
        """
        out: Dict[str, bool] = {}
        for k, obj in self._caches.all_items():
            for name, m in inspect.getmembers(obj, predicate=callable):
                if getattr(m, PICO_META, {}).get("health_check", False):
                    try:
                        out[f"{getattr(k, '__name__', k)}.{name}"] = bool(m())
                    except Exception:
                        out[f"{getattr(k, '__name__', k)}.{name}"] = False
        return out

    def stats(self) -> Dict[str, Any]:
        """Return container statistics.

        Returns:
            Dict with keys ``container_id``, ``profiles``,
            ``uptime_seconds``, ``total_resolves``, ``cache_hits``,
            ``cache_hit_rate``, and ``registered_components``.
        """
        import time as _t

        resolves = self.context.resolve_count
        hits = self.context.cache_hit_count
        total = resolves + hits
        return {
            "container_id": self.container_id,
            "profiles": self.context.profiles,
            "uptime_seconds": _t.time() - self.context.created_at,
            "total_resolves": resolves,
            "cache_hits": hits,
            "cache_hit_rate": (hits / total) if total > 0 else 0.0,
            "registered_components": len(self._locator._metadata) if self._locator else 0,
        }

    def shutdown(self) -> None:
        """Synchronously shut down the container.

        Calls all ``@cleanup`` methods and removes the container from the
        global registry.
        """
        self.cleanup_all()
        PicoContainer._container_registry.pop(self.container_id, None)

    async def ashutdown(self) -> None:
        """Asynchronously shut down the container.

        Awaits async ``@cleanup`` methods, closes the ``EventBus``, and
        removes the container from the global registry.
        """
        await self.cleanup_all_async()
        PicoContainer._container_registry.pop(self.container_id, None)

    def build_resolution_graph(self):
        """Build the static dependency graph from registered metadata.

        Returns:
            Dict mapping each key to a tuple of its dependency keys.
        """
        return _build_resolution_graph(self._locator)

    def export_graph(
        self,
        path: str,
        *,
        include_scopes: bool = True,
        include_qualifiers: bool = False,
        rankdir: str = "LR",
        title: Optional[str] = None,
    ) -> None:
        """Export the dependency graph as a Graphviz DOT file.

        Args:
            path: Filesystem path for the output ``.dot`` file.
            include_scopes: Annotate nodes with their scope.
            include_qualifiers: Annotate nodes with their qualifiers.
            rankdir: Graph layout direction (``"LR"`` or ``"TB"``).
            title: Optional graph title.

        Raises:
            RuntimeError: If no locator is attached to the container.
        """
        _export_graph(
            self._locator,
            path,
            include_scopes=include_scopes,
            include_qualifiers=include_qualifiers,
            rankdir=rankdir,
            title=title,
        )

get_current() classmethod

Return the container that is active in the current context, or None.

Source code in src/pico_ioc/container.py
@classmethod
def get_current(cls) -> Optional["PicoContainer"]:
    """Return the container that is active in the current context, or ``None``."""
    cid = cls._container_id_var.get()
    return cls._container_registry.get(cid) if cid else None

get_current_id() classmethod

Return the container ID that is active in the current context, or None.

Source code in src/pico_ioc/container.py
@classmethod
def get_current_id(cls) -> Optional[str]:
    """Return the container ID that is active in the current context, or ``None``."""
    return cls._container_id_var.get()

all_containers() classmethod

Return a snapshot dict of all live containers, keyed by container ID.

Source code in src/pico_ioc/container.py
@classmethod
def all_containers(cls) -> Dict[str, "PicoContainer"]:
    """Return a snapshot dict of all live containers, keyed by container ID."""
    return dict(cls._container_registry)

has(key)

Check whether a component is registered for key.

Parameters:

Name Type Description Default
key KeyT

The resolution key (type or string).

required

Returns:

Type Description
bool

True if a provider or cached instance exists for key.

Source code in src/pico_ioc/container.py
def has(self, key: KeyT) -> bool:
    """Check whether a component is registered for *key*.

    Args:
        key: The resolution key (type or string).

    Returns:
        ``True`` if a provider or cached instance exists for *key*.
    """
    cache = self._cache_for(key)
    return cache.get(key) is not None or self._factory.has(key)

get(key)

get(key: type) -> Any
get(key: str) -> Any

Resolve a component synchronously.

Parameters:

Name Type Description Default
key KeyT

The type or string key to resolve.

required

Returns:

Type Description
Any

The component instance.

Raises:

Type Description
ProviderNotFoundError

If no provider is bound to key.

AsyncResolutionError

If the provider returns an awaitable (use :meth:aget instead).

ComponentCreationError

If the provider fails during creation.

Source code in src/pico_ioc/container.py
def get(self, key: KeyT) -> Any:
    """Resolve a component synchronously.

    Args:
        key: The type or string key to resolve.

    Returns:
        The component instance.

    Raises:
        ProviderNotFoundError: If no provider is bound to *key*.
        AsyncResolutionError: If the provider returns an awaitable
            (use :meth:`aget` instead).
        ComponentCreationError: If the provider fails during creation.
    """
    instance_or_awaitable, took_ms, was_cached = self._resolve_or_create_internal(key)

    if was_cached:
        return instance_or_awaitable

    instance = instance_or_awaitable
    if inspect.isawaitable(instance):
        raise AsyncResolutionError(key)

    md = self._locator._metadata.get(key) if self._locator else None
    scope = md.scope if md else SCOPE_SINGLETON
    if scope != SCOPE_SINGLETON:
        instance_or_awaitable_configured = self._run_configure_methods(instance)
        if inspect.isawaitable(instance_or_awaitable_configured):
            raise AsyncResolutionError(key)
        instance = instance_or_awaitable_configured

    final_instance = self._maybe_wrap_with_aspects(key, instance)
    cache = self._cache_for(key)
    cache.put(key, final_instance)
    self.context.resolve_count += 1
    for o in self._observers:
        o.on_resolve(key, took_ms)

    return final_instance

aget(key) async

Resolve a component asynchronously.

Awaits any coroutine returned by the provider, __ainit__, and async @configure methods. Always safe to use, even for sync components.

Parameters:

Name Type Description Default
key KeyT

The type or string key to resolve.

required

Returns:

Type Description
Any

The component instance.

Raises:

Type Description
ProviderNotFoundError

If no provider is bound to key.

ComponentCreationError

If the provider fails during creation.

Source code in src/pico_ioc/container.py
async def aget(self, key: KeyT) -> Any:
    """Resolve a component asynchronously.

    Awaits any coroutine returned by the provider, ``__ainit__``, and
    async ``@configure`` methods. Always safe to use, even for sync
    components.

    Args:
        key: The type or string key to resolve.

    Returns:
        The component instance.

    Raises:
        ProviderNotFoundError: If no provider is bound to *key*.
        ComponentCreationError: If the provider fails during creation.
    """
    instance_or_awaitable, took_ms, was_cached = self._resolve_or_create_internal(key)

    instance = instance_or_awaitable
    if was_cached:
        if isinstance(instance, UnifiedComponentProxy):
            await instance._async_init_if_needed()
        return instance

    if inspect.isawaitable(instance_or_awaitable):
        instance = await instance_or_awaitable

    md = self._locator._metadata.get(key) if self._locator else None
    scope = md.scope if md else SCOPE_SINGLETON
    if scope != SCOPE_SINGLETON:
        instance_or_awaitable_configured = self._run_configure_methods(instance)
        if inspect.isawaitable(instance_or_awaitable_configured):
            instance = await instance_or_awaitable_configured
        else:
            instance = instance_or_awaitable_configured

    final_instance = self._maybe_wrap_with_aspects(key, instance)

    if isinstance(final_instance, UnifiedComponentProxy):
        await final_instance._async_init_if_needed()

    cache = self._cache_for(key)
    cache.put(key, final_instance)
    self.context.resolve_count += 1
    for o in self._observers:
        o.on_resolve(key, took_ms)

    return final_instance

cleanup_all()

Invoke all @cleanup methods on cached components (sync).

Source code in src/pico_ioc/container.py
def cleanup_all(self) -> None:
    """Invoke all ``@cleanup`` methods on cached components (sync)."""
    for obj in self._iterate_cleanup_targets():
        for _, m in inspect.getmembers(obj, predicate=inspect.ismethod):
            meta = getattr(m, PICO_META, {})
            if meta.get("cleanup", False):
                res = self._call_cleanup_method(m)
                if inspect.isawaitable(res):
                    LOGGER.warning(f"Async cleanup method {m} called during sync shutdown. Awaitable ignored.")

cleanup_all_async() async

Invoke all @cleanup methods on cached components (async).

Awaits async cleanup methods and closes the :class:EventBus if present.

Source code in src/pico_ioc/container.py
async def cleanup_all_async(self) -> None:
    """Invoke all ``@cleanup`` methods on cached components (async).

    Awaits async cleanup methods and closes the :class:`EventBus` if present.
    """
    for obj in self._iterate_cleanup_targets():
        for _, m in inspect.getmembers(obj, predicate=inspect.ismethod):
            meta = getattr(m, PICO_META, {})
            if meta.get("cleanup", False):
                res = self._call_cleanup_method(m)
                if inspect.isawaitable(res):
                    await res

    try:
        from .event_bus import EventBus

        for _, obj in self._caches.all_items():
            if isinstance(obj, EventBus):
                await obj.aclose()
    except Exception:
        pass

scope(name, scope_id)

Context manager that activates a scope for the duration of a block.

Parameters:

Name Type Description Default
name str

The scope name (e.g. "request").

required
scope_id Any

A unique identifier for this scope instance.

required

Yields:

Type Description

This container instance.

Example

with container.scope("request", request_id): ... ctx = container.get(RequestContext)

Source code in src/pico_ioc/container.py
@contextmanager
def scope(self, name: str, scope_id: Any):
    """Context manager that activates a scope for the duration of a block.

    Args:
        name: The scope name (e.g. ``"request"``).
        scope_id: A unique identifier for this scope instance.

    Yields:
        This container instance.

    Example:
        >>> with container.scope("request", request_id):
        ...     ctx = container.get(RequestContext)
    """
    tok = self.activate_scope(name, scope_id)
    try:
        yield self
    finally:
        self.deactivate_scope(name, tok)

health_check()

Run all @health-decorated methods and return their results.

Returns:

Type Description
Dict[str, bool]

Dict mapping "ClassName.method_name" to True/False.

Source code in src/pico_ioc/container.py
def health_check(self) -> Dict[str, bool]:
    """Run all ``@health``-decorated methods and return their results.

    Returns:
        Dict mapping ``"ClassName.method_name"`` to ``True``/``False``.
    """
    out: Dict[str, bool] = {}
    for k, obj in self._caches.all_items():
        for name, m in inspect.getmembers(obj, predicate=callable):
            if getattr(m, PICO_META, {}).get("health_check", False):
                try:
                    out[f"{getattr(k, '__name__', k)}.{name}"] = bool(m())
                except Exception:
                    out[f"{getattr(k, '__name__', k)}.{name}"] = False
    return out

stats()

Return container statistics.

Returns:

Type Description
Dict[str, Any]

Dict with keys container_id, profiles,

Dict[str, Any]

uptime_seconds, total_resolves, cache_hits,

Dict[str, Any]

cache_hit_rate, and registered_components.

Source code in src/pico_ioc/container.py
def stats(self) -> Dict[str, Any]:
    """Return container statistics.

    Returns:
        Dict with keys ``container_id``, ``profiles``,
        ``uptime_seconds``, ``total_resolves``, ``cache_hits``,
        ``cache_hit_rate``, and ``registered_components``.
    """
    import time as _t

    resolves = self.context.resolve_count
    hits = self.context.cache_hit_count
    total = resolves + hits
    return {
        "container_id": self.container_id,
        "profiles": self.context.profiles,
        "uptime_seconds": _t.time() - self.context.created_at,
        "total_resolves": resolves,
        "cache_hits": hits,
        "cache_hit_rate": (hits / total) if total > 0 else 0.0,
        "registered_components": len(self._locator._metadata) if self._locator else 0,
    }

shutdown()

Synchronously shut down the container.

Calls all @cleanup methods and removes the container from the global registry.

Source code in src/pico_ioc/container.py
def shutdown(self) -> None:
    """Synchronously shut down the container.

    Calls all ``@cleanup`` methods and removes the container from the
    global registry.
    """
    self.cleanup_all()
    PicoContainer._container_registry.pop(self.container_id, None)

ashutdown() async

Asynchronously shut down the container.

Awaits async @cleanup methods, closes the EventBus, and removes the container from the global registry.

Source code in src/pico_ioc/container.py
async def ashutdown(self) -> None:
    """Asynchronously shut down the container.

    Awaits async ``@cleanup`` methods, closes the ``EventBus``, and
    removes the container from the global registry.
    """
    await self.cleanup_all_async()
    PicoContainer._container_registry.pop(self.container_id, None)

build_resolution_graph()

Build the static dependency graph from registered metadata.

Returns:

Type Description

Dict mapping each key to a tuple of its dependency keys.

Source code in src/pico_ioc/container.py
def build_resolution_graph(self):
    """Build the static dependency graph from registered metadata.

    Returns:
        Dict mapping each key to a tuple of its dependency keys.
    """
    return _build_resolution_graph(self._locator)

export_graph(path, *, include_scopes=True, include_qualifiers=False, rankdir='LR', title=None)

Export the dependency graph as a Graphviz DOT file.

Parameters:

Name Type Description Default
path str

Filesystem path for the output .dot file.

required
include_scopes bool

Annotate nodes with their scope.

True
include_qualifiers bool

Annotate nodes with their qualifiers.

False
rankdir str

Graph layout direction ("LR" or "TB").

'LR'
title Optional[str]

Optional graph title.

None

Raises:

Type Description
RuntimeError

If no locator is attached to the container.

Source code in src/pico_ioc/container.py
def export_graph(
    self,
    path: str,
    *,
    include_scopes: bool = True,
    include_qualifiers: bool = False,
    rankdir: str = "LR",
    title: Optional[str] = None,
) -> None:
    """Export the dependency graph as a Graphviz DOT file.

    Args:
        path: Filesystem path for the output ``.dot`` file.
        include_scopes: Annotate nodes with their scope.
        include_qualifiers: Annotate nodes with their qualifiers.
        rankdir: Graph layout direction (``"LR"`` or ``"TB"``).
        title: Optional graph title.

    Raises:
        RuntimeError: If no locator is attached to the container.
    """
    _export_graph(
        self._locator,
        path,
        include_scopes=include_scopes,
        include_qualifiers=include_qualifiers,
        rankdir=rankdir,
        title=title,
    )