Skip to main content

A minimalist, zero-dependency Inversion of Control (IoC) container for Python.

Project description

📦 Pico-IoC: A Robust, Async-Native IoC Container for Python

PyPI Ask DeepWiki License: MIT CI (tox matrix) codecov Quality Gate Status Duplicated Lines (%) Maintainability Rating PyPI Downloads Docs Interactive Lab

Pico-IoC is a lightweight, async-ready, decorator-driven IoC container built for clarity, testability, and performance. It brings Inversion of Control and dependency injection to Python in a deterministic, modern, and framework-agnostic way.

🐍 Requires Python 3.10+


⚖️ Core Principles

  • Single Purpose – Do one thing: dependency management.
  • Declarative – Use simple decorators (@component, @factory, @provides, @configured) instead of complex config files.
  • Deterministic – No hidden scanning or side-effects; everything flows from an explicit init().
  • Async-Native – Fully supports async providers, async lifecycle hooks (__ainit__), and async interceptors.
  • Fail-Fast – Detects missing bindings and circular dependencies at bootstrap (init()).
  • Testable by Design – Use overrides and profiles to swap components instantly.
  • Zero Core Dependencies – Built entirely on the Python standard library. Optional features may require external packages (see Installation).

🚀 Why Pico-IoC?

As Python systems evolve, wiring dependencies by hand becomes fragile and unmaintainable. Pico-IoC eliminates that friction by letting you declare how components relate — not how they’re created.

Feature Manual Wiring With Pico-IoC
Object creation svc = Service(Repo(Config())) svc = container.get(Service)
Replacing deps Monkey-patch overrides={Repo: FakeRepo()}
Coupling Tight Loose
Testing Painful Instant
Async support Manual Built-in (aget, __ainit__)

🧩 Highlights (v2.0+)

  • Unified Configuration: Use @configured to bind both flat (ENV-like) and tree (YAML/JSON) sources via the configuration(...) builder (ADR-0010).
  • Async-aware AOP system: Method interceptors via @intercepted_by.
  • Scoped resolution: singleton, prototype, request, session, transaction, and custom scopes.
  • UnifiedComponentProxy: Transparent lazy=True and AOP proxy supporting serialization.
  • Tree-based configuration runtime: Advanced mapping with reusable adapters and discriminators (Annotated[Union[...], Discriminator(...)]).
  • Observable container context: Built-in stats, health checks (@health), observer hooks (ContainerObserver), dependency graph export (export_graph), and async cleanup.

📦 Installation

pip install pico-ioc

Optional extras:

  • YAML configuration support (requires PyYAML)

    pip install pico-ioc[yaml]
    

⚠️ Important Note for v2.1.3+

Breaking Behavior in Custom Integrations: As of version 2.1.3, Scope LRU Eviction has been removed to guarantee data integrity under high load.

  • If you use pico-fastapi: You are safe (the middleware handles cleanup automatically).
  • If you perform manual scope management: You must explicitly call container._caches.cleanup_scope("scope_name", scope_id) when a context ends. Failing to do so will result in a memory leak, as scopes are no longer automatically discarded when the container fills up.

⚙️ Quick Example (Unified Configuration)

import os
from dataclasses import dataclass
from pico_ioc import component, configured, configuration, init, EnvSource

# 1. Define configuration with @configured
@configured(prefix="APP_", mapping="auto")  # Auto-detects flat mapping
@dataclass
class Config:
    db_url: str = "sqlite:///demo.db"

# 2. Define components
@component
class Repo:
    def __init__(self, cfg: Config):  # Inject config
        self.cfg = cfg
    def fetch(self):
        return f"fetching from {self.cfg.db_url}"

@component
class Service:
    def __init__(self, repo: Repo):  # Inject Repo
        self.repo = repo
    def run(self):
        return self.repo.fetch()

# --- Example Setup ---
os.environ['APP_DB_URL'] = 'postgresql://user:pass@host/db'

# 3. Build configuration context
config_ctx = configuration(
    EnvSource(prefix="")  # Read APP_DB_URL from environment
)

# 4. Initialize container
container = init(modules=[__name__], config=config_ctx)  # Pass context via 'config'

# 5. Get and use the service
svc = container.get(Service)
print(svc.run())

# --- Cleanup ---
del os.environ['APP_DB_URL']

Output:

fetching from postgresql://user:pass@host/db

🧪 Testing with Overrides

class FakeRepo:
    def fetch(self): return "fake-data"

# Build configuration context (might be empty or specific for test)
test_config_ctx = configuration()

# Use overrides during init
container = init(
    modules=[__name__],
    config=test_config_ctx,
    overrides={Repo: FakeRepo()}  # Replace Repo with FakeRepo
)

