API Reference¶
Complete API reference for Pico-Pydantic, auto-generated from source code docstrings.
Module Overview¶
| Module | Description |
|---|---|
pico_pydantic | Package exports and public API |
pico_pydantic.decorators | @validate decorator for Pydantic validation |
pico_pydantic.interceptor | Validation interceptor implementation |
pico_pydantic¶
pico_pydantic ¶
pico-pydantic: Declarative, AOP-based Pydantic validation for pico-ioc.
This package provides automatic argument validation for pico-ioc managed components using Pydantic BaseModel type hints. It intercepts method calls via AOP and validates arguments with TypeAdapter.validate_python() before the method body executes.
Public API
validate: Marker decorator that enables validation on a method. ValidationFailedError: Exception raised when argument validation fails. ValidationInterceptor: Singleton MethodInterceptor that performs validation.
Auto-discovery
Registered via the pico_boot.modules entry point. When using pico-boot, the ValidationInterceptor is auto-discovered and globally registered with the container.
Example
from pydantic import BaseModel, Field from pico_ioc import component from pico_pydantic import validate
class UserCreate(BaseModel): ... username: str = Field(min_length=3) ... email: str
@component ... class UserService: ... @validate ... async def create_user(self, data: UserCreate) -> dict: ... return data.model_dump()
ValidationFailedError ¶
Bases: ValueError
Exception raised when Pydantic validation fails on method arguments.
Wraps the underlying Pydantic ValidationError with the name of the method that triggered the failure. Inherits from ValueError so it can be caught broadly as a value-related error.
Attributes:
| Name | Type | Description |
|---|---|---|
method_name | The name of the method whose arguments failed validation. | |
pydantic_error | The original Pydantic |
Example
from pico_pydantic import ValidationFailedError try: ... await service.create_user({"username": "ab"}) ... except ValidationFailedError as e: ... print(e.method_name) # "create_user" ... print(e.pydantic_error) # Original ValidationError
Source code in src/pico_pydantic/decorators.py
__init__(method_name, pydantic_error) ¶
Initialize ValidationFailedError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method_name | str | The name of the method that failed validation. | required |
pydantic_error | Exception | The original Pydantic | required |
Source code in src/pico_pydantic/decorators.py
ValidationInterceptor ¶
Bases: MethodInterceptor
AOP interceptor that validates method arguments against Pydantic schemas.
Registered as a singleton component via pico-ioc. When a method decorated with @validate is called, this interceptor:
- Checks for the
@validatemarker on the target method. - Inspects the method signature for
BaseModeltype hints. - Validates each matching argument using
TypeAdapter(annotation).validate_python(value). - Replaces dict arguments with validated
BaseModelinstances. - Raises
ValidationFailedErrorif any argument fails validation.
Only parameters with BaseModel type hints (or generic types containing BaseModel, such as List[Model], Optional[Model], Union[Model, ...]) are validated. Parameters without annotations or with non-Pydantic types (str, int, etc.) are passed through.
Auto-discovery
Registered via the pico_boot.modules entry point. No manual registration is needed when using pico-boot.
Example
from pydantic import BaseModel from pico_ioc import component from pico_pydantic import validate
class UserData(BaseModel): ... name: str ... age: int
@component ... class UserService: ... @validate ... async def create(self, data: UserData) -> dict: ... return data.model_dump()
Dicts are automatically converted to UserData instances:¶
await service.create({"name": "alice", "age": 30})¶
Source code in src/pico_pydantic/interceptor.py
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 | |
invoke(ctx, call_next) async ¶
Intercept a method call and validate arguments if marked.
This is the main entry point called by pico-ioc's interceptor chain. If the target method has the @validate marker, its arguments are validated and transformed before proceeding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx | MethodCtx | The method invocation context provided by pico-ioc, containing the target class, method name, args, and kwargs. | required |
call_next | Callable[[MethodCtx], Any] | Callable to invoke the next interceptor or the actual method in the chain. | required |
Returns:
| Type | Description |
|---|---|
Any | The return value of the target method (or next interceptor). |
Raises:
| Type | Description |
|---|---|
ValidationFailedError | If any argument with a |
Source code in src/pico_pydantic/interceptor.py
validate(func) ¶
Marker decorator that enables Pydantic validation on a method.
Marks the decorated function with a hidden metadata attribute (_pico_pydantic_validate_meta) so the ValidationInterceptor knows to inspect and validate its arguments at call time.
This decorator does not contain validation logic itself. It is intentionally lightweight to keep import times fast and to delegate the heavy lifting to the interceptor, which has access to the full IoC context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func | T | The function or method to mark for validation. | required |
Returns:
| Type | Description |
|---|---|
T | The same function, unmodified except for the added metadata attribute. |
Example
from pico_ioc import component from pico_pydantic import validate from pydantic import BaseModel
class ItemData(BaseModel): ... name: str ... price: float
@component ... class ItemService: ... @validate ... async def add_item(self, data: ItemData) -> dict: ... return data.model_dump()
Source code in src/pico_pydantic/decorators.py
Decorators¶
pico_pydantic.decorators ¶
Decorators and exceptions for pico-pydantic validation.
This module provides
- The
@validatemarker decorator that flags methods for argument validation by theValidationInterceptor. - The
ValidationFailedErrorexception raised when Pydantic validation fails on a method argument.
VALIDATE_META = '_pico_pydantic_validate_meta' module-attribute ¶
str: Hidden attribute name set on functions by @validate.
The ValidationInterceptor checks for this attribute to determine whether a method should undergo argument validation.
ValidationFailedError ¶
Bases: ValueError
Exception raised when Pydantic validation fails on method arguments.
Wraps the underlying Pydantic ValidationError with the name of the method that triggered the failure. Inherits from ValueError so it can be caught broadly as a value-related error.
Attributes:
| Name | Type | Description |
|---|---|---|
method_name | The name of the method whose arguments failed validation. | |
pydantic_error | The original Pydantic |
Example
from pico_pydantic import ValidationFailedError try: ... await service.create_user({"username": "ab"}) ... except ValidationFailedError as e: ... print(e.method_name) # "create_user" ... print(e.pydantic_error) # Original ValidationError
Source code in src/pico_pydantic/decorators.py
__init__(method_name, pydantic_error) ¶
Initialize ValidationFailedError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method_name | str | The name of the method that failed validation. | required |
pydantic_error | Exception | The original Pydantic | required |
Source code in src/pico_pydantic/decorators.py
validate(func) ¶
Marker decorator that enables Pydantic validation on a method.
Marks the decorated function with a hidden metadata attribute (_pico_pydantic_validate_meta) so the ValidationInterceptor knows to inspect and validate its arguments at call time.
This decorator does not contain validation logic itself. It is intentionally lightweight to keep import times fast and to delegate the heavy lifting to the interceptor, which has access to the full IoC context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func | T | The function or method to mark for validation. | required |
Returns:
| Type | Description |
|---|---|
T | The same function, unmodified except for the added metadata attribute. |
Example
from pico_ioc import component from pico_pydantic import validate from pydantic import BaseModel
class ItemData(BaseModel): ... name: str ... price: float
@component ... class ItemService: ... @validate ... async def add_item(self, data: ItemData) -> dict: ... return data.model_dump()
Source code in src/pico_pydantic/decorators.py
Interceptor¶
pico_pydantic.interceptor ¶
AOP validation interceptor for pico-ioc managed components.
This module implements the ValidationInterceptor, a singleton MethodInterceptor that inspects method signatures for Pydantic BaseModel type hints and validates arguments using TypeAdapter.validate_python() before the method body executes.
Helper functions are extracted at module level to keep cyclomatic complexity low: - _bind_arguments: Binds positional/keyword args to a signature. - _should_skip_param: Determines if a parameter should bypass validation. - _is_basemodel_class: Checks if an annotation is a BaseModel subclass. - _has_pydantic_in_args: Recursively checks generic __args__ for BaseModel types.
ValidationInterceptor ¶
Bases: MethodInterceptor
AOP interceptor that validates method arguments against Pydantic schemas.
Registered as a singleton component via pico-ioc. When a method decorated with @validate is called, this interceptor:
- Checks for the
@validatemarker on the target method. - Inspects the method signature for
BaseModeltype hints. - Validates each matching argument using
TypeAdapter(annotation).validate_python(value). - Replaces dict arguments with validated
BaseModelinstances. - Raises
ValidationFailedErrorif any argument fails validation.
Only parameters with BaseModel type hints (or generic types containing BaseModel, such as List[Model], Optional[Model], Union[Model, ...]) are validated. Parameters without annotations or with non-Pydantic types (str, int, etc.) are passed through.
Auto-discovery
Registered via the pico_boot.modules entry point. No manual registration is needed when using pico-boot.
Example
from pydantic import BaseModel from pico_ioc import component from pico_pydantic import validate
class UserData(BaseModel): ... name: str ... age: int
@component ... class UserService: ... @validate ... async def create(self, data: UserData) -> dict: ... return data.model_dump()
Dicts are automatically converted to UserData instances:¶
await service.create({"name": "alice", "age": 30})¶
Source code in src/pico_pydantic/interceptor.py
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 | |
invoke(ctx, call_next) async ¶
Intercept a method call and validate arguments if marked.
This is the main entry point called by pico-ioc's interceptor chain. If the target method has the @validate marker, its arguments are validated and transformed before proceeding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx | MethodCtx | The method invocation context provided by pico-ioc, containing the target class, method name, args, and kwargs. | required |
call_next | Callable[[MethodCtx], Any] | Callable to invoke the next interceptor or the actual method in the chain. | required |
Returns:
| Type | Description |
|---|---|
Any | The return value of the target method (or next interceptor). |
Raises:
| Type | Description |
|---|---|
ValidationFailedError | If any argument with a |