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: | required |
caches | ScopedCaches | The :class: | required |
scopes | ScopeManager | The :class: | required |
observers | Optional[List[ContainerObserver]] | Optional list of :class: | 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 | |
get_current() classmethod ¶
Return the container that is active in the current context, or None.
get_current_id() classmethod ¶
all_containers() classmethod ¶
Return a snapshot dict of all live containers, keyed by container ID.
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 |
|
Source code in src/pico_ioc/container.py
get(key) ¶
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: |
ComponentCreationError | If the provider fails during creation. |
Source code in src/pico_ioc/container.py
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
cleanup_all() ¶
Invoke all @cleanup methods on cached components (sync).
Source code in src/pico_ioc/container.py
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
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. | 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
health_check() ¶
Run all @health-decorated methods and return their results.
Returns:
| Type | Description |
|---|---|
Dict[str, bool] | Dict mapping |
Source code in src/pico_ioc/container.py
stats() ¶
Return container statistics.
Returns:
| Type | Description |
|---|---|
Dict[str, Any] | Dict with keys |
Dict[str, Any] |
|
Dict[str, Any] |
|
Source code in src/pico_ioc/container.py
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
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
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. |
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 | 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' |
title | Optional[str] | Optional graph title. | None |
Raises:
| Type | Description |
|---|---|
RuntimeError | If no locator is attached to the container. |