svc = container.get(Service)
assert svc.run() == "fake-data"

🧰 Profiles

Use profiles to enable/disable components or configuration branches conditionally.

# Enable "test" profile when bootstrapping the container
container = init(
    modules=[__name__],
    profiles=["test"]
)

Profiles are typically referenced in decorators or configuration mappings to include/exclude components and bindings.


⚡ Async Components

Pico-IoC supports async lifecycle and resolution.

import asyncio
from pico_ioc import component, init

@component
class AsyncRepo:
    async def __ainit__(self):
        # e.g., open async connections
        self.ready = True

    async def fetch(self):
        return "async-data"

async def main():
    container = init(modules=[__name__])
    repo = await container.aget(AsyncRepo)   # Async resolution
    print(await repo.fetch())

asyncio.run(main())
  • __ainit__ runs after construction if defined.
  • Use container.aget(Type) to resolve components that require async initialization or whose providers are async.

🩺 Lifecycle & AOP

import time
from pico_ioc import component, init, intercepted_by, MethodInterceptor, MethodCtx

# Define an interceptor component
@component
class LogInterceptor(MethodInterceptor):
    def invoke(self, ctx: MethodCtx, call_next):
        print(f"→ calling {ctx.cls.__name__}.{ctx.name}")
        start = time.perf_counter()
        try:
            res = call_next(ctx)
            duration = (time.perf_counter() - start) * 1000
            print(f"← {ctx.cls.__name__}.{ctx.name} done ({duration:.2f}ms)")
            return res
        except Exception as e:
            duration = (time.perf_counter() - start) * 1000
            print(f"← {ctx.cls.__name__}.{ctx.name} failed ({duration:.2f}ms): {e}")
            raise

@component
class Demo:
    @intercepted_by(LogInterceptor)  # Apply the interceptor
    def work(self):
        print("   Working...")
        time.sleep(0.01)
        return "ok"

# Initialize container (must scan module containing interceptor too)
c = init(modules=[__name__])
result = c.get(Demo).work()
print(f"Result: {result}")

Output:

→ calling Demo.work
   Working...
← Demo.work done (10.xxms)
Result: ok

👁️ Observability & Cleanup

  • Export a dependency graph in DOT format:

    c = init(modules=[...])
    dot = c.export_graph()  # Returns DOT graph as a string
    with open("dependencies.dot", "w") as f:
        f.write(dot)
    
  • Health checks:

    • Annotate health probes inside components with @health for container-level reporting.
    • The container exposes health information that can be queried in observability tooling.
  • Container cleanup:

    • For sync components: container.close()
    • For async components/resources: await container.aclose()

Use cleanup in application shutdown hooks to release resources deterministically.


📖 Documentation

The full documentation is available within the docs/ directory of the project repository. Start with docs/README.md for navigation.

  • Getting Started: docs/getting-started.md
  • User Guide: docs/user-guide/README.md
  • Advanced Features: docs/advanced-features/README.md
  • Observability: docs/observability/README.md
  • Cookbook (Patterns): docs/cookbook/README.md
  • Architecture: docs/architecture/README.md
  • API Reference: docs/api-reference/README.md
  • ADR Index: docs/adr/README.md

🧩 Development

pip install tox
tox

🧾 Changelog

See CHANGELOG.md — Significant redesigns and features in v2.0+.


📜 License

MIT — LICENSE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pico_ioc-2.1.3.tar.gz (173.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pico_ioc-2.1.3-py3-none-any.whl (42.1 kB view details)

Uploaded Python 3

File details

Details for the file pico_ioc-2.1.3.tar.gz.

File metadata

  • Download URL: pico_ioc-2.1.3.tar.gz
  • Upload date:
  • Size: 173.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pico_ioc-2.1.3.tar.gz
Algorithm Hash digest
SHA256 27f25a919bd2cc6ab27fdaf8beb5098648810d03c0314ca703a68ddff0e73ac0
MD5 3addf1f44b37480447e8bc6a80ea5b01
BLAKE2b-256 3e4f6ebf85a4356a3f0b1aa3d981e959b3e894bf5ff2e87ce2e11a19588f8bc4

See more details on using hashes here.

File details

Details for the file pico_ioc-2.1.3-py3-none-any.whl.

File metadata

  • Download URL: pico_ioc-2.1.3-py3-none-any.whl
  • Upload date:
  • Size: 42.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pico_ioc-2.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 cf28dd8526475edf6ecd4407944ad39a1d9cd32e2081ebe97aa11c266944f6f3
MD5 9be2208152ac249773a8c8b2025b8f7f
BLAKE2b-256 430814bbac19262217f00a0c6d9a3cd26734767a8a0c83d6d5f0ce4e98b13b94

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page