Decorators
plateforme.core.schema.decorators
This module provides utilities for managing schema decorators within the Plateforme framework using Pydantic features.
PlainSerializer
dataclass
PlainSerializer(
func: SerializerFunction,
return_type: Any = PydanticUndefined,
when_used: Literal[
"always", "unless-none", "json", "json-unless-none"
] = "always",
)
Plain serializers use a function to modify the output of serialization.
This is particularly helpful when you want to customize the serialization for annotated types.
Consider an input of list
, which will be serialized into a space-delimited string.
from typing import List
from typing_extensions import Annotated
from pydantic import BaseModel, PlainSerializer
CustomStr = Annotated[
List, PlainSerializer(lambda x: ' '.join(x), return_type=str)
]
class StudentModel(BaseModel):
courses: CustomStr
student = StudentModel(courses=['Math', 'Chemistry', 'English'])
print(student.model_dump())
#> {'courses': 'Math Chemistry English'}
Attributes:
Name | Type | Description |
---|---|---|
func |
SerializerFunction
|
The serializer function. |
return_type |
Any
|
The return type for the function. If omitted it will be inferred from the type annotation. |
when_used |
Literal['always', 'unless-none', 'json', 'json-unless-none']
|
Determines when this serializer should be used. Accepts a string with values |
WrapSerializer
dataclass
WrapSerializer(
func: WrapSerializerFunction,
return_type: Any = PydanticUndefined,
when_used: Literal[
"always", "unless-none", "json", "json-unless-none"
] = "always",
)
Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization logic, and can modify the resulting value before returning it as the final output of serialization.
For example, here's a scenario in which a wrap serializer transforms timezones to UTC and utilizes the existing datetime
serialization logic.
from datetime import datetime, timezone
from typing import Any, Dict
from typing_extensions import Annotated
from pydantic import BaseModel, WrapSerializer
class EventDatetime(BaseModel):
start: datetime
end: datetime
def convert_to_utc(value: Any, handler, info) -> Dict[str, datetime]:
# Note that `helper` can actually help serialize the `value` for further custom serialization in case it's a subclass.
partial_result = handler(value, info)
if info.mode == 'json':
return {
k: datetime.fromisoformat(v).astimezone(timezone.utc)
for k, v in partial_result.items()
}
return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()}
UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)]
class EventModel(BaseModel):
event_datetime: UTCEventDatetime
dt = EventDatetime(
start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00'
)
event = EventModel(event_datetime=dt)
print(event.model_dump())
'''
{
'event_datetime': {
'start': datetime.datetime(
2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc
),
'end': datetime.datetime(
2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc
),
}
}
'''
print(event.model_dump_json())
'''
{"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}}
'''
Attributes:
Name | Type | Description |
---|---|---|
func |
WrapSerializerFunction
|
The serializer function to be wrapped. |
return_type |
Any
|
The return type for the function. If omitted it will be inferred from the type annotation. |
when_used |
Literal['always', 'unless-none', 'json', 'json-unless-none']
|
Determines when this serializer should be used. Accepts a string with values |
AfterValidator
dataclass
Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied after the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
NoInfoValidatorFunction | WithInfoValidatorFunction
|
The validator function. |
Example
from typing_extensions import Annotated
from pydantic import AfterValidator, BaseModel, ValidationError
MyInt = Annotated[int, AfterValidator(lambda v: v + 1)]
class Model(BaseModel):
a: MyInt
print(Model(a=1).a)
#> 2
try:
Model(a='a')
except ValidationError as e:
print(e.json(indent=2))
'''
[
{
"type": "int_parsing",
"loc": [
"a"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "a",
"url": "https://errors.pydantic.dev/2/v/int_parsing"
}
]
'''
BeforeValidator
dataclass
Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied before the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
NoInfoValidatorFunction | WithInfoValidatorFunction
|
The validator function. |
Example
InstanceOf
dataclass
Generic type for annotating a type that is an instance of a given class.
Example
from pydantic import BaseModel, InstanceOf
class Foo:
...
class Bar(BaseModel):
foo: InstanceOf[Foo]
Bar(foo=Foo())
try:
Bar(foo=42)
except ValidationError as e:
print(e)
"""
[
│ {
│ │ 'type': 'is_instance_of',
│ │ 'loc': ('foo',),
│ │ 'msg': 'Input should be an instance of Foo',
│ │ 'input': 42,
│ │ 'ctx': {'class': 'Foo'},
│ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of'
│ }
]
"""
PlainValidator
dataclass
Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied instead of the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
NoInfoValidatorFunction | WithInfoValidatorFunction
|
The validator function. |
Example
SkipValidation
dataclass
If this is applied as an annotation (e.g., via x: Annotated[int, SkipValidation]
), validation will be
skipped. You can also use SkipValidation[int]
as a shorthand for Annotated[int, SkipValidation]
.
This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes, and know that it is safe to skip validation for one or more of the fields.
Because this converts the validation schema to any_schema
, subsequent annotation-applied transformations
may not have the expected effects. Therefore, when used, this annotation should generally be the final
annotation applied to a type.
WrapValidator
dataclass
Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied around the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
NoInfoWrapValidatorFunction | WithInfoWrapValidatorFunction
|
The validator function. |
from datetime import datetime
from typing_extensions import Annotated
from pydantic import BaseModel, ValidationError, WrapValidator
def validate_timestamp(v, handler):
if v == 'now':
# we don't want to bother with further validation, just return the new value
return datetime.now()
try:
return handler(v)
except ValidationError:
# validation failed, in this case we want to return a default value
return datetime(2000, 1, 1)
MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
class Model(BaseModel):
a: MyTimestamp
print(Model(a='now').a)
#> 2032-01-02 03:04:05.000006
print(Model(a='invalid').a)
#> 2000-01-01 00:00:00
RecursiveGuard
A recursive guard for schema validation in model field annotations.
Initialize the recursive guard.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
str | None
|
The value to add to the recursion context. If set to
|
None
|
mode
|
Literal['lax', 'omit', 'raise']
|
The mode for handling recursion errors. It can be either:
- |
'raise'
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/decorators.py
field_serializer
field_serializer(
__field: str,
*fields: str,
return_type: Any = ...,
when_used: Literal[
"always", "unless-none", "json", "json-unless-none"
] = ...,
check_fields: bool | None = ...,
) -> Callable[
[_PlainSerializeMethodType], _PlainSerializeMethodType
]
field_serializer(
*fields: str,
mode: Literal["plain", "wrap"] = "plain",
return_type: Any = PydanticUndefined,
when_used: Literal[
"always", "unless-none", "json", "json-unless-none"
] = "always",
check_fields: bool | None = None,
) -> Callable[[Any], Any]
Decorator that enables custom field serialization.
In the below example, a field of type set
is used to mitigate duplication. A field_serializer
is used to serialize the data as a sorted list.
from typing import Set
from pydantic import BaseModel, field_serializer
class StudentModel(BaseModel):
name: str = 'Jane'
courses: Set[str]
@field_serializer('courses', when_used='json')
def serialize_courses_in_order(courses: Set[str]):
return sorted(courses)
student = StudentModel(courses={'Math', 'Chemistry', 'English'})
print(student.model_dump_json())
#> {"name":"Jane","courses":["Chemistry","English","Math"]}
See Custom serializers for more information.
Four signatures are supported:
(self, value: Any, info: FieldSerializationInfo)
(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)
(value: Any, info: SerializationInfo)
(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fields
|
str
|
Which field(s) the method should be called on. |
()
|
mode
|
Literal['plain', 'wrap']
|
The serialization mode.
|
'plain'
|
return_type
|
Any
|
Optional return type for the function, if omitted it will be inferred from the type annotation. |
PydanticUndefined
|
when_used
|
Literal['always', 'unless-none', 'json', 'json-unless-none']
|
Determines the serializer will be used for serialization. |
'always'
|
check_fields
|
bool | None
|
Whether to check that the fields actually exist on the model. |
None
|
Returns:
Type | Description |
---|---|
Callable[[Any], Any]
|
The decorator function. |
Source code in .venv/lib/python3.12/site-packages/pydantic/functional_serializers.py
model_serializer
model_serializer(
__f: Callable[..., Any] | None = None,
*,
mode: Literal["plain", "wrap"] = "plain",
when_used: Literal[
"always", "unless-none", "json", "json-unless-none"
] = "always",
return_type: Any = PydanticUndefined,
) -> Callable[[Any], Any]
Decorator that enables custom model serialization.
This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields.
An example would be to serialize temperature to the same temperature scale, such as degrees Celsius.
from typing import Literal
from pydantic import BaseModel, model_serializer
class TemperatureModel(BaseModel):
unit: Literal['C', 'F']
value: int
@model_serializer()
def serialize_model(self):
if self.unit == 'F':
return {'unit': 'C', 'value': int((self.value - 32) / 1.8)}
return {'unit': self.unit, 'value': self.value}
temperature = TemperatureModel(unit='F', value=212)
print(temperature.model_dump())
#> {'unit': 'C', 'value': 100}
See Custom serializers for more information.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__f
|
Callable[..., Any] | None
|
The function to be decorated. |
None
|
mode
|
Literal['plain', 'wrap']
|
The serialization mode.
|
'plain'
|
when_used
|
Literal['always', 'unless-none', 'json', 'json-unless-none']
|
Determines when this serializer should be used. |
'always'
|
return_type
|
Any
|
The return type for the function. If omitted it will be inferred from the type annotation. |
PydanticUndefined
|
Returns:
Type | Description |
---|---|
Callable[[Any], Any]
|
The decorator function. |
Source code in .venv/lib/python3.12/site-packages/pydantic/functional_serializers.py
field_validator
field_validator(
__field: str,
*fields: str,
mode: FieldValidatorModes = "after",
check_fields: bool | None = None,
) -> Callable[[Any], Any]
Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#field-validators
Decorate methods on the class indicating that they should be used to validate fields.
Example usage:
from typing import Any
from pydantic import (
BaseModel,
ValidationError,
field_validator,
)
class Model(BaseModel):
a: str
@field_validator('a')
@classmethod
def ensure_foobar(cls, v: Any):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
print(repr(Model(a='this is foobar good')))
#> Model(a='this is foobar good')
try:
Model(a='snap')
except ValidationError as exc_info:
print(exc_info)
'''
1 validation error for Model
a
Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str]
'''
For more in depth examples, see Field Validators.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__field
|
str
|
The first field the |
required |
*fields
|
str
|
Additional field(s) the |
()
|
mode
|
FieldValidatorModes
|
Specifies whether to validate the fields before or after validation. |
'after'
|
check_fields
|
bool | None
|
Whether to check that the fields actually exist on the model. |
None
|
Returns:
Type | Description |
---|---|
Callable[[Any], Any]
|
A decorator that can be used to decorate a function to be used as a field_validator. |
Raises:
Type | Description |
---|---|
PydanticUserError
|
|
Source code in .venv/lib/python3.12/site-packages/pydantic/functional_validators.py
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 |
|
model_validator
model_validator(
*, mode: Literal["wrap"]
) -> Callable[
[_AnyModelWrapValidator[_ModelType]],
PydanticDescriptorProxy[ModelValidatorDecoratorInfo],
]
model_validator(
*, mode: Literal["before"]
) -> Callable[
[_AnyModeBeforeValidator],
PydanticDescriptorProxy[ModelValidatorDecoratorInfo],
]
model_validator(
*, mode: Literal["after"]
) -> Callable[
[_AnyModelAfterValidator[_ModelType]],
PydanticDescriptorProxy[ModelValidatorDecoratorInfo],
]
model_validator(
*, mode: Literal["wrap", "before", "after"]
) -> Any
Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#model-validators
Decorate model methods for validation purposes.
Example usage:
from typing_extensions import Self
from pydantic import BaseModel, ValidationError, model_validator
class Square(BaseModel):
width: float
height: float
@model_validator(mode='after')
def verify_square(self) -> Self:
if self.width != self.height:
raise ValueError('width and height do not match')
return self
s = Square(width=1, height=1)
print(repr(s))
#> Square(width=1.0, height=1.0)
try:
Square(width=1, height=2)
except ValidationError as e:
print(e)
'''
1 validation error for Square
Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict]
'''
For more in depth examples, see Model Validators.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode
|
Literal['wrap', 'before', 'after']
|
A required string literal that specifies the validation mode. It can be one of the following: 'wrap', 'before', or 'after'. |
required |
Returns:
Type | Description |
---|---|
Any
|
A decorator that can be used to decorate a function to be used as a model validator. |
Source code in .venv/lib/python3.12/site-packages/pydantic/functional_validators.py
validate_call
validate_call(
*,
config: ConfigDict | None = None,
validate_return: bool = False,
) -> Callable[[AnyCallableT], AnyCallableT]
validate_call(
__func: AnyCallableT | None = None,
*,
config: ConfigDict | None = None,
validate_return: bool = False,
) -> AnyCallableT | Callable[[AnyCallableT], AnyCallableT]
Usage docs: https://docs.pydantic.dev/2.6/concepts/validation_decorator/
Returns a decorated wrapper around the function that validates the arguments and, optionally, the return value.
Usage may be either as a plain decorator @validate_call
or with arguments @validate_call(...)
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__func
|
AnyCallableT | None
|
The function to be decorated. |
None
|
config
|
ConfigDict | None
|
The configuration dictionary. |
None
|
validate_return
|
bool
|
Whether to validate the return value. |
False
|
Returns:
Type | Description |
---|---|
AnyCallableT | Callable[[AnyCallableT], AnyCallableT]
|
The decorated function. |