Skip to main content

pico-pydantic

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

Pico-Pydantic

Pico-Pydantic integrates Pico-IoC with Pydantic, enabling declarative, aspect-oriented validation of method arguments within your service layer.

It uses Pico-IoC's MethodInterceptor system to perform validation based on Pydantic BaseModel type hints before your method's business logic runs. This is the ideal tool for ensuring arguments passed between IoC-managed services are structurally correct.

Requires Python 3.11+ (tested on 3.11, 3.12, 3.13 and 3.14) Works with Pydantic 2.0+ Supports async and sync methods Enables unit testing of validation separate from business logic


Why pico-pydantic

While web frameworks handle validation at the HTTP boundary, business services often need to guarantee input integrity internally, especially when components are called from CLI tools, workers, or other services.

Pico-Pydantic provides:

  • Declarative @validate boundaries for service methods.
  • Aspect-Oriented Programming (AOP) for argument validation.
  • Clear error handling with ValidationFailedError.
  • Centralized validation logic, decoupled from the core service code.
Concern Pico-IoC Default pico-pydantic
Argument checking Manual if/raise Declarative @validate
Schema definition None Pydantic BaseModel type hints
Handling errors Raw ValidationError Wrapped ValidationFailedError

Core Features

  • Method validation via @validate decorator.
  • ValidationInterceptor for AOP execution.
  • Seamless compatibility with BaseModel type annotations.
  • Correct handling of positional, keyword, and default arguments.
  • Zero coupling to web frameworks.

Installation

pip install pico-pydantic

Quick Example

1. Define the Data Model and Service:

from pydantic import BaseModel, Field
from pico_ioc import component
from pico_pydantic import validate

class ItemData(BaseModel):
    name: str = Field(min_length=3)
    price: float = Field(gt=0)

@component
class InventoryService:
    @validate
    async def add_item(self, data: ItemData) -> dict:
        # Validation happens BEFORE this line
        print(f"Adding item: {data.name}")
        return data.model_dump()

2. Full Example: Initialization, Success, and Failure Handling

import asyncio
from pico_boot import init
from pico_pydantic import ValidationFailedError

# 'components' is used here as the module containing InventoryService.
container = init(modules=["components"])

async def main():
    service = container.get(InventoryService)

    # --- Success: Validation Passes ---
    print("--- Testing Success ---")
    result = await service.add_item({"name": "Hammer", "price": 10.50})
    print(f"Result: {result}")
    
    # --- Failure: ValidationFailedError is thrown by the Interceptor ---
    print("\n--- Testing Failure ---")
    try:
        # Fails: 'price' is negative, violating Field(gt=0)
        await service.add_item({"name": "A", "price": -5})
    except ValidationFailedError as e:
        print(f"Validation failed for method '{e.method_name}'.")
        print(e.pydantic_error) # Shows the detailed Pydantic error
    
    await container.cleanup_all_async()
    container.shutdown()

if __name__ == "__main__":
    asyncio.run(main())

How It Works

  • The @validate decorator attaches ValidationInterceptor to the method's AOP chain via @intercepted_by.
  • When the method is called:
  • The interceptor captures the call arguments.
  • It inspects the method signature for arguments with the BaseModel type hint.
  • It validates each argument using TypeAdapter.validate_python(value).
  • If validation fails, it wraps the error in ValidationFailedError and stops execution.
  • If successful, call_next is executed, and the original method runs.

No manual checks inside the service method. Logic stays clean.


Architecture Overview

                 ┌─────────────────────────────┐
                 │         Your App            │
                 │ (Service Layer)             │
                 └──────────────┬──────────────┘
                                │
                        @validate called
                                │
                 ┌──────────────▼───────────────┐
                 │          Pico-IoC            │
                 └──────────────┬───────────────┘
                                │
                    ValidationInterceptor (AOP)
                                │
                 ┌──────────────▼───────────────┐
                 │         pico-pydantic        │
                 │  Inspect & validate_python()  │
                 └──────────────┬───────────────┘
                                │
                             Pydantic 2.0+

Built for AI-assisted development

pico-pydantic is part of an ecosystem designed for humans and coding agents building software together. Every package ships AGENTS.md working conventions, an llms.txt machine-readable docs index and documented behaviour pinned by regression tests; pico-testing gives agents a verification loop for their own changes, and releases are gated by the whole ecosystem booting together against real infrastructure. The full story: Built for AI-assisted development.

Install the agent skills for Claude Code or OpenAI Codex:

curl -sL https://raw.githubusercontent.com/dperezcabrera/pico-skills/main/install.sh | bash -s -- pydantic
Command Description
/add-validation Add Pydantic validation to component methods
/add-component Add components, factories, interceptors, settings
/add-tests Generate tests for pico components

All skills: curl -sL https://raw.githubusercontent.com/dperezcabrera/pico-skills/main/install.sh | bash

See pico-skills for details.


License

MIT

Metadata

Release files for pico-pydantic 0.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pico-pydantic 0.2.4
File Size Uploaded
pico_pydantic-0.2.4.tar.gz 42.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pico-pydantic 0.2.4
File Interpreter ABI Platform
pico_pydantic-0.2.4-py3-none-any.whl Python 3 none any Details

Total release size: 54.9 kB

Release files / pico_pydantic-0.2.4.tar.gz

Download URL pico_pydantic-0.2.4.tar.gz
Size 42.9 kB
Tags Source
SHA-256 checksum
How to use checksums
2158f121c65b2c3044453240bf2058e0300e64c3a18302dcfc97e7167a915c61
BLAKE2b-256 checksum
How to use checksums
4365171c539bded7a980cd4e1f9322236abe4e1740cce8d79dd6f08758029975
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 29, 2026.

Transparency log

Release files / pico_pydantic-0.2.4-py3-none-any.whl

Download URL pico_pydantic-0.2.4-py3-none-any.whl
Size 12.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f10fd02a64a1e650f7dce3cfc2dbbb57ed8b467bd8fbfa3741970b2cf4680924
BLAKE2b-256 checksum
How to use checksums
0cd6fd77d0e938843b93aca3432a91c0b1c21fcdb3e061ae4a32b5887ac3f658
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 29, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.4 This release

2 release files

0.2.3

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page