Coverage for pydantic-core / python / pydantic_core / core_schema.py: 99.38%
945 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
1"""
2This module contains definitions to build schemas which `pydantic_core` can
3validate and serialize.
4"""
6from __future__ import annotations as _annotations 1abcdefghijklsmnopqr
8import sys 1abcdefghijklsmnopqr
9from collections.abc import Callable, Generator, Mapping 1abcdefghijklsmnopqr
10from datetime import date, datetime, time, timedelta 1abcdefghijklsmnopqr
11from decimal import Decimal 1abcdefghijklsmnopqr
12from fractions import Fraction 1abcdefghijklsmnopqr
13from re import Pattern 1abcdefghijklsmnopqr
14from typing import TYPE_CHECKING, Any, Literal, Required, TypeAlias, Union 1abcdefghijklsmnopqr
16from typing_extensions import Protocol, TypeVar, deprecated 1abcdefghijklsmnopqr
18if sys.version_info < (3, 12): 1abcdefghijklsmnopqr
19 from typing_extensions import TypedDict 1agm
20else:
21 from typing import TypedDict 1bcdefhijklsnopqr
23if TYPE_CHECKING: 1abcdefghijklsmnopqr
24 from pydantic_core import PydanticUndefined
25else:
26 # The initial build of pydantic_core requires PydanticUndefined to generate
27 # the core schema; so we need to conditionally skip it. mypy doesn't like
28 # this at all, hence the TYPE_CHECKING branch above.
29 try: 1abcdefghijklsmnopqr
30 from pydantic_core import PydanticUndefined 1abcdefghijklsmnopqr
31 except ImportError:
32 PydanticUndefined = object()
35ExtraBehavior: TypeAlias = Literal['allow', 'forbid', 'ignore'] 1abcdefghijklsmnopqr
38class CoreConfig(TypedDict, total=False): 1abcdefghijklsmnopqr
39 """
40 Base class for schema configuration options.
42 Attributes:
43 title: The name of the configuration.
44 strict: Whether the configuration should strictly adhere to specified rules.
45 extra_fields_behavior: The behavior for handling extra fields.
46 typed_dict_total: Whether the TypedDict should be considered total. Default is `True`.
47 from_attributes: Whether to use attributes for models, dataclasses, and tagged union keys.
48 loc_by_alias: Whether to use the used alias (or first alias for "field required" errors) instead of
49 `field_names` to construct error `loc`s. Default is `True`.
50 revalidate_instances: Whether instances of models and dataclasses should re-validate. Default is 'never'.
51 validate_default: Whether to validate default values during validation. Default is `False`.
52 str_max_length: The maximum length for string fields.
53 str_min_length: The minimum length for string fields.
54 str_strip_whitespace: Whether to strip whitespace from string fields.
55 str_to_lower: Whether to convert string fields to lowercase.
56 str_to_upper: Whether to convert string fields to uppercase.
57 allow_inf_nan: Whether to allow infinity and NaN values for float fields. Default is `True`.
58 ser_json_timedelta: The serialization option for `timedelta` values. Default is 'iso8601'.
59 Note that if ser_json_temporal is set, then this param will be ignored.
60 ser_json_temporal: The serialization option for datetime like values. Default is 'iso8601'.
61 The types this covers are datetime, date, time and timedelta.
62 If this is set, it will take precedence over ser_json_timedelta
63 ser_json_bytes: The serialization option for `bytes` values. Default is 'utf8'.
64 ser_json_inf_nan: The serialization option for infinity and NaN values
65 in float fields. Default is 'null'.
66 val_json_bytes: The validation option for `bytes` values, complementing ser_json_bytes. Default is 'utf8'.
67 hide_input_in_errors: Whether to hide input data from `ValidationError` representation.
68 validation_error_cause: Whether to add user-python excs to the __cause__ of a ValidationError.
69 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
70 regex_engine: The regex engine to use for regex pattern validation. Default is 'rust-regex'. See `StringSchema`.
71 cache_strings: Whether to cache strings. Default is `True`, `True` or `'all'` is required to cache strings
72 during general validation since validators don't know if they're in a key or a value.
73 validate_by_alias: Whether to use the field's alias when validating against the provided input data. Default is `True`.
74 validate_by_name: Whether to use the field's name when validating against the provided input data. Default is `False`. Replacement for `populate_by_name`.
75 serialize_by_alias: Whether to serialize by alias. Default is `False`, expected to change to `True` in V3.
76 polymorphic_serialization: Whether to enable polymorphic serialization for models and dataclasses. Default is `False`.
77 url_preserve_empty_path: Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`.
78 """
80 title: str 1abcdefghijklsmnopqr
81 strict: bool 1abcdefghijklsmnopqr
82 # settings related to typed dicts, model fields, dataclass fields
83 extra_fields_behavior: ExtraBehavior 1abcdefghijklsmnopqr
84 typed_dict_total: bool # default: True 1abcdefghijklsmnopqr
85 # used for models, dataclasses, and tagged union keys
86 from_attributes: bool 1abcdefghijklsmnopqr
87 # whether to use the used alias (or first alias for "field required" errors) instead of field_names
88 # to construct error `loc`s, default True
89 loc_by_alias: bool 1abcdefghijklsmnopqr
90 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
91 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 1abcdefghijklsmnopqr
92 # whether to validate default values during validation, default False
93 validate_default: bool 1abcdefghijklsmnopqr
94 # used on typed-dicts and arguments
95 # fields related to string fields only
96 str_max_length: int 1abcdefghijklsmnopqr
97 str_min_length: int 1abcdefghijklsmnopqr
98 str_strip_whitespace: bool 1abcdefghijklsmnopqr
99 str_to_lower: bool 1abcdefghijklsmnopqr
100 str_to_upper: bool 1abcdefghijklsmnopqr
101 # fields related to float fields only
102 allow_inf_nan: bool # default: True 1abcdefghijklsmnopqr
103 # the config options are used to customise serialization to JSON
104 ser_json_timedelta: Literal['iso8601', 'float'] # default: 'iso8601' 1abcdefghijklsmnopqr
105 ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds'] # default: 'iso8601' 1abcdefghijklsmnopqr
106 ser_json_bytes: Literal['utf8', 'base64', 'hex'] # default: 'utf8' 1abcdefghijklsmnopqr
107 ser_json_inf_nan: Literal['null', 'constants', 'strings'] # default: 'null' 1abcdefghijklsmnopqr
108 val_json_bytes: Literal['utf8', 'base64', 'hex'] # default: 'utf8' 1abcdefghijklsmnopqr
109 # used to hide input data from ValidationError repr
110 hide_input_in_errors: bool 1abcdefghijklsmnopqr
111 validation_error_cause: bool # default: False 1abcdefghijklsmnopqr
112 coerce_numbers_to_str: bool # default: False 1abcdefghijklsmnopqr
113 regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex' 1abcdefghijklsmnopqr
114 cache_strings: bool | Literal['all', 'keys', 'none'] # default: 'True' 1abcdefghijklsmnopqr
115 validate_by_alias: bool # default: True 1abcdefghijklsmnopqr
116 validate_by_name: bool # default: False 1abcdefghijklsmnopqr
117 serialize_by_alias: bool # default: False 1abcdefghijklsmnopqr
118 polymorphic_serialization: bool # default: False 1abcdefghijklsmnopqr
119 url_preserve_empty_path: bool # default: False 1abcdefghijklsmnopqr
122IncExCall: TypeAlias = 'set[int | str] | dict[int | str, IncExCall] | None' 1abcdefghijklsmnopqr
124ContextT = TypeVar('ContextT', covariant=True, default='Any | None') # noqa: PLC0105 1abcdefghijklsmnopqr
127class SerializationInfo(Protocol[ContextT]): 1abcdefghijklsmnopqr
128 """Extra data used during serialization."""
130 @property 1abcdefghijklsmnopqr
131 def include(self) -> IncExCall: 1abcdefghijklsmnopqr
132 """The `include` argument set during serialization."""
133 ...
135 @property 1abcdefghijklsmnopqr
136 def exclude(self) -> IncExCall: 1abcdefghijklsmnopqr
137 """The `exclude` argument set during serialization."""
138 ...
140 @property 1abcdefghijklsmnopqr
141 def context(self) -> ContextT: 1abcdefghijklsmnopqr
142 """The current serialization context."""
143 ...
145 @property 1abcdefghijklsmnopqr
146 def mode(self) -> Literal['python', 'json'] | str: 1abcdefghijklsmnopqr
147 """The serialization mode set during serialization."""
148 ...
150 @property 1abcdefghijklsmnopqr
151 def by_alias(self) -> bool: 1abcdefghijklsmnopqr
152 """The `by_alias` argument set during serialization."""
153 ...
155 @property 1abcdefghijklsmnopqr
156 def exclude_unset(self) -> bool: 1abcdefghijklsmnopqr
157 """The `exclude_unset` argument set during serialization."""
158 ...
160 @property 1abcdefghijklsmnopqr
161 def exclude_defaults(self) -> bool: 1abcdefghijklsmnopqr
162 """The `exclude_defaults` argument set during serialization."""
163 ...
165 @property 1abcdefghijklsmnopqr
166 def exclude_none(self) -> bool: 1abcdefghijklsmnopqr
167 """The `exclude_none` argument set during serialization."""
168 ...
170 @property 1abcdefghijklsmnopqr
171 def exclude_computed_fields(self) -> bool: 1abcdefghijklsmnopqr
172 """The `exclude_computed_fields` argument set during serialization."""
173 ...
175 @property 1abcdefghijklsmnopqr
176 def serialize_as_any(self) -> bool: 1abcdefghijklsmnopqr
177 """The `serialize_as_any` argument set during serialization."""
178 ...
180 @property 1abcdefghijklsmnopqr
181 def polymorphic_serialization(self) -> bool | None: 1abcdefghijklsmnopqr
182 """The `polymorphic_serialization` argument set during serialization, if any."""
183 ...
185 @property 1abcdefghijklsmnopqr
186 def round_trip(self) -> bool: 1abcdefghijklsmnopqr
187 """The `round_trip` argument set during serialization."""
188 ...
190 def mode_is_json(self) -> bool: ... 1abcdefghijklsmnopqr
192 def __str__(self) -> str: ... 1abcdefghijklsmnopqr
194 def __repr__(self) -> str: ... 1abcdefghijklsmnopqr
197class FieldSerializationInfo(SerializationInfo[ContextT], Protocol): 1abcdefghijklsmnopqr
198 """Extra data used during field serialization.""" 1abcdefghijklsmnopqr
200 @property 1abcdefghijklsmnopqr
201 def field_name(self) -> str: 1abcdefghijklsmnopqr
202 """The name of the current field being serialized."""
203 ...
206class ValidationInfo(Protocol[ContextT]): 1abcdefghijklsmnopqr
207 """Extra data used during validation."""
209 @property 1abcdefghijklsmnopqr
210 def context(self) -> ContextT: 1abcdefghijklsmnopqr
211 """The current validation context."""
212 ...
214 @property 1abcdefghijklsmnopqr
215 def config(self) -> CoreConfig | None: 1abcdefghijklsmnopqr
216 """The CoreConfig that applies to this validation."""
217 ...
219 @property 1abcdefghijklsmnopqr
220 def mode(self) -> Literal['python', 'json']: 1abcdefghijklsmnopqr
221 """The type of input data we are currently validating."""
222 ...
224 @property 1abcdefghijklsmnopqr
225 def data(self) -> dict[str, Any]: 1abcdefghijklsmnopqr
226 """The data being validated for this model."""
227 ...
229 @property 1abcdefghijklsmnopqr
230 def field_name(self) -> str | None: 1abcdefghijklsmnopqr
231 """
232 The name of the current field being validated if this validator is
233 attached to a model field.
234 """
235 ...
238ExpectedSerializationTypes: TypeAlias = Literal[ 1abcdefghijklsmnopqr
239 'none',
240 'int',
241 'bool',
242 'float',
243 'str',
244 'bytes',
245 'bytearray',
246 'list',
247 'deque',
248 'tuple',
249 'set',
250 'frozenset',
251 'generator',
252 'dict',
253 'frozendict',
254 'ordered-dict',
255 'counter',
256 'datetime',
257 'date',
258 'time',
259 'timedelta',
260 'url',
261 'multi-host-url',
262 'json',
263 'uuid',
264 'any',
265]
268class SimpleSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
269 type: Required[ExpectedSerializationTypes] 1abcdefghijklsmnopqr
272def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema: 1abcdefghijklsmnopqr
273 """
274 Returns a schema for serialization with a custom type.
276 Note that any core schema can be used as a serialization schema, e.g. `int_schema()`
277 is equivalent to `simple_ser_schema('int')`.
279 Args:
280 type: The type to use for serialization
281 """
282 return SimpleSerSchema(type=type) 1abcdefghijklmnopqr
285# (input_value: Any, /) -> Any
286GeneralPlainNoInfoSerializerFunction: TypeAlias = Callable[[Any], Any] 1abcdefghijklsmnopqr
287# (input_value: Any, info: FieldSerializationInfo, /) -> Any
288GeneralPlainInfoSerializerFunction: TypeAlias = Callable[[Any, SerializationInfo[Any]], Any] 1abcdefghijklsmnopqr
289# (model: Any, input_value: Any, /) -> Any
290FieldPlainNoInfoSerializerFunction: TypeAlias = Callable[[Any, Any], Any] 1abcdefghijklsmnopqr
291# (model: Any, input_value: Any, info: FieldSerializationInfo, /) -> Any
292FieldPlainInfoSerializerFunction: TypeAlias = Callable[[Any, Any, FieldSerializationInfo[Any]], Any] 1abcdefghijklsmnopqr
293SerializerFunction: TypeAlias = ( 1abcdefghijklsmnopqr
294 GeneralPlainNoInfoSerializerFunction
295 | GeneralPlainInfoSerializerFunction
296 | FieldPlainNoInfoSerializerFunction
297 | FieldPlainInfoSerializerFunction
298)
300WhenUsed: TypeAlias = Literal['always', 'unless-none', 'json', 'json-unless-none'] 1abcdefghijklsmnopqr
301""" 1abcdefghijklsmnopqr
302Values have the following meanings:
304* `'always'` means always use
305* `'unless-none'` means use unless the value is `None`
306* `'json'` means use when serializing to JSON
307* `'json-unless-none'` means use when serializing to JSON and the value is not `None`
308"""
311class PlainSerializerFunctionSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
312 type: Required[Literal['function-plain']] 1abcdefghijklsmnopqr
313 function: Required[SerializerFunction] 1abcdefghijklsmnopqr
314 is_field_serializer: bool # default False 1abcdefghijklsmnopqr
315 info_arg: bool # default False 1abcdefghijklsmnopqr
316 return_schema: CoreSchema # if omitted, AnySchema is used 1abcdefghijklsmnopqr
317 when_used: WhenUsed # default: 'always' 1abcdefghijklsmnopqr
320def plain_serializer_function_ser_schema( 1abcdefghijklsmnopqr
321 function: SerializerFunction,
322 *,
323 is_field_serializer: bool | None = None,
324 info_arg: bool | None = None,
325 return_schema: CoreSchema | None = None,
326 when_used: WhenUsed = 'always',
327) -> PlainSerializerFunctionSerSchema:
328 """
329 Returns a schema for serialization with a function, can be either a "general" or "field" function.
331 Args:
332 function: The function to use for serialization
333 is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
334 and `info` includes `field_name`
335 info_arg: Whether the function takes an `info` argument
336 return_schema: Schema to use for serializing return value
337 when_used: When the function should be called
338 """
339 if when_used == 'always': 1abcdefghijklsmnopqr
340 # just to avoid extra elements in schema, and to use the actual default defined in rust
341 when_used = None # type: ignore 1abcdefghijklsmnopqr
342 return _dict_not_none( 1abcdefghijklsmnopqr
343 type='function-plain',
344 function=function,
345 is_field_serializer=is_field_serializer,
346 info_arg=info_arg,
347 return_schema=return_schema,
348 when_used=when_used,
349 )
352class SerializerFunctionWrapHandler(Protocol): # pragma: no cover 1abcdefghijklsmnopqr
353 def __call__(self, input_value: Any, index_key: int | str | None = None, /) -> Any: ... 1abcdefghijklsmnopqr
356# (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
357GeneralWrapNoInfoSerializerFunction: TypeAlias = Callable[[Any, SerializerFunctionWrapHandler], Any] 1abcdefghijklsmnopqr
358# (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any
359GeneralWrapInfoSerializerFunction: TypeAlias = Callable[ 1abcdefghijklsmnopqr
360 [Any, SerializerFunctionWrapHandler, SerializationInfo[Any]], Any
361]
362# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
363FieldWrapNoInfoSerializerFunction: TypeAlias = Callable[[Any, Any, SerializerFunctionWrapHandler], Any] 1abcdefghijklsmnopqr
364# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, info: FieldSerializationInfo, /) -> Any
365FieldWrapInfoSerializerFunction: TypeAlias = Callable[ 1abcdefghijklsmnopqr
366 [Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo[Any]], Any
367]
368WrapSerializerFunction: TypeAlias = ( 1abcdefghijklsmnopqr
369 GeneralWrapNoInfoSerializerFunction
370 | GeneralWrapInfoSerializerFunction
371 | FieldWrapNoInfoSerializerFunction
372 | FieldWrapInfoSerializerFunction
373)
376class WrapSerializerFunctionSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
377 type: Required[Literal['function-wrap']] 1abcdefghijklsmnopqr
378 function: Required[WrapSerializerFunction] 1abcdefghijklsmnopqr
379 is_field_serializer: bool # default False 1abcdefghijklsmnopqr
380 info_arg: bool # default False 1abcdefghijklsmnopqr
381 schema: CoreSchema # if omitted, the schema on which this serializer is defined is used 1abcdefghijklsmnopqr
382 return_schema: CoreSchema # if omitted, AnySchema is used 1abcdefghijklsmnopqr
383 when_used: WhenUsed # default: 'always' 1abcdefghijklsmnopqr
386def wrap_serializer_function_ser_schema( 1abcdefghijklsmnopqr
387 function: WrapSerializerFunction,
388 *,
389 is_field_serializer: bool | None = None,
390 info_arg: bool | None = None,
391 schema: CoreSchema | None = None,
392 return_schema: CoreSchema | None = None,
393 when_used: WhenUsed = 'always',
394) -> WrapSerializerFunctionSerSchema:
395 """
396 Returns a schema for serialization with a wrap function, can be either a "general" or "field" function.
398 Args:
399 function: The function to use for serialization
400 is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
401 and `info` includes `field_name`
402 info_arg: Whether the function takes an `info` argument
403 schema: The schema to use for the inner serialization
404 return_schema: Schema to use for serializing return value
405 when_used: When the function should be called
406 """
407 if when_used == 'always': 1abcdefghijklmnopqr
408 # just to avoid extra elements in schema, and to use the actual default defined in rust
409 when_used = None # type: ignore 1abcdefghijklmnopqr
410 return _dict_not_none( 1abcdefghijklmnopqr
411 type='function-wrap',
412 function=function,
413 is_field_serializer=is_field_serializer,
414 info_arg=info_arg,
415 schema=schema,
416 return_schema=return_schema,
417 when_used=when_used,
418 )
421class FormatSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
422 type: Required[Literal['format']] 1abcdefghijklsmnopqr
423 formatting_string: Required[str] 1abcdefghijklsmnopqr
424 when_used: WhenUsed # default: 'json-unless-none' 1abcdefghijklsmnopqr
427def format_ser_schema(formatting_string: str, *, when_used: WhenUsed = 'json-unless-none') -> FormatSerSchema: 1abcdefghijklsmnopqr
428 """
429 Returns a schema for serialization using python's `format` method.
431 Args:
432 formatting_string: String defining the format to use
433 when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
434 """
435 if when_used == 'json-unless-none': 1abcdefghijklmnopqr
436 # just to avoid extra elements in schema, and to use the actual default defined in rust
437 when_used = None # type: ignore 1abcdefghijklmnopqr
438 return _dict_not_none(type='format', formatting_string=formatting_string, when_used=when_used) 1abcdefghijklmnopqr
441class ToStringSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
442 type: Required[Literal['to-string']] 1abcdefghijklsmnopqr
443 when_used: WhenUsed # default: 'json-unless-none' 1abcdefghijklsmnopqr
446def to_string_ser_schema(*, when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema: 1abcdefghijklsmnopqr
447 """
448 Returns a schema for serialization using python's `str()` / `__str__` method.
450 Args:
451 when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
452 """
453 s = {'type': 'to-string'} 1abcdefghijklmnopqr
454 if when_used != 'json-unless-none': 1abcdefghijklmnopqr
455 # just to avoid extra elements in schema, and to use the actual default defined in rust
456 s['when_used'] = when_used 1abcdefghijklmnopqr
457 return s # type: ignore 1abcdefghijklmnopqr
460class ModelSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
461 type: Required[Literal['model']] 1abcdefghijklsmnopqr
462 cls: Required[type[Any]] 1abcdefghijklsmnopqr
463 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
466def model_ser_schema(cls: type[Any], schema: CoreSchema) -> ModelSerSchema: 1abcdefghijklsmnopqr
467 """
468 Returns a schema for serialization using a model.
470 Note that any core schema can be used as a serialization schema, e.g. `model_schema()`
471 can be used instead.
473 Args:
474 cls: The expected class type, used to generate warnings if the wrong type is passed
475 schema: Internal schema to use to serialize the model dict
476 """
477 return ModelSerSchema(type='model', cls=cls, schema=schema) 1abcdefghijklmnopqr
480SerSchema: TypeAlias = 'SimpleSerSchema | PlainSerializerFunctionSerSchema | WrapSerializerFunctionSerSchema | FormatSerSchema | ToStringSerSchema | ModelSerSchema | CoreSchema' 1abcdefghijklsmnopqr
482"""The schemas that can be used as the `serialization` key of a core schema.""" 1abcdefghijklsmnopqr
485class InvalidSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
486 type: Required[Literal['invalid']] 1abcdefghijklsmnopqr
487 ref: str 1abcdefghijklsmnopqr
488 metadata: dict[str, Any] 1abcdefghijklsmnopqr
489 # note, we never plan to use this, but include it for type checking purposes to match
490 # all other CoreSchema union members
491 serialization: SerSchema 1abcdefghijklsmnopqr
494def invalid_schema(ref: str | None = None, metadata: dict[str, Any] | None = None) -> InvalidSchema: 1abcdefghijklsmnopqr
495 """
496 Returns an invalid schema, used to indicate that a schema is invalid.
498 Args:
499 ref: optional unique identifier of the schema, used to reference the schema in other places
500 metadata: Any other information you want to include with the schema, not used by pydantic-core
501 """
503 return _dict_not_none(type='invalid', ref=ref, metadata=metadata) 1abcdefghijklmnopqr
506class ComputedField(TypedDict, total=False): 1abcdefghijklsmnopqr
507 type: Required[Literal['computed-field']] 1abcdefghijklsmnopqr
508 property_name: Required[str] 1abcdefghijklsmnopqr
509 return_schema: Required[CoreSchema] 1abcdefghijklsmnopqr
510 alias: str 1abcdefghijklsmnopqr
511 serialization_exclude_if: Callable[[Any], bool] 1abcdefghijklsmnopqr
512 metadata: dict[str, Any] 1abcdefghijklsmnopqr
515def computed_field( 1abcdefghijklsmnopqr
516 property_name: str,
517 return_schema: CoreSchema,
518 *,
519 alias: str | None = None,
520 serialization_exclude_if: Callable[[Any], bool] | None = None,
521 metadata: dict[str, Any] | None = None,
522) -> ComputedField:
523 """
524 ComputedFields are properties of a model or dataclass that are included in serialization.
526 Args:
527 property_name: The name of the property on the model or dataclass
528 return_schema: The schema used for the type returned by the computed field
529 alias: The name to use in the serialized output
530 metadata: Any other information you want to include with the schema, not used by pydantic-core
531 """
532 return _dict_not_none( 1abcdefghijklmnopqr
533 type='computed-field',
534 property_name=property_name,
535 return_schema=return_schema,
536 alias=alias,
537 serialization_exclude_if=serialization_exclude_if,
538 metadata=metadata,
539 )
542class AnySchema(TypedDict, total=False): 1abcdefghijklsmnopqr
543 type: Required[Literal['any']] 1abcdefghijklsmnopqr
544 ref: str 1abcdefghijklsmnopqr
545 metadata: dict[str, Any] 1abcdefghijklsmnopqr
546 serialization: SerSchema 1abcdefghijklsmnopqr
549def any_schema( 1abcdefghijklsmnopqr
550 *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
551) -> AnySchema:
552 """
553 Returns a schema that matches any value, e.g.:
555 ```py
556 from pydantic_core import SchemaValidator, core_schema
558 schema = core_schema.any_schema()
559 v = SchemaValidator(schema)
560 assert v.validate_python(1) == 1
561 ```
563 Args:
564 ref: optional unique identifier of the schema, used to reference the schema in other places
565 metadata: Any other information you want to include with the schema, not used by pydantic-core
566 serialization: Custom serialization schema
567 """
568 return _dict_not_none(type='any', ref=ref, metadata=metadata, serialization=serialization) 1abcdefghijklsmnopqr
571class NoneSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
572 type: Required[Literal['none']] 1abcdefghijklsmnopqr
573 ref: str 1abcdefghijklsmnopqr
574 metadata: dict[str, Any] 1abcdefghijklsmnopqr
575 serialization: SerSchema 1abcdefghijklsmnopqr
578def none_schema( 1abcdefghijklsmnopqr
579 *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
580) -> NoneSchema:
581 """
582 Returns a schema that matches a None value, e.g.:
584 ```py
585 from pydantic_core import SchemaValidator, core_schema
587 schema = core_schema.none_schema()
588 v = SchemaValidator(schema)
589 assert v.validate_python(None) is None
590 ```
592 Args:
593 ref: optional unique identifier of the schema, used to reference the schema in other places
594 metadata: Any other information you want to include with the schema, not used by pydantic-core
595 serialization: Custom serialization schema
596 """
597 return _dict_not_none(type='none', ref=ref, metadata=metadata, serialization=serialization) 1abcdefghijklsmnopqr
600class BoolSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
601 type: Required[Literal['bool']] 1abcdefghijklsmnopqr
602 strict: bool 1abcdefghijklsmnopqr
603 ref: str 1abcdefghijklsmnopqr
604 metadata: dict[str, Any] 1abcdefghijklsmnopqr
605 serialization: SerSchema 1abcdefghijklsmnopqr
608def bool_schema( 1abcdefghijklsmnopqr
609 strict: bool | None = None,
610 ref: str | None = None,
611 metadata: dict[str, Any] | None = None,
612 serialization: SerSchema | None = None,
613) -> BoolSchema:
614 """
615 Returns a schema that matches a bool value, e.g.:
617 ```py
618 from pydantic_core import SchemaValidator, core_schema
620 schema = core_schema.bool_schema()
621 v = SchemaValidator(schema)
622 assert v.validate_python('True') is True
623 ```
625 Args:
626 strict: Whether the value should be a bool or a value that can be converted to a bool
627 ref: optional unique identifier of the schema, used to reference the schema in other places
628 metadata: Any other information you want to include with the schema, not used by pydantic-core
629 serialization: Custom serialization schema
630 """
631 return _dict_not_none(type='bool', strict=strict, ref=ref, metadata=metadata, serialization=serialization) 1abcdefghijklsmnopqr
634class IntSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
635 type: Required[Literal['int']] 1abcdefghijklsmnopqr
636 multiple_of: int 1abcdefghijklsmnopqr
637 le: int 1abcdefghijklsmnopqr
638 ge: int 1abcdefghijklsmnopqr
639 lt: int 1abcdefghijklsmnopqr
640 gt: int 1abcdefghijklsmnopqr
641 strict: bool 1abcdefghijklsmnopqr
642 ref: str 1abcdefghijklsmnopqr
643 metadata: dict[str, Any] 1abcdefghijklsmnopqr
644 serialization: SerSchema 1abcdefghijklsmnopqr
647def int_schema( 1abcdefghijklsmnopqr
648 *,
649 multiple_of: int | None = None,
650 le: int | None = None,
651 ge: int | None = None,
652 lt: int | None = None,
653 gt: int | None = None,
654 strict: bool | None = None,
655 ref: str | None = None,
656 metadata: dict[str, Any] | None = None,
657 serialization: SerSchema | None = None,
658) -> IntSchema:
659 """
660 Returns a schema that matches a int value, e.g.:
662 ```py
663 from pydantic_core import SchemaValidator, core_schema
665 schema = core_schema.int_schema(multiple_of=2, le=6, ge=2)
666 v = SchemaValidator(schema)
667 assert v.validate_python('4') == 4
668 ```
670 Args:
671 multiple_of: The value must be a multiple of this number
672 le: The value must be less than or equal to this number
673 ge: The value must be greater than or equal to this number
674 lt: The value must be strictly less than this number
675 gt: The value must be strictly greater than this number
676 strict: Whether the value should be a int or a value that can be converted to a int
677 ref: optional unique identifier of the schema, used to reference the schema in other places
678 metadata: Any other information you want to include with the schema, not used by pydantic-core
679 serialization: Custom serialization schema
680 """
681 return _dict_not_none( 1abcdefghijklsmnopqr
682 type='int',
683 multiple_of=multiple_of,
684 le=le,
685 ge=ge,
686 lt=lt,
687 gt=gt,
688 strict=strict,
689 ref=ref,
690 metadata=metadata,
691 serialization=serialization,
692 )
695class FloatSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
696 type: Required[Literal['float']] 1abcdefghijklsmnopqr
697 allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: True 1abcdefghijklsmnopqr
698 multiple_of: float 1abcdefghijklsmnopqr
699 le: float 1abcdefghijklsmnopqr
700 ge: float 1abcdefghijklsmnopqr
701 lt: float 1abcdefghijklsmnopqr
702 gt: float 1abcdefghijklsmnopqr
703 strict: bool 1abcdefghijklsmnopqr
704 ref: str 1abcdefghijklsmnopqr
705 metadata: dict[str, Any] 1abcdefghijklsmnopqr
706 serialization: SerSchema 1abcdefghijklsmnopqr
709def float_schema( 1abcdefghijklsmnopqr
710 *,
711 allow_inf_nan: bool | None = None,
712 multiple_of: float | None = None,
713 le: float | None = None,
714 ge: float | None = None,
715 lt: float | None = None,
716 gt: float | None = None,
717 strict: bool | None = None,
718 ref: str | None = None,
719 metadata: dict[str, Any] | None = None,
720 serialization: SerSchema | None = None,
721) -> FloatSchema:
722 """
723 Returns a schema that matches a float value, e.g.:
725 ```py
726 from pydantic_core import SchemaValidator, core_schema
728 schema = core_schema.float_schema(le=0.8, ge=0.2)
729 v = SchemaValidator(schema)
730 assert v.validate_python('0.5') == 0.5
731 ```
733 Args:
734 allow_inf_nan: Whether to allow inf and nan values
735 multiple_of: The value must be a multiple of this number
736 le: The value must be less than or equal to this number
737 ge: The value must be greater than or equal to this number
738 lt: The value must be strictly less than this number
739 gt: The value must be strictly greater than this number
740 strict: Whether the value should be a float or a value that can be converted to a float
741 ref: optional unique identifier of the schema, used to reference the schema in other places
742 metadata: Any other information you want to include with the schema, not used by pydantic-core
743 serialization: Custom serialization schema
744 """
745 return _dict_not_none( 1abcdefghijklsmnopqr
746 type='float',
747 allow_inf_nan=allow_inf_nan,
748 multiple_of=multiple_of,
749 le=le,
750 ge=ge,
751 lt=lt,
752 gt=gt,
753 strict=strict,
754 ref=ref,
755 metadata=metadata,
756 serialization=serialization,
757 )
760class DecimalSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
761 type: Required[Literal['decimal']] 1abcdefghijklsmnopqr
762 allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: False 1abcdefghijklsmnopqr
763 multiple_of: Decimal 1abcdefghijklsmnopqr
764 le: Decimal 1abcdefghijklsmnopqr
765 ge: Decimal 1abcdefghijklsmnopqr
766 lt: Decimal 1abcdefghijklsmnopqr
767 gt: Decimal 1abcdefghijklsmnopqr
768 max_digits: int 1abcdefghijklsmnopqr
769 decimal_places: int 1abcdefghijklsmnopqr
770 strict: bool 1abcdefghijklsmnopqr
771 ref: str 1abcdefghijklsmnopqr
772 metadata: dict[str, Any] 1abcdefghijklsmnopqr
773 serialization: SerSchema 1abcdefghijklsmnopqr
776def decimal_schema( 1abcdefghijklsmnopqr
777 *,
778 allow_inf_nan: bool | None = None,
779 multiple_of: Decimal | None = None,
780 le: Decimal | None = None,
781 ge: Decimal | None = None,
782 lt: Decimal | None = None,
783 gt: Decimal | None = None,
784 max_digits: int | None = None,
785 decimal_places: int | None = None,
786 strict: bool | None = None,
787 ref: str | None = None,
788 metadata: dict[str, Any] | None = None,
789 serialization: SerSchema | None = None,
790) -> DecimalSchema:
791 """
792 Returns a schema that matches a decimal value, e.g.:
794 ```py
795 from decimal import Decimal
796 from pydantic_core import SchemaValidator, core_schema
798 schema = core_schema.decimal_schema(le=0.8, ge=0.2)
799 v = SchemaValidator(schema)
800 assert v.validate_python('0.5') == Decimal('0.5')
801 ```
803 Args:
804 allow_inf_nan: Whether to allow inf and nan values
805 multiple_of: The value must be a multiple of this number
806 le: The value must be less than or equal to this number
807 ge: The value must be greater than or equal to this number
808 lt: The value must be strictly less than this number
809 gt: The value must be strictly greater than this number
810 max_digits: The maximum number of decimal digits allowed
811 decimal_places: The maximum number of decimal places allowed
812 strict: Whether the value should be a float or a value that can be converted to a float
813 ref: optional unique identifier of the schema, used to reference the schema in other places
814 metadata: Any other information you want to include with the schema, not used by pydantic-core
815 serialization: Custom serialization schema
816 """
817 return _dict_not_none( 1abcdefghijklsmnopqr
818 type='decimal',
819 gt=gt,
820 ge=ge,
821 lt=lt,
822 le=le,
823 max_digits=max_digits,
824 decimal_places=decimal_places,
825 multiple_of=multiple_of,
826 allow_inf_nan=allow_inf_nan,
827 strict=strict,
828 ref=ref,
829 metadata=metadata,
830 serialization=serialization,
831 )
834class FractionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
835 type: Required[Literal['fraction']] 1abcdefghijklsmnopqr
836 multiple_of: Fraction 1abcdefghijklsmnopqr
837 le: Fraction 1abcdefghijklsmnopqr
838 ge: Fraction 1abcdefghijklsmnopqr
839 lt: Fraction 1abcdefghijklsmnopqr
840 gt: Fraction 1abcdefghijklsmnopqr
841 strict: bool 1abcdefghijklsmnopqr
842 ref: str 1abcdefghijklsmnopqr
843 metadata: dict[str, Any] 1abcdefghijklsmnopqr
844 serialization: SerSchema 1abcdefghijklsmnopqr
847def fraction_schema( 1abcdefghijklsmnopqr
848 *,
849 multiple_of: Fraction | None = None,
850 le: Fraction | None = None,
851 ge: Fraction | None = None,
852 lt: Fraction | None = None,
853 gt: Fraction | None = None,
854 strict: bool | None = None,
855 ref: str | None = None,
856 metadata: dict[str, Any] | None = None,
857 serialization: SerSchema | None = None,
858) -> FractionSchema:
859 """
860 Returns a schema that matches a fraction value, e.g.:
862 ```py
863 from fractions import Fraction
864 from pydantic_core import SchemaValidator, core_schema
866 schema = core_schema.fraction_schema(le=Fraction(3, 4), ge=Fraction(1, 4))
867 v = SchemaValidator(schema)
868 assert v.validate_python('1/2') == Fraction(1, 2)
869 ```
871 Args:
872 multiple_of: The value must be a multiple of this number
873 le: The value must be less than or equal to this number
874 ge: The value must be greater than or equal to this number
875 lt: The value must be strictly less than this number
876 gt: The value must be strictly greater than this number
877 strict: Whether the value should be a Fraction or a value that can be converted to a Fraction
878 ref: optional unique identifier of the schema, used to reference the schema in other places
879 metadata: Any other information you want to include with the schema, not used by pydantic-core
880 serialization: Custom serialization schema
881 """
882 return _dict_not_none( 1abcdefghijklsmnopqr
883 type='fraction',
884 multiple_of=multiple_of,
885 gt=gt,
886 ge=ge,
887 lt=lt,
888 le=le,
889 strict=strict,
890 ref=ref,
891 metadata=metadata,
892 serialization=serialization,
893 )
896class ComplexSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
897 type: Required[Literal['complex']] 1abcdefghijklsmnopqr
898 strict: bool 1abcdefghijklsmnopqr
899 ref: str 1abcdefghijklsmnopqr
900 metadata: dict[str, Any] 1abcdefghijklsmnopqr
901 serialization: SerSchema 1abcdefghijklsmnopqr
904def complex_schema( 1abcdefghijklsmnopqr
905 *,
906 strict: bool | None = None,
907 ref: str | None = None,
908 metadata: dict[str, Any] | None = None,
909 serialization: SerSchema | None = None,
910) -> ComplexSchema:
911 """
912 Returns a schema that matches a complex value, e.g.:
914 ```py
915 from pydantic_core import SchemaValidator, core_schema
917 schema = core_schema.complex_schema()
918 v = SchemaValidator(schema)
919 assert v.validate_python('1+2j') == complex(1, 2)
920 assert v.validate_python(complex(1, 2)) == complex(1, 2)
921 ```
923 Args:
924 strict: Whether the value should be a complex object instance or a value that can be converted to a complex object
925 ref: optional unique identifier of the schema, used to reference the schema in other places
926 metadata: Any other information you want to include with the schema, not used by pydantic-core
927 serialization: Custom serialization schema
928 """
929 return _dict_not_none( 1abcdefghijklsmnopqr
930 type='complex',
931 strict=strict,
932 ref=ref,
933 metadata=metadata,
934 serialization=serialization,
935 )
938class StringSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
939 type: Required[Literal['str']] 1abcdefghijklsmnopqr
940 pattern: str | Pattern[str] 1abcdefghijklsmnopqr
941 max_length: int 1abcdefghijklsmnopqr
942 min_length: int 1abcdefghijklsmnopqr
943 strip_whitespace: bool 1abcdefghijklsmnopqr
944 to_lower: bool 1abcdefghijklsmnopqr
945 to_upper: bool 1abcdefghijklsmnopqr
946 ascii_only: bool 1abcdefghijklsmnopqr
947 regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex' 1abcdefghijklsmnopqr
948 strict: bool 1abcdefghijklsmnopqr
949 coerce_numbers_to_str: bool 1abcdefghijklsmnopqr
950 ref: str 1abcdefghijklsmnopqr
951 metadata: dict[str, Any] 1abcdefghijklsmnopqr
952 serialization: SerSchema 1abcdefghijklsmnopqr
955def str_schema( 1abcdefghijklsmnopqr
956 *,
957 pattern: str | Pattern[str] | None = None,
958 max_length: int | None = None,
959 min_length: int | None = None,
960 strip_whitespace: bool | None = None,
961 to_lower: bool | None = None,
962 to_upper: bool | None = None,
963 ascii_only: bool | None = None,
964 regex_engine: Literal['rust-regex', 'python-re'] | None = None,
965 strict: bool | None = None,
966 coerce_numbers_to_str: bool | None = None,
967 ref: str | None = None,
968 metadata: dict[str, Any] | None = None,
969 serialization: SerSchema | None = None,
970) -> StringSchema:
971 """
972 Returns a schema that matches a string value, e.g.:
974 ```py
975 from pydantic_core import SchemaValidator, core_schema
977 schema = core_schema.str_schema(max_length=10, min_length=2)
978 v = SchemaValidator(schema)
979 assert v.validate_python('hello') == 'hello'
980 ```
982 Args:
983 pattern: A regex pattern that the value must match
984 max_length: The value must be at most this length
985 min_length: The value must be at least this length
986 strip_whitespace: Whether to strip whitespace from the value
987 to_lower: Whether to convert the value to lowercase
988 to_upper: Whether to convert the value to uppercase
989 ascii_only: Whether the value must contain only ASCII characters
990 regex_engine: The regex engine to use for pattern validation. Default is 'rust-regex'.
991 - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust
992 crate, which is non-backtracking and therefore more DDoS
993 resistant, but does not support all regex features.
994 - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
995 which supports all regex features, but may be slower.
996 strict: Whether the value should be a string or a value that can be converted to a string
997 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
998 ref: optional unique identifier of the schema, used to reference the schema in other places
999 metadata: Any other information you want to include with the schema, not used by pydantic-core
1000 serialization: Custom serialization schema
1001 """
1002 return _dict_not_none( 1abcdefghijklsmnopqr
1003 type='str',
1004 pattern=pattern,
1005 max_length=max_length,
1006 min_length=min_length,
1007 strip_whitespace=strip_whitespace,
1008 to_lower=to_lower,
1009 to_upper=to_upper,
1010 ascii_only=ascii_only,
1011 regex_engine=regex_engine,
1012 strict=strict,
1013 coerce_numbers_to_str=coerce_numbers_to_str,
1014 ref=ref,
1015 metadata=metadata,
1016 serialization=serialization,
1017 )
1020class BytesSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1021 type: Required[Literal['bytes']] 1abcdefghijklsmnopqr
1022 max_length: int 1abcdefghijklsmnopqr
1023 min_length: int 1abcdefghijklsmnopqr
1024 strict: bool 1abcdefghijklsmnopqr
1025 ref: str 1abcdefghijklsmnopqr
1026 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1027 serialization: SerSchema 1abcdefghijklsmnopqr
1030def bytes_schema( 1abcdefghijklsmnopqr
1031 *,
1032 max_length: int | None = None,
1033 min_length: int | None = None,
1034 strict: bool | None = None,
1035 ref: str | None = None,
1036 metadata: dict[str, Any] | None = None,
1037 serialization: SerSchema | None = None,
1038) -> BytesSchema:
1039 """
1040 Returns a schema that matches a bytes value, e.g.:
1042 ```py
1043 from pydantic_core import SchemaValidator, core_schema
1045 schema = core_schema.bytes_schema(max_length=10, min_length=2)
1046 v = SchemaValidator(schema)
1047 assert v.validate_python(b'hello') == b'hello'
1048 ```
1050 Args:
1051 max_length: The value must be at most this length
1052 min_length: The value must be at least this length
1053 strict: Whether the value should be a bytes or a value that can be converted to a bytes
1054 ref: optional unique identifier of the schema, used to reference the schema in other places
1055 metadata: Any other information you want to include with the schema, not used by pydantic-core
1056 serialization: Custom serialization schema
1057 """
1058 return _dict_not_none( 1abcdefghijklsmnopqr
1059 type='bytes',
1060 max_length=max_length,
1061 min_length=min_length,
1062 strict=strict,
1063 ref=ref,
1064 metadata=metadata,
1065 serialization=serialization,
1066 )
1069class DateSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1070 type: Required[Literal['date']] 1abcdefghijklsmnopqr
1071 strict: bool 1abcdefghijklsmnopqr
1072 le: date 1abcdefghijklsmnopqr
1073 ge: date 1abcdefghijklsmnopqr
1074 lt: date 1abcdefghijklsmnopqr
1075 gt: date 1abcdefghijklsmnopqr
1076 now_op: Literal['past', 'future'] 1abcdefghijklsmnopqr
1077 # defaults to current local utc offset from `time.localtime().tm_gmtoff`
1078 # value is restricted to -86_400 < offset < 86_400:
1079 now_utc_offset: int 1abcdefghijklsmnopqr
1080 ref: str 1abcdefghijklsmnopqr
1081 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1082 serialization: SerSchema 1abcdefghijklsmnopqr
1085def date_schema( 1abcdefghijklsmnopqr
1086 *,
1087 strict: bool | None = None,
1088 le: date | None = None,
1089 ge: date | None = None,
1090 lt: date | None = None,
1091 gt: date | None = None,
1092 now_op: Literal['past', 'future'] | None = None,
1093 now_utc_offset: int | None = None,
1094 ref: str | None = None,
1095 metadata: dict[str, Any] | None = None,
1096 serialization: SerSchema | None = None,
1097) -> DateSchema:
1098 """
1099 Returns a schema that matches a date value, e.g.:
1101 ```py
1102 from datetime import date
1103 from pydantic_core import SchemaValidator, core_schema
1105 schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1))
1106 v = SchemaValidator(schema)
1107 assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1)
1108 ```
1110 Args:
1111 strict: Whether the value should be a date or a value that can be converted to a date
1112 le: The value must be less than or equal to this date
1113 ge: The value must be greater than or equal to this date
1114 lt: The value must be strictly less than this date
1115 gt: The value must be strictly greater than this date
1116 now_op: The value must be in the past or future relative to the current date
1117 now_utc_offset: The value must be in the past or future relative to the current date with this utc offset
1118 ref: optional unique identifier of the schema, used to reference the schema in other places
1119 metadata: Any other information you want to include with the schema, not used by pydantic-core
1120 serialization: Custom serialization schema
1121 """
1122 return _dict_not_none( 1abcdefghijklsmnopqr
1123 type='date',
1124 strict=strict,
1125 le=le,
1126 ge=ge,
1127 lt=lt,
1128 gt=gt,
1129 now_op=now_op,
1130 now_utc_offset=now_utc_offset,
1131 ref=ref,
1132 metadata=metadata,
1133 serialization=serialization,
1134 )
1137class TimeSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1138 type: Required[Literal['time']] 1abcdefghijklsmnopqr
1139 strict: bool 1abcdefghijklsmnopqr
1140 le: time 1abcdefghijklsmnopqr
1141 ge: time 1abcdefghijklsmnopqr
1142 lt: time 1abcdefghijklsmnopqr
1143 gt: time 1abcdefghijklsmnopqr
1144 tz_constraint: Literal['aware', 'naive'] | int 1abcdefghijklsmnopqr
1145 microseconds_precision: Literal['truncate', 'error'] 1abcdefghijklsmnopqr
1146 ref: str 1abcdefghijklsmnopqr
1147 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1148 serialization: SerSchema 1abcdefghijklsmnopqr
1151def time_schema( 1abcdefghijklsmnopqr
1152 *,
1153 strict: bool | None = None,
1154 le: time | None = None,
1155 ge: time | None = None,
1156 lt: time | None = None,
1157 gt: time | None = None,
1158 tz_constraint: Literal['aware', 'naive'] | int | None = None,
1159 microseconds_precision: Literal['truncate', 'error'] = 'truncate',
1160 ref: str | None = None,
1161 metadata: dict[str, Any] | None = None,
1162 serialization: SerSchema | None = None,
1163) -> TimeSchema:
1164 """
1165 Returns a schema that matches a time value, e.g.:
1167 ```py
1168 from datetime import time
1169 from pydantic_core import SchemaValidator, core_schema
1171 schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0))
1172 v = SchemaValidator(schema)
1173 assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0)
1174 ```
1176 Args:
1177 strict: Whether the value should be a time or a value that can be converted to a time
1178 le: The value must be less than or equal to this time
1179 ge: The value must be greater than or equal to this time
1180 lt: The value must be strictly less than this time
1181 gt: The value must be strictly greater than this time
1182 tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset
1183 microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
1184 ref: optional unique identifier of the schema, used to reference the schema in other places
1185 metadata: Any other information you want to include with the schema, not used by pydantic-core
1186 serialization: Custom serialization schema
1187 """
1188 return _dict_not_none( 1abcdefghijklsmnopqr
1189 type='time',
1190 strict=strict,
1191 le=le,
1192 ge=ge,
1193 lt=lt,
1194 gt=gt,
1195 tz_constraint=tz_constraint,
1196 microseconds_precision=microseconds_precision,
1197 ref=ref,
1198 metadata=metadata,
1199 serialization=serialization,
1200 )
1203class DatetimeSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1204 type: Required[Literal['datetime']] 1abcdefghijklsmnopqr
1205 strict: bool 1abcdefghijklsmnopqr
1206 le: datetime 1abcdefghijklsmnopqr
1207 ge: datetime 1abcdefghijklsmnopqr
1208 lt: datetime 1abcdefghijklsmnopqr
1209 gt: datetime 1abcdefghijklsmnopqr
1210 now_op: Literal['past', 'future'] 1abcdefghijklsmnopqr
1211 tz_constraint: Literal['aware', 'naive'] | int 1abcdefghijklsmnopqr
1212 # defaults to current local utc offset from `time.localtime().tm_gmtoff`
1213 # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py
1214 now_utc_offset: int 1abcdefghijklsmnopqr
1215 microseconds_precision: Literal['truncate', 'error'] # default: 'truncate' 1abcdefghijklsmnopqr
1216 ref: str 1abcdefghijklsmnopqr
1217 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1218 serialization: SerSchema 1abcdefghijklsmnopqr
1221def datetime_schema( 1abcdefghijklsmnopqr
1222 *,
1223 strict: bool | None = None,
1224 le: datetime | None = None,
1225 ge: datetime | None = None,
1226 lt: datetime | None = None,
1227 gt: datetime | None = None,
1228 now_op: Literal['past', 'future'] | None = None,
1229 tz_constraint: Literal['aware', 'naive'] | int | None = None,
1230 now_utc_offset: int | None = None,
1231 microseconds_precision: Literal['truncate', 'error'] = 'truncate',
1232 ref: str | None = None,
1233 metadata: dict[str, Any] | None = None,
1234 serialization: SerSchema | None = None,
1235) -> DatetimeSchema:
1236 """
1237 Returns a schema that matches a datetime value, e.g.:
1239 ```py
1240 from datetime import datetime
1241 from pydantic_core import SchemaValidator, core_schema
1243 schema = core_schema.datetime_schema()
1244 v = SchemaValidator(schema)
1245 now = datetime.now()
1246 assert v.validate_python(str(now)) == now
1247 ```
1249 Args:
1250 strict: Whether the value should be a datetime or a value that can be converted to a datetime
1251 le: The value must be less than or equal to this datetime
1252 ge: The value must be greater than or equal to this datetime
1253 lt: The value must be strictly less than this datetime
1254 gt: The value must be strictly greater than this datetime
1255 now_op: The value must be in the past or future relative to the current datetime
1256 tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset
1257 TODO: use of a tzinfo where offset changes based on the datetime is not yet supported
1258 now_utc_offset: The value must be in the past or future relative to the current datetime with this utc offset
1259 microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
1260 ref: optional unique identifier of the schema, used to reference the schema in other places
1261 metadata: Any other information you want to include with the schema, not used by pydantic-core
1262 serialization: Custom serialization schema
1263 """
1264 return _dict_not_none( 1abcdefghijklsmnopqr
1265 type='datetime',
1266 strict=strict,
1267 le=le,
1268 ge=ge,
1269 lt=lt,
1270 gt=gt,
1271 now_op=now_op,
1272 tz_constraint=tz_constraint,
1273 now_utc_offset=now_utc_offset,
1274 microseconds_precision=microseconds_precision,
1275 ref=ref,
1276 metadata=metadata,
1277 serialization=serialization,
1278 )
1281class TimedeltaSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1282 type: Required[Literal['timedelta']] 1abcdefghijklsmnopqr
1283 strict: bool 1abcdefghijklsmnopqr
1284 multiple_of: timedelta 1abcdefghijklsmnopqr
1285 le: timedelta 1abcdefghijklsmnopqr
1286 ge: timedelta 1abcdefghijklsmnopqr
1287 lt: timedelta 1abcdefghijklsmnopqr
1288 gt: timedelta 1abcdefghijklsmnopqr
1289 microseconds_precision: Literal['truncate', 'error'] 1abcdefghijklsmnopqr
1290 ref: str 1abcdefghijklsmnopqr
1291 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1292 serialization: SerSchema 1abcdefghijklsmnopqr
1295def timedelta_schema( 1abcdefghijklsmnopqr
1296 *,
1297 strict: bool | None = None,
1298 multiple_of: timedelta | None = None,
1299 le: timedelta | None = None,
1300 ge: timedelta | None = None,
1301 lt: timedelta | None = None,
1302 gt: timedelta | None = None,
1303 microseconds_precision: Literal['truncate', 'error'] = 'truncate',
1304 ref: str | None = None,
1305 metadata: dict[str, Any] | None = None,
1306 serialization: SerSchema | None = None,
1307) -> TimedeltaSchema:
1308 """
1309 Returns a schema that matches a timedelta value, e.g.:
1311 ```py
1312 from datetime import timedelta
1313 from pydantic_core import SchemaValidator, core_schema
1315 schema = core_schema.timedelta_schema(le=timedelta(days=1), ge=timedelta(days=0))
1316 v = SchemaValidator(schema)
1317 assert v.validate_python(timedelta(hours=12)) == timedelta(hours=12)
1318 ```
1320 Args:
1321 strict: Whether the value should be a timedelta or a value that can be converted to a timedelta
1322 multiple_of: The value must be a multiple of this timedelta
1323 le: The value must be less than or equal to this timedelta
1324 ge: The value must be greater than or equal to this timedelta
1325 lt: The value must be strictly less than this timedelta
1326 gt: The value must be strictly greater than this timedelta
1327 microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
1328 ref: optional unique identifier of the schema, used to reference the schema in other places
1329 metadata: Any other information you want to include with the schema, not used by pydantic-core
1330 serialization: Custom serialization schema
1331 """
1332 return _dict_not_none( 1abcdefghijklsmnopqr
1333 type='timedelta',
1334 strict=strict,
1335 multiple_of=multiple_of,
1336 le=le,
1337 ge=ge,
1338 lt=lt,
1339 gt=gt,
1340 microseconds_precision=microseconds_precision,
1341 ref=ref,
1342 metadata=metadata,
1343 serialization=serialization,
1344 )
1347class LiteralSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1348 type: Required[Literal['literal']] 1abcdefghijklsmnopqr
1349 expected: Required[list[Any]] 1abcdefghijklsmnopqr
1350 ref: str 1abcdefghijklsmnopqr
1351 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1352 serialization: SerSchema 1abcdefghijklsmnopqr
1355def literal_schema( 1abcdefghijklsmnopqr
1356 expected: list[Any],
1357 *,
1358 ref: str | None = None,
1359 metadata: dict[str, Any] | None = None,
1360 serialization: SerSchema | None = None,
1361) -> LiteralSchema:
1362 """
1363 Returns a schema that matches a literal value, e.g.:
1365 ```py
1366 from pydantic_core import SchemaValidator, core_schema
1368 schema = core_schema.literal_schema(['hello', 'world'])
1369 v = SchemaValidator(schema)
1370 assert v.validate_python('hello') == 'hello'
1371 ```
1373 Args:
1374 expected: The value must be one of these values
1375 ref: optional unique identifier of the schema, used to reference the schema in other places
1376 metadata: Any other information you want to include with the schema, not used by pydantic-core
1377 serialization: Custom serialization schema
1378 """
1379 return _dict_not_none(type='literal', expected=expected, ref=ref, metadata=metadata, serialization=serialization) 1abcdefghijklmnopqr
1382class EnumSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1383 type: Required[Literal['enum']] 1abcdefghijklsmnopqr
1384 cls: Required[Any] 1abcdefghijklsmnopqr
1385 members: Required[list[Any]] 1abcdefghijklsmnopqr
1386 sub_type: Literal['str', 'int', 'float'] 1abcdefghijklsmnopqr
1387 strict: bool 1abcdefghijklsmnopqr
1388 ref: str 1abcdefghijklsmnopqr
1389 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1390 serialization: SerSchema 1abcdefghijklsmnopqr
1393def enum_schema( 1abcdefghijklsmnopqr
1394 cls: Any,
1395 members: list[Any],
1396 *,
1397 sub_type: Literal['str', 'int', 'float'] | None = None,
1398 strict: bool | None = None,
1399 ref: str | None = None,
1400 metadata: dict[str, Any] | None = None,
1401 serialization: SerSchema | None = None,
1402) -> EnumSchema:
1403 """
1404 Returns a schema that matches an enum value, e.g.:
1406 ```py
1407 from enum import Enum
1408 from pydantic_core import SchemaValidator, core_schema
1410 class Color(Enum):
1411 RED = 1
1412 GREEN = 2
1413 BLUE = 3
1415 schema = core_schema.enum_schema(Color, list(Color.__members__.values()))
1416 v = SchemaValidator(schema)
1417 assert v.validate_python(2) is Color.GREEN
1418 ```
1420 Args:
1421 cls: The enum class
1422 members: The members of the enum, generally `list(MyEnum.__members__.values())`
1423 sub_type: The type of the enum, either 'str' or 'int' or None for plain enums
1424 strict: Whether to use strict mode, defaults to False
1425 ref: optional unique identifier of the schema, used to reference the schema in other places
1426 metadata: Any other information you want to include with the schema, not used by pydantic-core
1427 serialization: Custom serialization schema
1428 """
1429 return _dict_not_none( 1abcdefghijklmnopqr
1430 type='enum',
1431 cls=cls,
1432 members=members,
1433 sub_type=sub_type,
1434 strict=strict,
1435 ref=ref,
1436 metadata=metadata,
1437 serialization=serialization,
1438 )
1441class MissingSentinelSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1442 type: Required[Literal['missing-sentinel']] 1abcdefghijklsmnopqr
1443 schema: CoreSchema 1abcdefghijklsmnopqr
1444 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1445 serialization: SerSchema 1abcdefghijklsmnopqr
1448def missing_sentinel_schema( 1abcdefghijklsmnopqr
1449 schema: CoreSchema | None = None,
1450 *,
1451 metadata: dict[str, Any] | None = None,
1452 serialization: SerSchema | None = None,
1453) -> MissingSentinelSchema:
1454 """
1455 Returns a schema that matches the `MISSING` sentinel, or, if provided, the wrapped schema, e.g.:
1457 ```py
1458 from pydantic_core import MISSING, SchemaValidator, core_schema
1460 schema = core_schema.missing_sentinel_schema(core_schema.int_schema())
1461 v = SchemaValidator(schema)
1462 assert v.validate_python(MISSING) is MISSING
1463 assert v.validate_python(1) == 1
1464 ```
1466 If no schema is provided, only the `MISSING` sentinel is a valid input.
1468 Args:
1469 schema: The schema to wrap
1470 metadata: Any other information you want to include with the schema, not used by pydantic-core
1471 serialization: Custom serialization schema
1472 """
1474 return _dict_not_none( 1abcdefghijklsmnopqr
1475 type='missing-sentinel',
1476 schema=schema,
1477 metadata=metadata,
1478 serialization=serialization,
1479 )
1482class EllipsisSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1483 type: Required[Literal['ellipsis']] 1abcdefghijklsmnopqr
1484 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1485 serialization: SerSchema 1abcdefghijklsmnopqr
1488def ellipsis_schema( 1abcdefghijklsmnopqr
1489 metadata: dict[str, Any] | None = None,
1490 serialization: SerSchema | None = None,
1491) -> EllipsisSchema:
1492 """Returns a schema for the [`Ellipsis`][] literal."""
1494 return _dict_not_none( 1abcdefghijklsmnopqr
1495 type='ellipsis',
1496 metadata=metadata,
1497 serialization=serialization,
1498 )
1501# must match input/parse_json.rs::JsonType::try_from
1502JsonType = Literal['null', 'bool', 'int', 'float', 'str', 'list', 'dict'] 1abcdefghijklsmnopqr
1505class IsInstanceSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1506 type: Required[Literal['is-instance']] 1abcdefghijklsmnopqr
1507 cls: Required[Any] 1abcdefghijklsmnopqr
1508 cls_repr: str 1abcdefghijklsmnopqr
1509 ref: str 1abcdefghijklsmnopqr
1510 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1511 serialization: SerSchema 1abcdefghijklsmnopqr
1514def is_instance_schema( 1abcdefghijklsmnopqr
1515 cls: Any,
1516 *,
1517 cls_repr: str | None = None,
1518 ref: str | None = None,
1519 metadata: dict[str, Any] | None = None,
1520 serialization: SerSchema | None = None,
1521) -> IsInstanceSchema:
1522 """
1523 Returns a schema that checks if a value is an instance of a class, equivalent to python's `isinstance` method, e.g.:
1525 ```py
1526 from pydantic_core import SchemaValidator, core_schema
1528 class A:
1529 pass
1531 schema = core_schema.is_instance_schema(cls=A)
1532 v = SchemaValidator(schema)
1533 v.validate_python(A())
1534 ```
1536 Args:
1537 cls: The value must be an instance of this class
1538 cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
1539 ref: optional unique identifier of the schema, used to reference the schema in other places
1540 metadata: Any other information you want to include with the schema, not used by pydantic-core
1541 serialization: Custom serialization schema
1542 """
1543 return _dict_not_none( 1abcdefghijklmnopqr
1544 type='is-instance', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization
1545 )
1548class IsSubclassSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1549 type: Required[Literal['is-subclass']] 1abcdefghijklsmnopqr
1550 cls: Required[type[Any]] 1abcdefghijklsmnopqr
1551 cls_repr: str 1abcdefghijklsmnopqr
1552 ref: str 1abcdefghijklsmnopqr
1553 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1554 serialization: SerSchema 1abcdefghijklsmnopqr
1557def is_subclass_schema( 1abcdefghijklsmnopqr
1558 cls: type[Any],
1559 *,
1560 cls_repr: str | None = None,
1561 ref: str | None = None,
1562 metadata: dict[str, Any] | None = None,
1563 serialization: SerSchema | None = None,
1564) -> IsInstanceSchema:
1565 """
1566 Returns a schema that checks if a value is a subtype of a class, equivalent to python's `issubclass` method, e.g.:
1568 ```py
1569 from pydantic_core import SchemaValidator, core_schema
1571 class A:
1572 pass
1574 class B(A):
1575 pass
1577 schema = core_schema.is_subclass_schema(cls=A)
1578 v = SchemaValidator(schema)
1579 v.validate_python(B)
1580 ```
1582 Args:
1583 cls: The value must be a subclass of this class
1584 cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
1585 ref: optional unique identifier of the schema, used to reference the schema in other places
1586 metadata: Any other information you want to include with the schema, not used by pydantic-core
1587 serialization: Custom serialization schema
1588 """
1589 return _dict_not_none( 1abcdefghijklmnopqr
1590 type='is-subclass', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization
1591 )
1594class CallableSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1595 type: Required[Literal['callable']] 1abcdefghijklsmnopqr
1596 ref: str 1abcdefghijklsmnopqr
1597 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1598 serialization: SerSchema 1abcdefghijklsmnopqr
1601def callable_schema( 1abcdefghijklsmnopqr
1602 *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
1603) -> CallableSchema:
1604 """
1605 Returns a schema that checks if a value is callable, equivalent to python's `callable` method, e.g.:
1607 ```py
1608 from pydantic_core import SchemaValidator, core_schema
1610 schema = core_schema.callable_schema()
1611 v = SchemaValidator(schema)
1612 v.validate_python(min)
1613 ```
1615 Args:
1616 ref: optional unique identifier of the schema, used to reference the schema in other places
1617 metadata: Any other information you want to include with the schema, not used by pydantic-core
1618 serialization: Custom serialization schema
1619 """
1620 return _dict_not_none(type='callable', ref=ref, metadata=metadata, serialization=serialization) 1abcdefghijklsmnopqr
1623class UuidSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1624 type: Required[Literal['uuid']] 1abcdefghijklsmnopqr
1625 version: Literal[1, 3, 4, 5, 7] 1abcdefghijklsmnopqr
1626 strict: bool 1abcdefghijklsmnopqr
1627 ref: str 1abcdefghijklsmnopqr
1628 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1629 serialization: SerSchema 1abcdefghijklsmnopqr
1632def uuid_schema( 1abcdefghijklsmnopqr
1633 *,
1634 version: Literal[1, 3, 4, 5, 6, 7, 8] | None = None,
1635 strict: bool | None = None,
1636 ref: str | None = None,
1637 metadata: dict[str, Any] | None = None,
1638 serialization: SerSchema | None = None,
1639) -> UuidSchema:
1640 return _dict_not_none( 1abcdefghijklsmnopqr
1641 type='uuid', version=version, strict=strict, ref=ref, metadata=metadata, serialization=serialization
1642 )
1645class IncExSeqSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1646 type: Required[Literal['include-exclude-sequence']] 1abcdefghijklsmnopqr
1647 include: set[int] 1abcdefghijklsmnopqr
1648 exclude: set[int] 1abcdefghijklsmnopqr
1651def filter_seq_schema(*, include: set[int] | None = None, exclude: set[int] | None = None) -> IncExSeqSerSchema: 1abcdefghijklsmnopqr
1652 return _dict_not_none(type='include-exclude-sequence', include=include, exclude=exclude) 1abcdefghijklmnopqr
1655IncExSeqOrElseSerSchema: TypeAlias = Union[IncExSeqSerSchema, SerSchema] # noqa: UP007 (TypeError when evaluating) 1abcdefghijklsmnopqr
1658class ListSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1659 type: Required[Literal['list']] 1abcdefghijklsmnopqr
1660 items_schema: CoreSchema 1abcdefghijklsmnopqr
1661 min_length: int 1abcdefghijklsmnopqr
1662 max_length: int 1abcdefghijklsmnopqr
1663 fail_fast: bool 1abcdefghijklsmnopqr
1664 strict: bool 1abcdefghijklsmnopqr
1665 ref: str 1abcdefghijklsmnopqr
1666 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1667 serialization: IncExSeqOrElseSerSchema 1abcdefghijklsmnopqr
1670def list_schema( 1abcdefghijklsmnopqr
1671 items_schema: CoreSchema | None = None,
1672 *,
1673 min_length: int | None = None,
1674 max_length: int | None = None,
1675 fail_fast: bool | None = None,
1676 strict: bool | None = None,
1677 ref: str | None = None,
1678 metadata: dict[str, Any] | None = None,
1679 serialization: IncExSeqOrElseSerSchema | None = None,
1680) -> ListSchema:
1681 """
1682 Returns a schema that matches a list value, e.g.:
1684 ```py
1685 from pydantic_core import SchemaValidator, core_schema
1687 schema = core_schema.list_schema(core_schema.int_schema(), min_length=0, max_length=10)
1688 v = SchemaValidator(schema)
1689 assert v.validate_python(['4']) == [4]
1690 ```
1692 Args:
1693 items_schema: The value must be a list of items that match this schema
1694 min_length: The value must be a list with at least this many items
1695 max_length: The value must be a list with at most this many items
1696 fail_fast: Stop validation on the first error
1697 strict: The value must be a list with exactly this many items
1698 ref: optional unique identifier of the schema, used to reference the schema in other places
1699 metadata: Any other information you want to include with the schema, not used by pydantic-core
1700 serialization: Custom serialization schema
1701 """
1702 return _dict_not_none( 1abcdefghijklsmnopqr
1703 type='list',
1704 items_schema=items_schema,
1705 min_length=min_length,
1706 max_length=max_length,
1707 fail_fast=fail_fast,
1708 strict=strict,
1709 ref=ref,
1710 metadata=metadata,
1711 serialization=serialization,
1712 )
1715class DequeSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1716 type: Required[Literal['deque']] 1abcdefghijklsmnopqr
1717 items_schema: CoreSchema 1abcdefghijklsmnopqr
1718 min_length: int 1abcdefghijklsmnopqr
1719 max_length: int 1abcdefghijklsmnopqr
1720 fail_fast: bool 1abcdefghijklsmnopqr
1721 strict: bool 1abcdefghijklsmnopqr
1722 ref: str 1abcdefghijklsmnopqr
1723 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1724 serialization: IncExSeqOrElseSerSchema 1abcdefghijklsmnopqr
1727def deque_schema( 1abcdefghijklsmnopqr
1728 items_schema: CoreSchema | None = None,
1729 *,
1730 min_length: int | None = None,
1731 max_length: int | None = None,
1732 fail_fast: bool | None = None,
1733 strict: bool | None = None,
1734 ref: str | None = None,
1735 metadata: dict[str, Any] | None = None,
1736 serialization: IncExSeqOrElseSerSchema | None = None,
1737) -> DequeSchema:
1738 """
1739 Returns a schema that matches a [`collections.deque`][] value, e.g.:
1741 ```py
1742 from collections import deque
1744 from pydantic_core import SchemaValidator, core_schema
1746 schema = core_schema.deque_schema(core_schema.int_schema(), min_length=0, max_length=10)
1747 v = SchemaValidator(schema)
1748 assert v.validate_python(['4']) == deque([4])
1749 ```
1751 In lax mode, any iterable (except strings, bytes and mappings) is accepted and converted to a deque.
1752 If the input is a deque instance, its `maxlen` is preserved on the output.
1754 Args:
1755 items_schema: The value must be a deque of items that match this schema
1756 min_length: The value must be a deque with at least this many items
1757 max_length: The value must be a deque with at most this many items
1758 fail_fast: Stop validation on the first error
1759 strict: The value must be a deque instance
1760 ref: optional unique identifier of the schema, used to reference the schema in other places
1761 metadata: Any other information you want to include with the schema, not used by pydantic-core
1762 serialization: Custom serialization schema
1763 """
1764 return _dict_not_none( 1abcdefghijklmnopqr
1765 type='deque',
1766 items_schema=items_schema,
1767 min_length=min_length,
1768 max_length=max_length,
1769 fail_fast=fail_fast,
1770 strict=strict,
1771 ref=ref,
1772 metadata=metadata,
1773 serialization=serialization,
1774 )
1777class TupleSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1778 type: Required[Literal['tuple']] 1abcdefghijklsmnopqr
1779 items_schema: Required[list[CoreSchema]] 1abcdefghijklsmnopqr
1780 variadic_item_index: int 1abcdefghijklsmnopqr
1781 min_length: int 1abcdefghijklsmnopqr
1782 max_length: int 1abcdefghijklsmnopqr
1783 fail_fast: bool 1abcdefghijklsmnopqr
1784 strict: bool 1abcdefghijklsmnopqr
1785 ref: str 1abcdefghijklsmnopqr
1786 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1787 serialization: IncExSeqOrElseSerSchema 1abcdefghijklsmnopqr
1790def tuple_schema( 1abcdefghijklsmnopqr
1791 items_schema: list[CoreSchema],
1792 *,
1793 variadic_item_index: int | None = None,
1794 min_length: int | None = None,
1795 max_length: int | None = None,
1796 fail_fast: bool | None = None,
1797 strict: bool | None = None,
1798 ref: str | None = None,
1799 metadata: dict[str, Any] | None = None,
1800 serialization: IncExSeqOrElseSerSchema | None = None,
1801) -> TupleSchema:
1802 """
1803 Returns a schema that matches a tuple of schemas, with an optional variadic item, e.g.:
1805 ```py
1806 from pydantic_core import SchemaValidator, core_schema
1808 schema = core_schema.tuple_schema(
1809 [core_schema.int_schema(), core_schema.str_schema(), core_schema.float_schema()],
1810 variadic_item_index=1,
1811 )
1812 v = SchemaValidator(schema)
1813 assert v.validate_python((1, 'hello', 'world', 1.5)) == (1, 'hello', 'world', 1.5)
1814 ```
1816 Args:
1817 items_schema: The value must be a tuple with items that match these schemas
1818 variadic_item_index: The index of the schema in `items_schema` to be treated as variadic (following PEP 646)
1819 min_length: The value must be a tuple with at least this many items
1820 max_length: The value must be a tuple with at most this many items
1821 fail_fast: Stop validation on the first error
1822 strict: The value must be a tuple with exactly this many items
1823 ref: Optional unique identifier of the schema, used to reference the schema in other places
1824 metadata: Any other information you want to include with the schema, not used by pydantic-core
1825 serialization: Custom serialization schema
1826 """
1827 return _dict_not_none( 1abcdefghijklmnopqr
1828 type='tuple',
1829 items_schema=items_schema,
1830 variadic_item_index=variadic_item_index,
1831 min_length=min_length,
1832 max_length=max_length,
1833 fail_fast=fail_fast,
1834 strict=strict,
1835 ref=ref,
1836 metadata=metadata,
1837 serialization=serialization,
1838 )
1841class SetSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1842 type: Required[Literal['set']] 1abcdefghijklsmnopqr
1843 items_schema: CoreSchema 1abcdefghijklsmnopqr
1844 min_length: int 1abcdefghijklsmnopqr
1845 max_length: int 1abcdefghijklsmnopqr
1846 fail_fast: bool 1abcdefghijklsmnopqr
1847 strict: bool 1abcdefghijklsmnopqr
1848 ref: str 1abcdefghijklsmnopqr
1849 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1850 serialization: SerSchema 1abcdefghijklsmnopqr
1853def set_schema( 1abcdefghijklsmnopqr
1854 items_schema: CoreSchema | None = None,
1855 *,
1856 min_length: int | None = None,
1857 max_length: int | None = None,
1858 fail_fast: bool | None = None,
1859 strict: bool | None = None,
1860 ref: str | None = None,
1861 metadata: dict[str, Any] | None = None,
1862 serialization: SerSchema | None = None,
1863) -> SetSchema:
1864 """
1865 Returns a schema that matches a set of a given schema, e.g.:
1867 ```py
1868 from pydantic_core import SchemaValidator, core_schema
1870 schema = core_schema.set_schema(
1871 items_schema=core_schema.int_schema(), min_length=0, max_length=10
1872 )
1873 v = SchemaValidator(schema)
1874 assert v.validate_python({1, '2', 3}) == {1, 2, 3}
1875 ```
1877 Args:
1878 items_schema: The value must be a set with items that match this schema
1879 min_length: The value must be a set with at least this many items
1880 max_length: The value must be a set with at most this many items
1881 fail_fast: Stop validation on the first error
1882 strict: The value must be a set with exactly this many items
1883 ref: optional unique identifier of the schema, used to reference the schema in other places
1884 metadata: Any other information you want to include with the schema, not used by pydantic-core
1885 serialization: Custom serialization schema
1886 """
1887 return _dict_not_none( 1abcdefghijklmnopqr
1888 type='set',
1889 items_schema=items_schema,
1890 min_length=min_length,
1891 max_length=max_length,
1892 fail_fast=fail_fast,
1893 strict=strict,
1894 ref=ref,
1895 metadata=metadata,
1896 serialization=serialization,
1897 )
1900class FrozenSetSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1901 type: Required[Literal['frozenset']] 1abcdefghijklsmnopqr
1902 items_schema: CoreSchema 1abcdefghijklsmnopqr
1903 min_length: int 1abcdefghijklsmnopqr
1904 max_length: int 1abcdefghijklsmnopqr
1905 fail_fast: bool 1abcdefghijklsmnopqr
1906 strict: bool 1abcdefghijklsmnopqr
1907 ref: str 1abcdefghijklsmnopqr
1908 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1909 serialization: SerSchema 1abcdefghijklsmnopqr
1912def frozenset_schema( 1abcdefghijklsmnopqr
1913 items_schema: CoreSchema | None = None,
1914 *,
1915 min_length: int | None = None,
1916 max_length: int | None = None,
1917 fail_fast: bool | None = None,
1918 strict: bool | None = None,
1919 ref: str | None = None,
1920 metadata: dict[str, Any] | None = None,
1921 serialization: SerSchema | None = None,
1922) -> FrozenSetSchema:
1923 """
1924 Returns a schema that matches a frozenset of a given schema, e.g.:
1926 ```py
1927 from pydantic_core import SchemaValidator, core_schema
1929 schema = core_schema.frozenset_schema(
1930 items_schema=core_schema.int_schema(), min_length=0, max_length=10
1931 )
1932 v = SchemaValidator(schema)
1933 assert v.validate_python(frozenset(range(3))) == frozenset({0, 1, 2})
1934 ```
1936 Args:
1937 items_schema: The value must be a frozenset with items that match this schema
1938 min_length: The value must be a frozenset with at least this many items
1939 max_length: The value must be a frozenset with at most this many items
1940 fail_fast: Stop validation on the first error
1941 strict: The value must be a frozenset with exactly this many items
1942 ref: optional unique identifier of the schema, used to reference the schema in other places
1943 metadata: Any other information you want to include with the schema, not used by pydantic-core
1944 serialization: Custom serialization schema
1945 """
1946 return _dict_not_none( 1abcdefghijklmnopqr
1947 type='frozenset',
1948 items_schema=items_schema,
1949 min_length=min_length,
1950 max_length=max_length,
1951 fail_fast=fail_fast,
1952 strict=strict,
1953 ref=ref,
1954 metadata=metadata,
1955 serialization=serialization,
1956 )
1959class GeneratorSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
1960 type: Required[Literal['generator']] 1abcdefghijklsmnopqr
1961 items_schema: CoreSchema 1abcdefghijklsmnopqr
1962 min_length: int 1abcdefghijklsmnopqr
1963 max_length: int 1abcdefghijklsmnopqr
1964 ref: str 1abcdefghijklsmnopqr
1965 metadata: dict[str, Any] 1abcdefghijklsmnopqr
1966 serialization: IncExSeqOrElseSerSchema 1abcdefghijklsmnopqr
1969def generator_schema( 1abcdefghijklsmnopqr
1970 items_schema: CoreSchema | None = None,
1971 *,
1972 min_length: int | None = None,
1973 max_length: int | None = None,
1974 ref: str | None = None,
1975 metadata: dict[str, Any] | None = None,
1976 serialization: IncExSeqOrElseSerSchema | None = None,
1977) -> GeneratorSchema:
1978 """
1979 Returns a schema that matches a generator value, e.g.:
1981 ```py
1982 from typing import Iterator
1983 from pydantic_core import SchemaValidator, core_schema
1985 def gen() -> Iterator[int]:
1986 yield 1
1988 schema = core_schema.generator_schema(items_schema=core_schema.int_schema())
1989 v = SchemaValidator(schema)
1990 v.validate_python(gen())
1991 ```
1993 Unlike other types, validated generators do not raise ValidationErrors eagerly,
1994 but instead will raise a ValidationError when a violating value is actually read from the generator.
1995 This is to ensure that "validated" generators retain the benefit of lazy evaluation.
1997 Args:
1998 items_schema: The value must be a generator with items that match this schema
1999 min_length: The value must be a generator that yields at least this many items
2000 max_length: The value must be a generator that yields at most this many items
2001 ref: optional unique identifier of the schema, used to reference the schema in other places
2002 metadata: Any other information you want to include with the schema, not used by pydantic-core
2003 serialization: Custom serialization schema
2004 """
2005 return _dict_not_none( 1abcdefghijklmnopqr
2006 type='generator',
2007 items_schema=items_schema,
2008 min_length=min_length,
2009 max_length=max_length,
2010 ref=ref,
2011 metadata=metadata,
2012 serialization=serialization,
2013 )
2016IncExDict: TypeAlias = set[int | str] 1abcdefghijklsmnopqr
2019class IncExDictSerSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2020 type: Required[Literal['include-exclude-dict']] 1abcdefghijklsmnopqr
2021 include: IncExDict 1abcdefghijklsmnopqr
2022 exclude: IncExDict 1abcdefghijklsmnopqr
2025def filter_dict_schema(*, include: IncExDict | None = None, exclude: IncExDict | None = None) -> IncExDictSerSchema: 1abcdefghijklsmnopqr
2026 return _dict_not_none(type='include-exclude-dict', include=include, exclude=exclude) 1abcdefghijklmnopqr
2029IncExDictOrElseSerSchema: TypeAlias = Union[IncExDictSerSchema, SerSchema] # noqa: UP007 (TypeError when evaluating) 1abcdefghijklsmnopqr
2032class DictSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2033 type: Required[Literal['dict']] 1abcdefghijklsmnopqr
2034 keys_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2035 values_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2036 min_length: int 1abcdefghijklsmnopqr
2037 max_length: int 1abcdefghijklsmnopqr
2038 fail_fast: bool 1abcdefghijklsmnopqr
2039 strict: bool 1abcdefghijklsmnopqr
2040 ref: str 1abcdefghijklsmnopqr
2041 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2042 serialization: IncExDictOrElseSerSchema 1abcdefghijklsmnopqr
2045def dict_schema( 1abcdefghijklsmnopqr
2046 keys_schema: CoreSchema | None = None,
2047 values_schema: CoreSchema | None = None,
2048 *,
2049 min_length: int | None = None,
2050 max_length: int | None = None,
2051 fail_fast: bool | None = None,
2052 strict: bool | None = None,
2053 ref: str | None = None,
2054 metadata: dict[str, Any] | None = None,
2055 serialization: SerSchema | None = None,
2056) -> DictSchema:
2057 """
2058 Returns a schema that matches a dict value, e.g.:
2060 ```py
2061 from pydantic_core import SchemaValidator, core_schema
2063 schema = core_schema.dict_schema(
2064 keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
2065 )
2066 v = SchemaValidator(schema)
2067 assert v.validate_python({'a': '1', 'b': 2}) == {'a': 1, 'b': 2}
2068 ```
2070 Args:
2071 keys_schema: The value must be a dict with keys that match this schema
2072 values_schema: The value must be a dict with values that match this schema
2073 min_length: The value must be a dict with at least this many items
2074 max_length: The value must be a dict with at most this many items
2075 fail_fast: Stop validation on the first error
2076 strict: Whether the keys and values should be validated with strict mode
2077 ref: optional unique identifier of the schema, used to reference the schema in other places
2078 metadata: Any other information you want to include with the schema, not used by pydantic-core
2079 serialization: Custom serialization schema
2080 """
2081 return _dict_not_none( 1abcdefghijklmnopqr
2082 type='dict',
2083 keys_schema=keys_schema,
2084 values_schema=values_schema,
2085 min_length=min_length,
2086 max_length=max_length,
2087 fail_fast=fail_fast,
2088 strict=strict,
2089 ref=ref,
2090 metadata=metadata,
2091 serialization=serialization,
2092 )
2095class FrozenDictSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2096 type: Required[Literal['frozendict']] 1abcdefghijklsmnopqr
2097 keys_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2098 values_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2099 min_length: int 1abcdefghijklsmnopqr
2100 max_length: int 1abcdefghijklsmnopqr
2101 fail_fast: bool 1abcdefghijklsmnopqr
2102 strict: bool 1abcdefghijklsmnopqr
2103 ref: str 1abcdefghijklsmnopqr
2104 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2105 serialization: IncExDictOrElseSerSchema 1abcdefghijklsmnopqr
2108def frozendict_schema( 1abcdefghijklsmnopqr
2109 keys_schema: CoreSchema | None = None,
2110 values_schema: CoreSchema | None = None,
2111 *,
2112 min_length: int | None = None,
2113 max_length: int | None = None,
2114 fail_fast: bool | None = None,
2115 strict: bool | None = None,
2116 ref: str | None = None,
2117 metadata: dict[str, Any] | None = None,
2118 serialization: SerSchema | None = None,
2119) -> FrozenDictSchema:
2120 """
2121 Returns a schema that matches a `frozendict` value, e.g.:
2123 ```py {requires="3.15" lint="skip"}
2124 from pydantic_core import SchemaValidator, core_schema
2126 schema = core_schema.frozendict_schema(
2127 keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
2128 )
2129 v = SchemaValidator(schema)
2130 assert v.validate_python({'a': '1', 'b': 2}) == frozendict({'a': 1, 'b': 2})
2131 ```
2133 !!! note
2134 The `frozendict` builtin type is only available in Python 3.15 and above.
2135 Using this schema on older Python versions will raise a [`SchemaError`][pydantic_core.SchemaError]
2136 when the validator or serializer is built.
2138 Args:
2139 keys_schema: The value must be a frozendict with keys that match this schema
2140 values_schema: The value must be a frozendict with values that match this schema
2141 min_length: The value must be a frozendict with at least this many items
2142 max_length: The value must be a frozendict with at most this many items
2143 fail_fast: Stop validation on the first error
2144 strict: Whether the input should be validated with strict mode
2145 ref: optional unique identifier of the schema, used to reference the schema in other places
2146 metadata: Any other information you want to include with the schema, not used by pydantic-core
2147 serialization: Custom serialization schema
2148 """
2149 return _dict_not_none( 1abcdefghijklmnopqr
2150 type='frozendict',
2151 keys_schema=keys_schema,
2152 values_schema=values_schema,
2153 min_length=min_length,
2154 max_length=max_length,
2155 fail_fast=fail_fast,
2156 strict=strict,
2157 ref=ref,
2158 metadata=metadata,
2159 serialization=serialization,
2160 )
2163class OrderedDictSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2164 type: Required[Literal['ordered-dict']] 1abcdefghijklsmnopqr
2165 keys_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2166 values_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2167 min_length: int 1abcdefghijklsmnopqr
2168 max_length: int 1abcdefghijklsmnopqr
2169 fail_fast: bool 1abcdefghijklsmnopqr
2170 strict: bool 1abcdefghijklsmnopqr
2171 ref: str 1abcdefghijklsmnopqr
2172 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2173 serialization: IncExDictOrElseSerSchema 1abcdefghijklsmnopqr
2176def ordered_dict_schema( 1abcdefghijklsmnopqr
2177 keys_schema: CoreSchema | None = None,
2178 values_schema: CoreSchema | None = None,
2179 *,
2180 min_length: int | None = None,
2181 max_length: int | None = None,
2182 fail_fast: bool | None = None,
2183 strict: bool | None = None,
2184 ref: str | None = None,
2185 metadata: dict[str, Any] | None = None,
2186 serialization: SerSchema | None = None,
2187) -> OrderedDictSchema:
2188 """
2189 Returns a schema that matches a [`collections.OrderedDict`][] value, e.g.:
2191 ```py
2192 from collections import OrderedDict
2194 from pydantic_core import SchemaValidator, core_schema
2196 schema = core_schema.ordered_dict_schema(
2197 keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
2198 )
2199 v = SchemaValidator(schema)
2200 assert v.validate_python({'a': '1', 'b': 2}) == OrderedDict({'a': 1, 'b': 2})
2201 ```
2203 In lax mode, any mapping is accepted and converted to an `OrderedDict`.
2205 Args:
2206 keys_schema: The value must be an `OrderedDict` with keys that match this schema
2207 values_schema: The value must be an `OrderedDict` with values that match this schema
2208 min_length: The value must be an `OrderedDict` with at least this many items
2209 max_length: The value must be an `OrderedDict` with at most this many items
2210 fail_fast: Stop validation on the first error
2211 strict: The value must be an `OrderedDict` instance
2212 ref: optional unique identifier of the schema, used to reference the schema in other places
2213 metadata: Any other information you want to include with the schema, not used by pydantic-core
2214 serialization: Custom serialization schema
2215 """
2216 return _dict_not_none( 1abcdefghijklmnopqr
2217 type='ordered-dict',
2218 keys_schema=keys_schema,
2219 values_schema=values_schema,
2220 min_length=min_length,
2221 max_length=max_length,
2222 fail_fast=fail_fast,
2223 strict=strict,
2224 ref=ref,
2225 metadata=metadata,
2226 serialization=serialization,
2227 )
2230class CounterSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2231 type: Required[Literal['counter']] 1abcdefghijklsmnopqr
2232 keys_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2233 values_schema: CoreSchema # default: AnySchema 1abcdefghijklsmnopqr
2234 min_length: int 1abcdefghijklsmnopqr
2235 max_length: int 1abcdefghijklsmnopqr
2236 fail_fast: bool 1abcdefghijklsmnopqr
2237 strict: bool 1abcdefghijklsmnopqr
2238 ref: str 1abcdefghijklsmnopqr
2239 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2240 serialization: IncExDictOrElseSerSchema 1abcdefghijklsmnopqr
2243def counter_schema( 1abcdefghijklsmnopqr
2244 keys_schema: CoreSchema | None = None,
2245 values_schema: CoreSchema | None = None,
2246 *,
2247 min_length: int | None = None,
2248 max_length: int | None = None,
2249 fail_fast: bool | None = None,
2250 strict: bool | None = None,
2251 ref: str | None = None,
2252 metadata: dict[str, Any] | None = None,
2253 serialization: SerSchema | None = None,
2254) -> CounterSchema:
2255 """
2256 Returns a schema that matches a [`collections.Counter`][] value, e.g.:
2258 ```py
2259 from collections import Counter
2261 from pydantic_core import SchemaValidator, core_schema
2263 schema = core_schema.counter_schema(
2264 keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
2265 )
2266 v = SchemaValidator(schema)
2267 assert v.validate_python({'a': '1', 'b': 2}) == Counter({'a': 1, 'b': 2})
2268 ```
2270 In lax mode, any mapping is accepted and converted to a `Counter`.
2272 Args:
2273 keys_schema: The value must be a `Counter` with keys that match this schema
2274 values_schema: The value must be a `Counter` with values that match this schema
2275 min_length: The value must be a `Counter` with at least this many items
2276 max_length: The value must be a `Counter` with at most this many items
2277 fail_fast: Stop validation on the first error
2278 strict: The value must be a `Counter` instance
2279 ref: optional unique identifier of the schema, used to reference the schema in other places
2280 metadata: Any other information you want to include with the schema, not used by pydantic-core
2281 serialization: Custom serialization schema
2282 """
2283 return _dict_not_none( 1abcdefghijklmnopqr
2284 type='counter',
2285 keys_schema=keys_schema,
2286 values_schema=values_schema,
2287 min_length=min_length,
2288 max_length=max_length,
2289 fail_fast=fail_fast,
2290 strict=strict,
2291 ref=ref,
2292 metadata=metadata,
2293 serialization=serialization,
2294 )
2297# (input_value: Any, /) -> Any
2298NoInfoValidatorFunction: TypeAlias = Callable[[Any], Any] 1abcdefghijklsmnopqr
2301class NoInfoValidatorFunctionSchema(TypedDict): 1abcdefghijklsmnopqr
2302 type: Literal['no-info'] 1abcdefghijklsmnopqr
2303 function: NoInfoValidatorFunction 1abcdefghijklsmnopqr
2306# (input_value: Any, info: ValidationInfo, /) -> Any
2307WithInfoValidatorFunction: TypeAlias = Callable[[Any, ValidationInfo[Any]], Any] 1abcdefghijklsmnopqr
2310class WithInfoValidatorFunctionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2311 type: Required[Literal['with-info']] 1abcdefghijklsmnopqr
2312 function: Required[WithInfoValidatorFunction] 1abcdefghijklsmnopqr
2315ValidationFunction: TypeAlias = NoInfoValidatorFunctionSchema | WithInfoValidatorFunctionSchema 1abcdefghijklsmnopqr
2318class _ValidatorFunctionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2319 function: Required[ValidationFunction] 1abcdefghijklsmnopqr
2320 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
2321 ref: str 1abcdefghijklsmnopqr
2322 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2323 serialization: SerSchema 1abcdefghijklsmnopqr
2326class BeforeValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): 1abcdefghijklsmnopqr
2327 type: Required[Literal['function-before']] 1abcdefghijklsmnopqr
2328 json_schema_input_schema: CoreSchema 1abcdefghijklsmnopqr
2331def no_info_before_validator_function( 1abcdefghijklsmnopqr
2332 function: NoInfoValidatorFunction,
2333 schema: CoreSchema,
2334 *,
2335 ref: str | None = None,
2336 json_schema_input_schema: CoreSchema | None = None,
2337 metadata: dict[str, Any] | None = None,
2338 serialization: SerSchema | None = None,
2339) -> BeforeValidatorFunctionSchema:
2340 """
2341 Returns a schema that calls a validator function before validating, no `info` argument is provided, e.g.:
2343 ```py
2344 from pydantic_core import SchemaValidator, core_schema
2346 def fn(v: bytes) -> str:
2347 return v.decode() + 'world'
2349 func_schema = core_schema.no_info_before_validator_function(
2350 function=fn, schema=core_schema.str_schema()
2351 )
2352 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
2354 v = SchemaValidator(schema)
2355 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
2356 ```
2358 Args:
2359 function: The validator function to call
2360 schema: The schema to validate the output of the validator function
2361 ref: optional unique identifier of the schema, used to reference the schema in other places
2362 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
2363 metadata: Any other information you want to include with the schema, not used by pydantic-core
2364 serialization: Custom serialization schema
2365 """
2366 return _dict_not_none( 1abcdefghijklmnopqr
2367 type='function-before',
2368 function={'type': 'no-info', 'function': function},
2369 schema=schema,
2370 ref=ref,
2371 json_schema_input_schema=json_schema_input_schema,
2372 metadata=metadata,
2373 serialization=serialization,
2374 )
2377def with_info_before_validator_function( 1abcdefghijklsmnopqr
2378 function: WithInfoValidatorFunction,
2379 schema: CoreSchema,
2380 *,
2381 ref: str | None = None,
2382 json_schema_input_schema: CoreSchema | None = None,
2383 metadata: dict[str, Any] | None = None,
2384 serialization: SerSchema | None = None,
2385) -> BeforeValidatorFunctionSchema:
2386 """
2387 Returns a schema that calls a validator function before validation, the function is called with
2388 an `info` argument, e.g.:
2390 ```py
2391 from pydantic_core import SchemaValidator, core_schema
2393 def fn(v: bytes, info: core_schema.ValidationInfo) -> str:
2394 assert info.data is not None
2395 assert info.field_name is not None
2396 return v.decode() + 'world'
2398 func_schema = core_schema.with_info_before_validator_function(
2399 function=fn, schema=core_schema.str_schema()
2400 )
2401 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
2403 v = SchemaValidator(schema)
2404 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
2405 ```
2407 Args:
2408 function: The validator function to call
2409 schema: The schema to validate the output of the validator function
2410 ref: optional unique identifier of the schema, used to reference the schema in other places
2411 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
2412 metadata: Any other information you want to include with the schema, not used by pydantic-core
2413 serialization: Custom serialization schema
2414 """
2415 return _dict_not_none( 1abcdefghijklmnopqr
2416 type='function-before',
2417 function=_dict_not_none(type='with-info', function=function),
2418 schema=schema,
2419 ref=ref,
2420 json_schema_input_schema=json_schema_input_schema,
2421 metadata=metadata,
2422 serialization=serialization,
2423 )
2426class AfterValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): 1abcdefghijklsmnopqr
2427 type: Required[Literal['function-after']] 1abcdefghijklsmnopqr
2430def no_info_after_validator_function( 1abcdefghijklsmnopqr
2431 function: NoInfoValidatorFunction,
2432 schema: CoreSchema,
2433 *,
2434 ref: str | None = None,
2435 json_schema_input_schema: CoreSchema | None = None,
2436 metadata: dict[str, Any] | None = None,
2437 serialization: SerSchema | None = None,
2438) -> AfterValidatorFunctionSchema:
2439 """
2440 Returns a schema that calls a validator function after validating, no `info` argument is provided, e.g.:
2442 ```py
2443 from pydantic_core import SchemaValidator, core_schema
2445 def fn(v: str) -> str:
2446 return v + 'world'
2448 func_schema = core_schema.no_info_after_validator_function(fn, core_schema.str_schema())
2449 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
2451 v = SchemaValidator(schema)
2452 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
2453 ```
2455 Args:
2456 function: The validator function to call after the schema is validated
2457 schema: The schema to validate before the validator function
2458 ref: optional unique identifier of the schema, used to reference the schema in other places
2459 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
2460 metadata: Any other information you want to include with the schema, not used by pydantic-core
2461 serialization: Custom serialization schema
2462 """
2463 return _dict_not_none( 1abcdefghijklsmnopqr
2464 type='function-after',
2465 function={'type': 'no-info', 'function': function},
2466 schema=schema,
2467 ref=ref,
2468 json_schema_input_schema=json_schema_input_schema,
2469 metadata=metadata,
2470 serialization=serialization,
2471 )
2474def with_info_after_validator_function( 1abcdefghijklsmnopqr
2475 function: WithInfoValidatorFunction,
2476 schema: CoreSchema,
2477 *,
2478 ref: str | None = None,
2479 metadata: dict[str, Any] | None = None,
2480 serialization: SerSchema | None = None,
2481) -> AfterValidatorFunctionSchema:
2482 """
2483 Returns a schema that calls a validator function after validation, the function is called with
2484 an `info` argument, e.g.:
2486 ```py
2487 from pydantic_core import SchemaValidator, core_schema
2489 def fn(v: str, info: core_schema.ValidationInfo) -> str:
2490 assert info.data is not None
2491 assert info.field_name is not None
2492 return v + 'world'
2494 func_schema = core_schema.with_info_after_validator_function(
2495 function=fn, schema=core_schema.str_schema()
2496 )
2497 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
2499 v = SchemaValidator(schema)
2500 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
2501 ```
2503 Args:
2504 function: The validator function to call after the schema is validated
2505 schema: The schema to validate before the validator function
2506 ref: optional unique identifier of the schema, used to reference the schema in other places
2507 metadata: Any other information you want to include with the schema, not used by pydantic-core
2508 serialization: Custom serialization schema
2509 """
2510 return _dict_not_none( 1abcdefghijklmnopqr
2511 type='function-after',
2512 function=_dict_not_none(type='with-info', function=function),
2513 schema=schema,
2514 ref=ref,
2515 metadata=metadata,
2516 serialization=serialization,
2517 )
2520class ValidatorFunctionWrapHandler(Protocol): 1abcdefghijklsmnopqr
2521 def __call__(self, input_value: Any, outer_location: str | int | None = None, /) -> Any: # pragma: no cover 1abcdefghijklsmnopqr
2522 ...
2525# (input_value: Any, validator: ValidatorFunctionWrapHandler, /) -> Any
2526NoInfoWrapValidatorFunction: TypeAlias = Callable[[Any, ValidatorFunctionWrapHandler], Any] 1abcdefghijklsmnopqr
2529class NoInfoWrapValidatorFunctionSchema(TypedDict): 1abcdefghijklsmnopqr
2530 type: Literal['no-info'] 1abcdefghijklsmnopqr
2531 function: NoInfoWrapValidatorFunction 1abcdefghijklsmnopqr
2534# (input_value: Any, validator: ValidatorFunctionWrapHandler, info: ValidationInfo, /) -> Any
2535WithInfoWrapValidatorFunction: TypeAlias = Callable[[Any, ValidatorFunctionWrapHandler, ValidationInfo[Any]], Any] 1abcdefghijklsmnopqr
2538class WithInfoWrapValidatorFunctionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2539 type: Required[Literal['with-info']] 1abcdefghijklsmnopqr
2540 function: Required[WithInfoWrapValidatorFunction] 1abcdefghijklsmnopqr
2543WrapValidatorFunction: TypeAlias = NoInfoWrapValidatorFunctionSchema | WithInfoWrapValidatorFunctionSchema 1abcdefghijklsmnopqr
2546class WrapValidatorFunctionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2547 type: Required[Literal['function-wrap']] 1abcdefghijklsmnopqr
2548 function: Required[WrapValidatorFunction] 1abcdefghijklsmnopqr
2549 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
2550 ref: str 1abcdefghijklsmnopqr
2551 json_schema_input_schema: CoreSchema 1abcdefghijklsmnopqr
2552 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2553 serialization: SerSchema 1abcdefghijklsmnopqr
2556def no_info_wrap_validator_function( 1abcdefghijklsmnopqr
2557 function: NoInfoWrapValidatorFunction,
2558 schema: CoreSchema,
2559 *,
2560 ref: str | None = None,
2561 json_schema_input_schema: CoreSchema | None = None,
2562 metadata: dict[str, Any] | None = None,
2563 serialization: SerSchema | None = None,
2564) -> WrapValidatorFunctionSchema:
2565 """
2566 Returns a schema which calls a function with a `validator` callable argument which can
2567 optionally be used to call inner validation with the function logic, this is much like the
2568 "onion" implementation of middleware in many popular web frameworks, no `info` argument is passed, e.g.:
2570 ```py
2571 from pydantic_core import SchemaValidator, core_schema
2573 def fn(
2574 v: str,
2575 validator: core_schema.ValidatorFunctionWrapHandler,
2576 ) -> str:
2577 return validator(input_value=v) + 'world'
2579 schema = core_schema.no_info_wrap_validator_function(
2580 function=fn, schema=core_schema.str_schema()
2581 )
2582 v = SchemaValidator(schema)
2583 assert v.validate_python('hello ') == 'hello world'
2584 ```
2586 Args:
2587 function: The validator function to call
2588 schema: The schema to validate the output of the validator function
2589 ref: optional unique identifier of the schema, used to reference the schema in other places
2590 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
2591 metadata: Any other information you want to include with the schema, not used by pydantic-core
2592 serialization: Custom serialization schema
2593 """
2594 return _dict_not_none( 1abcdefghijklmnopqr
2595 type='function-wrap',
2596 function={'type': 'no-info', 'function': function},
2597 schema=schema,
2598 json_schema_input_schema=json_schema_input_schema,
2599 ref=ref,
2600 metadata=metadata,
2601 serialization=serialization,
2602 )
2605def with_info_wrap_validator_function( 1abcdefghijklsmnopqr
2606 function: WithInfoWrapValidatorFunction,
2607 schema: CoreSchema,
2608 *,
2609 json_schema_input_schema: CoreSchema | None = None,
2610 ref: str | None = None,
2611 metadata: dict[str, Any] | None = None,
2612 serialization: SerSchema | None = None,
2613) -> WrapValidatorFunctionSchema:
2614 """
2615 Returns a schema which calls a function with a `validator` callable argument which can
2616 optionally be used to call inner validation with the function logic, this is much like the
2617 "onion" implementation of middleware in many popular web frameworks, an `info` argument is also passed, e.g.:
2619 ```py
2620 from pydantic_core import SchemaValidator, core_schema
2622 def fn(
2623 v: str,
2624 validator: core_schema.ValidatorFunctionWrapHandler,
2625 info: core_schema.ValidationInfo,
2626 ) -> str:
2627 return validator(input_value=v) + 'world'
2629 schema = core_schema.with_info_wrap_validator_function(
2630 function=fn, schema=core_schema.str_schema()
2631 )
2632 v = SchemaValidator(schema)
2633 assert v.validate_python('hello ') == 'hello world'
2634 ```
2636 Args:
2637 function: The validator function to call
2638 schema: The schema to validate the output of the validator function
2639 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
2640 ref: optional unique identifier of the schema, used to reference the schema in other places
2641 metadata: Any other information you want to include with the schema, not used by pydantic-core
2642 serialization: Custom serialization schema
2643 """
2644 return _dict_not_none( 1abcdefghijklmnopqr
2645 type='function-wrap',
2646 function=_dict_not_none(type='with-info', function=function),
2647 schema=schema,
2648 json_schema_input_schema=json_schema_input_schema,
2649 ref=ref,
2650 metadata=metadata,
2651 serialization=serialization,
2652 )
2655class PlainValidatorFunctionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2656 type: Required[Literal['function-plain']] 1abcdefghijklsmnopqr
2657 function: Required[ValidationFunction] 1abcdefghijklsmnopqr
2658 ref: str 1abcdefghijklsmnopqr
2659 json_schema_input_schema: CoreSchema 1abcdefghijklsmnopqr
2660 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2661 serialization: SerSchema 1abcdefghijklsmnopqr
2664def no_info_plain_validator_function( 1abcdefghijklsmnopqr
2665 function: NoInfoValidatorFunction,
2666 *,
2667 ref: str | None = None,
2668 json_schema_input_schema: CoreSchema | None = None,
2669 metadata: dict[str, Any] | None = None,
2670 serialization: SerSchema | None = None,
2671) -> PlainValidatorFunctionSchema:
2672 """
2673 Returns a schema that uses the provided function for validation, no `info` argument is passed, e.g.:
2675 ```py
2676 from pydantic_core import SchemaValidator, core_schema
2678 def fn(v: str) -> str:
2679 assert 'hello' in v
2680 return v + 'world'
2682 schema = core_schema.no_info_plain_validator_function(function=fn)
2683 v = SchemaValidator(schema)
2684 assert v.validate_python('hello ') == 'hello world'
2685 ```
2687 Args:
2688 function: The validator function to call
2689 ref: optional unique identifier of the schema, used to reference the schema in other places
2690 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
2691 metadata: Any other information you want to include with the schema, not used by pydantic-core
2692 serialization: Custom serialization schema
2693 """
2694 return _dict_not_none( 1abcdefghijklmnopqr
2695 type='function-plain',
2696 function={'type': 'no-info', 'function': function},
2697 ref=ref,
2698 json_schema_input_schema=json_schema_input_schema,
2699 metadata=metadata,
2700 serialization=serialization,
2701 )
2704def with_info_plain_validator_function( 1abcdefghijklsmnopqr
2705 function: WithInfoValidatorFunction,
2706 *,
2707 ref: str | None = None,
2708 json_schema_input_schema: CoreSchema | None = None,
2709 metadata: dict[str, Any] | None = None,
2710 serialization: SerSchema | None = None,
2711) -> PlainValidatorFunctionSchema:
2712 """
2713 Returns a schema that uses the provided function for validation, an `info` argument is passed, e.g.:
2715 ```py
2716 from pydantic_core import SchemaValidator, core_schema
2718 def fn(v: str, info: core_schema.ValidationInfo) -> str:
2719 assert 'hello' in v
2720 return v + 'world'
2722 schema = core_schema.with_info_plain_validator_function(function=fn)
2723 v = SchemaValidator(schema)
2724 assert v.validate_python('hello ') == 'hello world'
2725 ```
2727 Args:
2728 function: The validator function to call
2729 ref: optional unique identifier of the schema, used to reference the schema in other places
2730 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
2731 metadata: Any other information you want to include with the schema, not used by pydantic-core
2732 serialization: Custom serialization schema
2733 """
2734 return _dict_not_none( 1abcdefghijklmnopqr
2735 type='function-plain',
2736 function=_dict_not_none(type='with-info', function=function),
2737 ref=ref,
2738 json_schema_input_schema=json_schema_input_schema,
2739 metadata=metadata,
2740 serialization=serialization,
2741 )
2744class WithDefaultSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2745 type: Required[Literal['default']] 1abcdefghijklsmnopqr
2746 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
2747 default: Any 1abcdefghijklsmnopqr
2748 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] 1abcdefghijklsmnopqr
2749 default_factory_takes_data: bool 1abcdefghijklsmnopqr
2750 on_error: Literal['raise', 'omit', 'default'] # default: 'raise' 1abcdefghijklsmnopqr
2751 validate_default: bool # default: False 1abcdefghijklsmnopqr
2752 strict: bool 1abcdefghijklsmnopqr
2753 ref: str 1abcdefghijklsmnopqr
2754 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2755 serialization: SerSchema 1abcdefghijklsmnopqr
2758def with_default_schema( 1abcdefghijklsmnopqr
2759 schema: CoreSchema,
2760 *,
2761 default: Any = PydanticUndefined,
2762 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
2763 default_factory_takes_data: bool | None = None,
2764 on_error: Literal['raise', 'omit', 'default'] | None = None,
2765 validate_default: bool | None = None,
2766 strict: bool | None = None,
2767 ref: str | None = None,
2768 metadata: dict[str, Any] | None = None,
2769 serialization: SerSchema | None = None,
2770) -> WithDefaultSchema:
2771 """
2772 Returns a schema that adds a default value to the given schema, e.g.:
2774 ```py
2775 from pydantic_core import SchemaValidator, core_schema
2777 schema = core_schema.with_default_schema(core_schema.str_schema(), default='hello')
2778 wrapper_schema = core_schema.typed_dict_schema(
2779 {'a': core_schema.typed_dict_field(schema)}
2780 )
2781 v = SchemaValidator(wrapper_schema)
2782 assert v.validate_python({}) == v.validate_python({'a': 'hello'})
2783 ```
2785 Args:
2786 schema: The schema to add a default value to
2787 default: The default value to use
2788 default_factory: A callable that returns the default value to use
2789 default_factory_takes_data: Whether the default factory takes a validated data argument
2790 on_error: What to do if the schema validation fails. One of 'raise', 'omit', 'default'
2791 validate_default: Whether the default value should be validated
2792 strict: Whether the underlying schema should be validated with strict mode
2793 ref: optional unique identifier of the schema, used to reference the schema in other places
2794 metadata: Any other information you want to include with the schema, not used by pydantic-core
2795 serialization: Custom serialization schema
2796 """
2797 s = _dict_not_none( 1abcdefghijklsmnopqr
2798 type='default',
2799 schema=schema,
2800 default_factory=default_factory,
2801 default_factory_takes_data=default_factory_takes_data,
2802 on_error=on_error,
2803 validate_default=validate_default,
2804 strict=strict,
2805 ref=ref,
2806 metadata=metadata,
2807 serialization=serialization,
2808 )
2809 if default is not PydanticUndefined: 1abcdefghijklsmnopqr
2810 s['default'] = default 1abcdefghijklsmnopqr
2811 return s 1abcdefghijklsmnopqr
2814class NullableSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2815 type: Required[Literal['nullable']] 1abcdefghijklsmnopqr
2816 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
2817 strict: bool 1abcdefghijklsmnopqr
2818 ref: str 1abcdefghijklsmnopqr
2819 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2820 serialization: SerSchema 1abcdefghijklsmnopqr
2823def nullable_schema( 1abcdefghijklsmnopqr
2824 schema: CoreSchema,
2825 *,
2826 strict: bool | None = None,
2827 ref: str | None = None,
2828 metadata: dict[str, Any] | None = None,
2829 serialization: SerSchema | None = None,
2830) -> NullableSchema:
2831 """
2832 Returns a schema that matches a nullable value, e.g.:
2834 ```py
2835 from pydantic_core import SchemaValidator, core_schema
2837 schema = core_schema.nullable_schema(core_schema.str_schema())
2838 v = SchemaValidator(schema)
2839 assert v.validate_python(None) is None
2840 ```
2842 Args:
2843 schema: The schema to wrap
2844 strict: Whether the underlying schema should be validated with strict mode
2845 ref: optional unique identifier of the schema, used to reference the schema in other places
2846 metadata: Any other information you want to include with the schema, not used by pydantic-core
2847 serialization: Custom serialization schema
2848 """
2849 return _dict_not_none( 1abcdefghijklsmnopqr
2850 type='nullable', schema=schema, strict=strict, ref=ref, metadata=metadata, serialization=serialization
2851 )
2854class UnionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2855 type: Required[Literal['union']] 1abcdefghijklsmnopqr
2856 choices: Required[list[CoreSchema | tuple[CoreSchema, str]]] 1abcdefghijklsmnopqr
2857 # default true, whether to automatically collapse unions with one element to the inner validator
2858 auto_collapse: bool 1abcdefghijklsmnopqr
2859 custom_error_type: str 1abcdefghijklsmnopqr
2860 custom_error_message: str 1abcdefghijklsmnopqr
2861 custom_error_context: dict[str, str | int | float] 1abcdefghijklsmnopqr
2862 mode: Literal['smart', 'left_to_right'] # default: 'smart' 1abcdefghijklsmnopqr
2863 strict: bool 1abcdefghijklsmnopqr
2864 ref: str 1abcdefghijklsmnopqr
2865 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2866 serialization: SerSchema 1abcdefghijklsmnopqr
2869def union_schema( 1abcdefghijklsmnopqr
2870 choices: list[CoreSchema | tuple[CoreSchema, str]],
2871 *,
2872 auto_collapse: bool | None = None,
2873 custom_error_type: str | None = None,
2874 custom_error_message: str | None = None,
2875 custom_error_context: dict[str, str | int] | None = None,
2876 mode: Literal['smart', 'left_to_right'] | None = None,
2877 ref: str | None = None,
2878 metadata: dict[str, Any] | None = None,
2879 serialization: SerSchema | None = None,
2880) -> UnionSchema:
2881 """
2882 Returns a schema that matches a union value, e.g.:
2884 ```py
2885 from pydantic_core import SchemaValidator, core_schema
2887 schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()])
2888 v = SchemaValidator(schema)
2889 assert v.validate_python('hello') == 'hello'
2890 assert v.validate_python(1) == 1
2891 ```
2893 Args:
2894 choices: The schemas to match. If a tuple, the second item is used as the label for the case.
2895 auto_collapse: whether to automatically collapse unions with one element to the inner validator, default true
2896 custom_error_type: The custom error type to use if the validation fails
2897 custom_error_message: The custom error message to use if the validation fails
2898 custom_error_context: The custom error context to use if the validation fails
2899 mode: How to select which choice to return
2900 * `smart` (default) will try to return the choice which is the closest match to the input value
2901 * `left_to_right` will return the first choice in `choices` which succeeds validation
2902 ref: optional unique identifier of the schema, used to reference the schema in other places
2903 metadata: Any other information you want to include with the schema, not used by pydantic-core
2904 serialization: Custom serialization schema
2905 """
2906 return _dict_not_none( 1abcdefghijklmnopqr
2907 type='union',
2908 choices=choices,
2909 auto_collapse=auto_collapse,
2910 custom_error_type=custom_error_type,
2911 custom_error_message=custom_error_message,
2912 custom_error_context=custom_error_context,
2913 mode=mode,
2914 ref=ref,
2915 metadata=metadata,
2916 serialization=serialization,
2917 )
2920class TaggedUnionSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
2921 type: Required[Literal['tagged-union']] 1abcdefghijklsmnopqr
2922 choices: Required[dict[Any, CoreSchema]] 1abcdefghijklsmnopqr
2923 discriminator: Required[str | list[str | int] | list[list[str | int]] | Callable[[Any], Any]] 1abcdefghijklsmnopqr
2924 custom_error_type: str 1abcdefghijklsmnopqr
2925 custom_error_message: str 1abcdefghijklsmnopqr
2926 custom_error_context: dict[str, str | int | float] 1abcdefghijklsmnopqr
2927 strict: bool 1abcdefghijklsmnopqr
2928 from_attributes: bool # default: True 1abcdefghijklsmnopqr
2929 ref: str 1abcdefghijklsmnopqr
2930 metadata: dict[str, Any] 1abcdefghijklsmnopqr
2931 serialization: SerSchema 1abcdefghijklsmnopqr
2934def tagged_union_schema( 1abcdefghijklsmnopqr
2935 choices: dict[Any, CoreSchema],
2936 discriminator: str | list[str | int] | list[list[str | int]] | Callable[[Any], Any],
2937 *,
2938 custom_error_type: str | None = None,
2939 custom_error_message: str | None = None,
2940 custom_error_context: dict[str, int | str | float] | None = None,
2941 strict: bool | None = None,
2942 from_attributes: bool | None = None,
2943 ref: str | None = None,
2944 metadata: dict[str, Any] | None = None,
2945 serialization: SerSchema | None = None,
2946) -> TaggedUnionSchema:
2947 """
2948 Returns a schema that matches a tagged union value, e.g.:
2950 ```py
2951 from pydantic_core import SchemaValidator, core_schema
2953 apple_schema = core_schema.typed_dict_schema(
2954 {
2955 'foo': core_schema.typed_dict_field(core_schema.str_schema()),
2956 'bar': core_schema.typed_dict_field(core_schema.int_schema()),
2957 }
2958 )
2959 banana_schema = core_schema.typed_dict_schema(
2960 {
2961 'foo': core_schema.typed_dict_field(core_schema.str_schema()),
2962 'spam': core_schema.typed_dict_field(
2963 core_schema.list_schema(items_schema=core_schema.int_schema())
2964 ),
2965 }
2966 )
2967 schema = core_schema.tagged_union_schema(
2968 choices={
2969 'apple': apple_schema,
2970 'banana': banana_schema,
2971 },
2972 discriminator='foo',
2973 )
2974 v = SchemaValidator(schema)
2975 assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123}
2976 assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == {
2977 'foo': 'banana',
2978 'spam': [1, 2, 3],
2979 }
2980 ```
2982 Args:
2983 choices: The schemas to match
2984 When retrieving a schema from `choices` using the discriminator value, if the value is a str,
2985 it should be fed back into the `choices` map until a schema is obtained
2986 (This approach is to prevent multiple ownership of a single schema in Rust)
2987 discriminator: The discriminator to use to determine the schema to use
2988 * If `discriminator` is a str, it is the name of the attribute to use as the discriminator
2989 * If `discriminator` is a list of int/str, it should be used as a "path" to access the discriminator
2990 * If `discriminator` is a list of lists, each inner list is a path, and the first path that exists is used
2991 * If `discriminator` is a callable, it should return the discriminator when called on the value to validate;
2992 the callable can return `None` to indicate that there is no matching discriminator present on the input
2993 custom_error_type: The custom error type to use if the validation fails
2994 custom_error_message: The custom error message to use if the validation fails
2995 custom_error_context: The custom error context to use if the validation fails
2996 strict: Whether the underlying schemas should be validated with strict mode
2997 from_attributes: Whether to use the attributes of the object to retrieve the discriminator value
2998 ref: optional unique identifier of the schema, used to reference the schema in other places
2999 metadata: Any other information you want to include with the schema, not used by pydantic-core
3000 serialization: Custom serialization schema
3001 """
3002 return _dict_not_none( 1abcdefghijklmnopqr
3003 type='tagged-union',
3004 choices=choices,
3005 discriminator=discriminator,
3006 custom_error_type=custom_error_type,
3007 custom_error_message=custom_error_message,
3008 custom_error_context=custom_error_context,
3009 strict=strict,
3010 from_attributes=from_attributes,
3011 ref=ref,
3012 metadata=metadata,
3013 serialization=serialization,
3014 )
3017class ChainSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3018 type: Required[Literal['chain']] 1abcdefghijklsmnopqr
3019 steps: Required[list[CoreSchema]] 1abcdefghijklsmnopqr
3020 ref: str 1abcdefghijklsmnopqr
3021 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3022 serialization: SerSchema 1abcdefghijklsmnopqr
3025def chain_schema( 1abcdefghijklsmnopqr
3026 steps: list[CoreSchema],
3027 *,
3028 ref: str | None = None,
3029 metadata: dict[str, Any] | None = None,
3030 serialization: SerSchema | None = None,
3031) -> ChainSchema:
3032 """
3033 Returns a schema that chains the provided validation schemas, e.g.:
3035 ```py
3036 from pydantic_core import SchemaValidator, core_schema
3038 def fn(v: str, info: core_schema.ValidationInfo) -> str:
3039 assert 'hello' in v
3040 return v + ' world'
3042 fn_schema = core_schema.with_info_plain_validator_function(function=fn)
3043 schema = core_schema.chain_schema(
3044 [fn_schema, fn_schema, fn_schema, core_schema.str_schema()]
3045 )
3046 v = SchemaValidator(schema)
3047 assert v.validate_python('hello') == 'hello world world world'
3048 ```
3050 Args:
3051 steps: The schemas to chain
3052 ref: optional unique identifier of the schema, used to reference the schema in other places
3053 metadata: Any other information you want to include with the schema, not used by pydantic-core
3054 serialization: Custom serialization schema
3055 """
3056 return _dict_not_none(type='chain', steps=steps, ref=ref, metadata=metadata, serialization=serialization) 1abcdefghijklmnopqr
3059class LaxOrStrictSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3060 type: Required[Literal['lax-or-strict']] 1abcdefghijklsmnopqr
3061 lax_schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3062 strict_schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3063 strict: bool 1abcdefghijklsmnopqr
3064 ref: str 1abcdefghijklsmnopqr
3065 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3066 serialization: SerSchema 1abcdefghijklsmnopqr
3069def lax_or_strict_schema( 1abcdefghijklsmnopqr
3070 lax_schema: CoreSchema,
3071 strict_schema: CoreSchema,
3072 *,
3073 strict: bool | None = None,
3074 ref: str | None = None,
3075 metadata: dict[str, Any] | None = None,
3076 serialization: SerSchema | None = None,
3077) -> LaxOrStrictSchema:
3078 """
3079 Returns a schema that uses the lax or strict schema, e.g.:
3081 ```py
3082 from pydantic_core import SchemaValidator, core_schema
3084 def fn(v: str, info: core_schema.ValidationInfo) -> str:
3085 assert 'hello' in v
3086 return v + ' world'
3088 lax_schema = core_schema.int_schema(strict=False)
3089 strict_schema = core_schema.int_schema(strict=True)
3091 schema = core_schema.lax_or_strict_schema(
3092 lax_schema=lax_schema, strict_schema=strict_schema, strict=True
3093 )
3094 v = SchemaValidator(schema)
3095 assert v.validate_python(123) == 123
3097 schema = core_schema.lax_or_strict_schema(
3098 lax_schema=lax_schema, strict_schema=strict_schema, strict=False
3099 )
3100 v = SchemaValidator(schema)
3101 assert v.validate_python('123') == 123
3102 ```
3104 Args:
3105 lax_schema: The lax schema to use
3106 strict_schema: The strict schema to use
3107 strict: Whether the strict schema should be used
3108 ref: optional unique identifier of the schema, used to reference the schema in other places
3109 metadata: Any other information you want to include with the schema, not used by pydantic-core
3110 serialization: Custom serialization schema
3111 """
3112 return _dict_not_none( 1abcdefghijklmnopqr
3113 type='lax-or-strict',
3114 lax_schema=lax_schema,
3115 strict_schema=strict_schema,
3116 strict=strict,
3117 ref=ref,
3118 metadata=metadata,
3119 serialization=serialization,
3120 )
3123class JsonOrPythonSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3124 type: Required[Literal['json-or-python']] 1abcdefghijklsmnopqr
3125 json_schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3126 python_schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3127 ref: str 1abcdefghijklsmnopqr
3128 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3129 serialization: SerSchema 1abcdefghijklsmnopqr
3132def json_or_python_schema( 1abcdefghijklsmnopqr
3133 json_schema: CoreSchema,
3134 python_schema: CoreSchema,
3135 *,
3136 ref: str | None = None,
3137 metadata: dict[str, Any] | None = None,
3138 serialization: SerSchema | None = None,
3139) -> JsonOrPythonSchema:
3140 """
3141 Returns a schema that uses the Json or Python schema depending on the input:
3143 ```py
3144 from pydantic_core import SchemaValidator, ValidationError, core_schema
3146 v = SchemaValidator(
3147 core_schema.json_or_python_schema(
3148 json_schema=core_schema.int_schema(),
3149 python_schema=core_schema.int_schema(strict=True),
3150 )
3151 )
3153 assert v.validate_json('"123"') == 123
3155 try:
3156 v.validate_python('123')
3157 except ValidationError:
3158 pass
3159 else:
3160 raise AssertionError('Validation should have failed')
3161 ```
3163 Args:
3164 json_schema: The schema to use for Json inputs
3165 python_schema: The schema to use for Python inputs
3166 ref: optional unique identifier of the schema, used to reference the schema in other places
3167 metadata: Any other information you want to include with the schema, not used by pydantic-core
3168 serialization: Custom serialization schema
3169 """
3170 return _dict_not_none( 1abcdefghijklmnopqr
3171 type='json-or-python',
3172 json_schema=json_schema,
3173 python_schema=python_schema,
3174 ref=ref,
3175 metadata=metadata,
3176 serialization=serialization,
3177 )
3180class TypedDictField(TypedDict, total=False): 1abcdefghijklsmnopqr
3181 type: Required[Literal['typed-dict-field']] 1abcdefghijklsmnopqr
3182 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3183 required: bool 1abcdefghijklsmnopqr
3184 validation_alias: str | list[str | int] | list[list[str | int]] 1abcdefghijklsmnopqr
3185 serialization_alias: str 1abcdefghijklsmnopqr
3186 serialization_exclude: bool # default: False 1abcdefghijklsmnopqr
3187 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3188 serialization_exclude_if: Callable[[Any], bool] # default None 1abcdefghijklsmnopqr
3191def typed_dict_field( 1abcdefghijklsmnopqr
3192 schema: CoreSchema,
3193 *,
3194 required: bool | None = None,
3195 validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
3196 serialization_alias: str | None = None,
3197 serialization_exclude: bool | None = None,
3198 metadata: dict[str, Any] | None = None,
3199 serialization_exclude_if: Callable[[Any], bool] | None = None,
3200) -> TypedDictField:
3201 """
3202 Returns a schema that matches a typed dict field, e.g.:
3204 ```py
3205 from pydantic_core import core_schema
3207 field = core_schema.typed_dict_field(schema=core_schema.int_schema(), required=True)
3208 ```
3210 Args:
3211 schema: The schema to use for the field
3212 required: Whether the field is required, otherwise uses the value from `total` on the typed dict
3213 validation_alias: The alias(es) to use to find the field in the validation data
3214 serialization_alias: The alias to use as a key when serializing
3215 serialization_exclude: Whether to exclude the field when serializing
3216 serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value.
3217 metadata: Any other information you want to include with the schema, not used by pydantic-core
3218 """
3219 return _dict_not_none( 1abcdefghijklmnopqr
3220 type='typed-dict-field',
3221 schema=schema,
3222 required=required,
3223 validation_alias=validation_alias,
3224 serialization_alias=serialization_alias,
3225 serialization_exclude=serialization_exclude,
3226 serialization_exclude_if=serialization_exclude_if,
3227 metadata=metadata,
3228 )
3231class TypedDictSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3232 type: Required[Literal['typed-dict']] 1abcdefghijklsmnopqr
3233 fields: Required[dict[str, TypedDictField]] 1abcdefghijklsmnopqr
3234 cls: type[Any] 1abcdefghijklsmnopqr
3235 cls_name: str 1abcdefghijklsmnopqr
3236 computed_fields: list[ComputedField] 1abcdefghijklsmnopqr
3237 strict: bool 1abcdefghijklsmnopqr
3238 extras_schema: CoreSchema 1abcdefghijklsmnopqr
3239 # all these values can be set via config, equivalent fields have `typed_dict_` prefix
3240 extra_behavior: ExtraBehavior 1abcdefghijklsmnopqr
3241 total: bool # default: True 1abcdefghijklsmnopqr
3242 ref: str 1abcdefghijklsmnopqr
3243 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3244 serialization: SerSchema 1abcdefghijklsmnopqr
3245 config: CoreConfig 1abcdefghijklsmnopqr
3248def typed_dict_schema( 1abcdefghijklsmnopqr
3249 fields: dict[str, TypedDictField],
3250 *,
3251 cls: type[Any] | None = None,
3252 cls_name: str | None = None,
3253 computed_fields: list[ComputedField] | None = None,
3254 strict: bool | None = None,
3255 extras_schema: CoreSchema | None = None,
3256 extra_behavior: ExtraBehavior | None = None,
3257 total: bool | None = None,
3258 ref: str | None = None,
3259 metadata: dict[str, Any] | None = None,
3260 serialization: SerSchema | None = None,
3261 config: CoreConfig | None = None,
3262) -> TypedDictSchema:
3263 """
3264 Returns a schema that matches a typed dict, e.g.:
3266 ```py
3267 from typing_extensions import TypedDict
3269 from pydantic_core import SchemaValidator, core_schema
3271 class MyTypedDict(TypedDict):
3272 a: str
3274 wrapper_schema = core_schema.typed_dict_schema(
3275 {'a': core_schema.typed_dict_field(core_schema.str_schema())}, cls=MyTypedDict
3276 )
3277 v = SchemaValidator(wrapper_schema)
3278 assert v.validate_python({'a': 'hello'}) == {'a': 'hello'}
3279 ```
3281 Args:
3282 fields: The fields to use for the typed dict
3283 cls: The class to use for the typed dict
3284 cls_name: The name to use in error locations. Falls back to `cls.__name__`, or the validator name if no class
3285 is provided.
3286 computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model
3287 strict: Whether the typed dict is strict
3288 extras_schema: The extra validator to use for the typed dict
3289 ref: optional unique identifier of the schema, used to reference the schema in other places
3290 metadata: Any other information you want to include with the schema, not used by pydantic-core
3291 extra_behavior: The extra behavior to use for the typed dict
3292 total: Whether the typed dict is total, otherwise uses `typed_dict_total` from config
3293 serialization: Custom serialization schema
3294 """
3295 return _dict_not_none( 1abcdefghijklmnopqr
3296 type='typed-dict',
3297 fields=fields,
3298 cls=cls,
3299 cls_name=cls_name,
3300 computed_fields=computed_fields,
3301 strict=strict,
3302 extras_schema=extras_schema,
3303 extra_behavior=extra_behavior,
3304 total=total,
3305 ref=ref,
3306 metadata=metadata,
3307 serialization=serialization,
3308 config=config,
3309 )
3312class ModelField(TypedDict, total=False): 1abcdefghijklsmnopqr
3313 type: Required[Literal['model-field']] 1abcdefghijklsmnopqr
3314 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3315 validation_alias: str | list[str | int] | list[list[str | int]] 1abcdefghijklsmnopqr
3316 serialization_alias: str 1abcdefghijklsmnopqr
3317 serialization_exclude: bool # default: False 1abcdefghijklsmnopqr
3318 serialization_exclude_if: Callable[[Any], bool] # default: None 1abcdefghijklsmnopqr
3319 frozen: bool 1abcdefghijklsmnopqr
3320 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3323def model_field( 1abcdefghijklsmnopqr
3324 schema: CoreSchema,
3325 *,
3326 validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
3327 serialization_alias: str | None = None,
3328 serialization_exclude: bool | None = None,
3329 serialization_exclude_if: Callable[[Any], bool] | None = None,
3330 frozen: bool | None = None,
3331 metadata: dict[str, Any] | None = None,
3332) -> ModelField:
3333 """
3334 Returns a schema for a model field, e.g.:
3336 ```py
3337 from pydantic_core import core_schema
3339 field = core_schema.model_field(schema=core_schema.int_schema())
3340 ```
3342 Args:
3343 schema: The schema to use for the field
3344 validation_alias: The alias(es) to use to find the field in the validation data
3345 serialization_alias: The alias to use as a key when serializing
3346 serialization_exclude: Whether to exclude the field when serializing
3347 serialization_exclude_if: A Callable that determines whether to exclude a field during serialization based on its value.
3348 frozen: Whether the field is frozen
3349 metadata: Any other information you want to include with the schema, not used by pydantic-core
3350 """
3351 return _dict_not_none( 1abcdefghijklsmnopqr
3352 type='model-field',
3353 schema=schema,
3354 validation_alias=validation_alias,
3355 serialization_alias=serialization_alias,
3356 serialization_exclude=serialization_exclude,
3357 serialization_exclude_if=serialization_exclude_if,
3358 frozen=frozen,
3359 metadata=metadata,
3360 )
3363class ModelFieldsSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3364 type: Required[Literal['model-fields']] 1abcdefghijklsmnopqr
3365 fields: Required[dict[str, ModelField]] 1abcdefghijklsmnopqr
3366 model_name: str 1abcdefghijklsmnopqr
3367 computed_fields: list[ComputedField] 1abcdefghijklsmnopqr
3368 strict: bool 1abcdefghijklsmnopqr
3369 extras_schema: CoreSchema 1abcdefghijklsmnopqr
3370 extras_keys_schema: CoreSchema 1abcdefghijklsmnopqr
3371 extra_behavior: ExtraBehavior 1abcdefghijklsmnopqr
3372 from_attributes: bool 1abcdefghijklsmnopqr
3373 ref: str 1abcdefghijklsmnopqr
3374 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3375 serialization: SerSchema 1abcdefghijklsmnopqr
3378def model_fields_schema( 1abcdefghijklsmnopqr
3379 fields: dict[str, ModelField],
3380 *,
3381 model_name: str | None = None,
3382 computed_fields: list[ComputedField] | None = None,
3383 strict: bool | None = None,
3384 extras_schema: CoreSchema | None = None,
3385 extras_keys_schema: CoreSchema | None = None,
3386 extra_behavior: ExtraBehavior | None = None,
3387 from_attributes: bool | None = None,
3388 ref: str | None = None,
3389 metadata: dict[str, Any] | None = None,
3390 serialization: SerSchema | None = None,
3391) -> ModelFieldsSchema:
3392 """
3393 Returns a schema that matches the fields of a Pydantic model, e.g.:
3395 ```py
3396 from pydantic_core import SchemaValidator, core_schema
3398 wrapper_schema = core_schema.model_fields_schema(
3399 {'a': core_schema.model_field(core_schema.str_schema())}
3400 )
3401 v = SchemaValidator(wrapper_schema)
3402 print(v.validate_python({'a': 'hello'}))
3403 #> ({'a': 'hello'}, None, {'a'})
3404 ```
3406 Args:
3407 fields: The fields of the model
3408 model_name: The name of the model, used for error messages, defaults to "Model"
3409 computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model
3410 strict: Whether the model is strict
3411 extras_schema: The schema to use when validating extra input data
3412 extras_keys_schema: The schema to use when validating the keys of extra input data
3413 ref: optional unique identifier of the schema, used to reference the schema in other places
3414 metadata: Any other information you want to include with the schema, not used by pydantic-core
3415 extra_behavior: The extra behavior to use for the model fields
3416 from_attributes: Whether the model fields should be populated from attributes
3417 serialization: Custom serialization schema
3418 """
3419 return _dict_not_none( 1abcdefghijklsmnopqr
3420 type='model-fields',
3421 fields=fields,
3422 model_name=model_name,
3423 computed_fields=computed_fields,
3424 strict=strict,
3425 extras_schema=extras_schema,
3426 extras_keys_schema=extras_keys_schema,
3427 extra_behavior=extra_behavior,
3428 from_attributes=from_attributes,
3429 ref=ref,
3430 metadata=metadata,
3431 serialization=serialization,
3432 )
3435class ModelSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3436 type: Required[Literal['model']] 1abcdefghijklsmnopqr
3437 cls: Required[type[Any]] 1abcdefghijklsmnopqr
3438 generic_origin: type[Any] 1abcdefghijklsmnopqr
3439 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3440 custom_init: bool 1abcdefghijklsmnopqr
3441 root_model: bool 1abcdefghijklsmnopqr
3442 post_init: str 1abcdefghijklsmnopqr
3443 revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never' 1abcdefghijklsmnopqr
3444 strict: bool 1abcdefghijklsmnopqr
3445 frozen: bool 1abcdefghijklsmnopqr
3446 extra_behavior: ExtraBehavior 1abcdefghijklsmnopqr
3447 config: CoreConfig 1abcdefghijklsmnopqr
3448 ref: str 1abcdefghijklsmnopqr
3449 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3450 serialization: SerSchema 1abcdefghijklsmnopqr
3453def model_schema( 1abcdefghijklsmnopqr
3454 cls: type[Any],
3455 schema: CoreSchema,
3456 *,
3457 generic_origin: type[Any] | None = None,
3458 custom_init: bool | None = None,
3459 root_model: bool | None = None,
3460 post_init: str | None = None,
3461 revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
3462 strict: bool | None = None,
3463 frozen: bool | None = None,
3464 extra_behavior: ExtraBehavior | None = None,
3465 config: CoreConfig | None = None,
3466 ref: str | None = None,
3467 metadata: dict[str, Any] | None = None,
3468 serialization: SerSchema | None = None,
3469) -> ModelSchema:
3470 """
3471 A model schema generally contains a typed-dict schema.
3472 It will run the typed dict validator, then create a new class
3473 and set the dict and fields set returned from the typed dict validator
3474 to `__dict__` and `__pydantic_fields_set__` respectively.
3476 Example:
3478 ```py
3479 from pydantic_core import CoreConfig, SchemaValidator, core_schema
3481 class MyModel:
3482 __slots__ = (
3483 '__dict__',
3484 '__pydantic_extra__',
3485 '__pydantic_fields_set__',
3486 '__pydantic_private__',
3487 )
3489 schema = core_schema.model_schema(
3490 cls=MyModel,
3491 config=CoreConfig(str_max_length=5),
3492 schema=core_schema.model_fields_schema(
3493 fields={'a': core_schema.model_field(core_schema.str_schema())},
3494 ),
3495 )
3496 v = SchemaValidator(schema)
3497 assert v.isinstance_python({'a': 'hello'}) is True
3498 assert v.isinstance_python({'a': 'too long'}) is False
3499 ```
3501 Args:
3502 cls: The class to use for the model
3503 schema: The schema to use for the model
3504 generic_origin: The origin type used for this model, if it's a parametrized generic. Ex,
3505 if this model schema represents `SomeModel[int]`, generic_origin is `SomeModel`
3506 custom_init: Whether the model has a custom init method
3507 root_model: Whether the model is a `RootModel`
3508 post_init: The call after init to use for the model
3509 revalidate_instances: whether instances of models and dataclasses (including subclass instances)
3510 should re-validate defaults to config.revalidate_instances, else 'never'
3511 strict: Whether the model is strict
3512 frozen: Whether the model is frozen
3513 extra_behavior: The extra behavior to use for the model, used in serialization
3514 config: The config to use for the model
3515 ref: optional unique identifier of the schema, used to reference the schema in other places
3516 metadata: Any other information you want to include with the schema, not used by pydantic-core
3517 serialization: Custom serialization schema
3518 """
3519 return _dict_not_none( 1abcdefghijklsmnopqr
3520 type='model',
3521 cls=cls,
3522 generic_origin=generic_origin,
3523 schema=schema,
3524 custom_init=custom_init,
3525 root_model=root_model,
3526 post_init=post_init,
3527 revalidate_instances=revalidate_instances,
3528 strict=strict,
3529 frozen=frozen,
3530 extra_behavior=extra_behavior,
3531 config=config,
3532 ref=ref,
3533 metadata=metadata,
3534 serialization=serialization,
3535 )
3538class DataclassField(TypedDict, total=False): 1abcdefghijklsmnopqr
3539 type: Required[Literal['dataclass-field']] 1abcdefghijklsmnopqr
3540 name: Required[str] 1abcdefghijklsmnopqr
3541 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3542 kw_only: bool # default: True 1abcdefghijklsmnopqr
3543 init: bool # default: True 1abcdefghijklsmnopqr
3544 init_only: bool # default: False 1abcdefghijklsmnopqr
3545 frozen: bool # default: False 1abcdefghijklsmnopqr
3546 validation_alias: str | list[str | int] | list[list[str | int]] 1abcdefghijklsmnopqr
3547 serialization_alias: str 1abcdefghijklsmnopqr
3548 serialization_exclude: bool # default: False 1abcdefghijklsmnopqr
3549 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3550 serialization_exclude_if: Callable[[Any], bool] # default: None 1abcdefghijklsmnopqr
3553def dataclass_field( 1abcdefghijklsmnopqr
3554 name: str,
3555 schema: CoreSchema,
3556 *,
3557 kw_only: bool | None = None,
3558 init: bool | None = None,
3559 init_only: bool | None = None,
3560 validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
3561 serialization_alias: str | None = None,
3562 serialization_exclude: bool | None = None,
3563 metadata: dict[str, Any] | None = None,
3564 serialization_exclude_if: Callable[[Any], bool] | None = None,
3565 frozen: bool | None = None,
3566) -> DataclassField:
3567 """
3568 Returns a schema for a dataclass field, e.g.:
3570 ```py
3571 from pydantic_core import SchemaValidator, core_schema
3573 field = core_schema.dataclass_field(
3574 name='a', schema=core_schema.str_schema(), kw_only=False
3575 )
3576 schema = core_schema.dataclass_args_schema('Foobar', [field])
3577 v = SchemaValidator(schema)
3578 assert v.validate_python({'a': 'hello'}) == ({'a': 'hello'}, None)
3579 ```
3581 Args:
3582 name: The name to use for the argument parameter
3583 schema: The schema to use for the argument parameter
3584 kw_only: Whether the field can be set with a positional argument as well as a keyword argument
3585 init: Whether the field should be validated during initialization
3586 init_only: Whether the field should be omitted from `__dict__` and passed to `__post_init__`
3587 validation_alias: The alias(es) to use to find the field in the validation data
3588 serialization_alias: The alias to use as a key when serializing
3589 serialization_exclude: Whether to exclude the field when serializing
3590 serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value.
3591 metadata: Any other information you want to include with the schema, not used by pydantic-core
3592 frozen: Whether the field is frozen
3593 """
3594 return _dict_not_none( 1abcdefghijklsmnopqr
3595 type='dataclass-field',
3596 name=name,
3597 schema=schema,
3598 kw_only=kw_only,
3599 init=init,
3600 init_only=init_only,
3601 validation_alias=validation_alias,
3602 serialization_alias=serialization_alias,
3603 serialization_exclude=serialization_exclude,
3604 serialization_exclude_if=serialization_exclude_if,
3605 metadata=metadata,
3606 frozen=frozen,
3607 )
3610class DataclassArgsSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3611 type: Required[Literal['dataclass-args']] 1abcdefghijklsmnopqr
3612 dataclass_name: Required[str] 1abcdefghijklsmnopqr
3613 fields: Required[list[DataclassField]] 1abcdefghijklsmnopqr
3614 computed_fields: list[ComputedField] 1abcdefghijklsmnopqr
3615 collect_init_only: bool # default: False 1abcdefghijklsmnopqr
3616 ref: str 1abcdefghijklsmnopqr
3617 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3618 serialization: SerSchema 1abcdefghijklsmnopqr
3619 extra_behavior: ExtraBehavior 1abcdefghijklsmnopqr
3622def dataclass_args_schema( 1abcdefghijklsmnopqr
3623 dataclass_name: str,
3624 fields: list[DataclassField],
3625 *,
3626 computed_fields: list[ComputedField] | None = None,
3627 collect_init_only: bool | None = None,
3628 ref: str | None = None,
3629 metadata: dict[str, Any] | None = None,
3630 serialization: SerSchema | None = None,
3631 extra_behavior: ExtraBehavior | None = None,
3632) -> DataclassArgsSchema:
3633 """
3634 Returns a schema for validating dataclass arguments, e.g.:
3636 ```py
3637 from pydantic_core import SchemaValidator, core_schema
3639 field_a = core_schema.dataclass_field(
3640 name='a', schema=core_schema.str_schema(), kw_only=False
3641 )
3642 field_b = core_schema.dataclass_field(
3643 name='b', schema=core_schema.bool_schema(), kw_only=False
3644 )
3645 schema = core_schema.dataclass_args_schema('Foobar', [field_a, field_b])
3646 v = SchemaValidator(schema)
3647 assert v.validate_python({'a': 'hello', 'b': True}) == ({'a': 'hello', 'b': True}, None)
3648 ```
3650 Args:
3651 dataclass_name: The name of the dataclass being validated
3652 fields: The fields to use for the dataclass
3653 computed_fields: Computed fields to use when serializing the dataclass
3654 collect_init_only: Whether to collect init only fields into a dict to pass to `__post_init__`
3655 ref: optional unique identifier of the schema, used to reference the schema in other places
3656 metadata: Any other information you want to include with the schema, not used by pydantic-core
3657 serialization: Custom serialization schema
3658 extra_behavior: How to handle extra fields
3659 """
3660 return _dict_not_none( 1abcdefghijklsmnopqr
3661 type='dataclass-args',
3662 dataclass_name=dataclass_name,
3663 fields=fields,
3664 computed_fields=computed_fields,
3665 collect_init_only=collect_init_only,
3666 ref=ref,
3667 metadata=metadata,
3668 serialization=serialization,
3669 extra_behavior=extra_behavior,
3670 )
3673class DataclassSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3674 type: Required[Literal['dataclass']] 1abcdefghijklsmnopqr
3675 cls: Required[type[Any]] 1abcdefghijklsmnopqr
3676 generic_origin: type[Any] 1abcdefghijklsmnopqr
3677 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3678 fields: Required[list[str]] 1abcdefghijklsmnopqr
3679 cls_name: str 1abcdefghijklsmnopqr
3680 post_init: bool # default: False 1abcdefghijklsmnopqr
3681 revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never' 1abcdefghijklsmnopqr
3682 strict: bool # default: False 1abcdefghijklsmnopqr
3683 frozen: bool # default False 1abcdefghijklsmnopqr
3684 ref: str 1abcdefghijklsmnopqr
3685 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3686 serialization: SerSchema 1abcdefghijklsmnopqr
3687 slots: bool 1abcdefghijklsmnopqr
3688 config: CoreConfig 1abcdefghijklsmnopqr
3691def dataclass_schema( 1abcdefghijklsmnopqr
3692 cls: type[Any],
3693 schema: CoreSchema,
3694 fields: list[str],
3695 *,
3696 generic_origin: type[Any] | None = None,
3697 cls_name: str | None = None,
3698 post_init: bool | None = None,
3699 revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
3700 strict: bool | None = None,
3701 ref: str | None = None,
3702 metadata: dict[str, Any] | None = None,
3703 serialization: SerSchema | None = None,
3704 frozen: bool | None = None,
3705 slots: bool | None = None,
3706 config: CoreConfig | None = None,
3707) -> DataclassSchema:
3708 """
3709 Returns a schema for a dataclass. As with `ModelSchema`, this schema can only be used as a field within
3710 another schema, not as the root type.
3712 Args:
3713 cls: The dataclass type, used to perform subclass checks
3714 schema: The schema to use for the dataclass fields
3715 fields: Fields of the dataclass, this is used in serialization and in validation during re-validation
3716 and while validating assignment
3717 generic_origin: The origin type used for this dataclass, if it's a parametrized generic. Ex,
3718 if this model schema represents `SomeDataclass[int]`, generic_origin is `SomeDataclass`
3719 cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`)
3720 post_init: Whether to call `__post_init__` after validation
3721 revalidate_instances: whether instances of models and dataclasses (including subclass instances)
3722 should re-validate defaults to config.revalidate_instances, else 'never'
3723 strict: Whether to require an exact instance of `cls`
3724 ref: optional unique identifier of the schema, used to reference the schema in other places
3725 metadata: Any other information you want to include with the schema, not used by pydantic-core
3726 serialization: Custom serialization schema
3727 frozen: Whether the dataclass is frozen
3728 slots: Whether `slots=True` on the dataclass, means each field is assigned independently, rather than
3729 simply setting `__dict__`, default false
3730 """
3731 return _dict_not_none( 1abcdefghijklsmnopqr
3732 type='dataclass',
3733 cls=cls,
3734 generic_origin=generic_origin,
3735 fields=fields,
3736 cls_name=cls_name,
3737 schema=schema,
3738 post_init=post_init,
3739 revalidate_instances=revalidate_instances,
3740 strict=strict,
3741 ref=ref,
3742 metadata=metadata,
3743 serialization=serialization,
3744 frozen=frozen,
3745 slots=slots,
3746 config=config,
3747 )
3750class NamedTupleField(TypedDict, total=False): 1abcdefghijklsmnopqr
3751 type: Required[Literal['named-tuple-field']] 1abcdefghijklsmnopqr
3752 name: Required[str] 1abcdefghijklsmnopqr
3753 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3754 validation_alias: str | list[str | int] | list[list[str | int]] 1abcdefghijklsmnopqr
3755 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3758def named_tuple_field( 1abcdefghijklsmnopqr
3759 name: str,
3760 schema: CoreSchema,
3761 *,
3762 validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
3763 metadata: dict[str, Any] | None = None,
3764) -> NamedTupleField:
3765 """
3766 Returns a schema for a named tuple field, e.g.:
3768 ```py
3769 from pydantic_core import core_schema
3771 field = core_schema.named_tuple_field(name='x', schema=core_schema.int_schema())
3772 ```
3774 Args:
3775 name: The name of the field
3776 schema: The schema to use for the field
3777 validation_alias: The alias(es) to use to find the field in the validation data, only used
3778 when validating from a dictionary or mapping
3779 metadata: Any other information you want to include with the schema, not used by pydantic-core
3780 """
3781 return _dict_not_none( 1abcdefghijklmnopqr
3782 type='named-tuple-field',
3783 name=name,
3784 schema=schema,
3785 validation_alias=validation_alias,
3786 metadata=metadata,
3787 )
3790class NamedTupleSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3791 type: Required[Literal['named-tuple']] 1abcdefghijklsmnopqr
3792 cls: Required[type[Any]] 1abcdefghijklsmnopqr
3793 fields: Required[list[NamedTupleField]] 1abcdefghijklsmnopqr
3794 cls_name: str 1abcdefghijklsmnopqr
3795 ref: str 1abcdefghijklsmnopqr
3796 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3797 serialization: SerSchema 1abcdefghijklsmnopqr
3800def named_tuple_schema( 1abcdefghijklsmnopqr
3801 cls: type[Any],
3802 fields: list[NamedTupleField],
3803 *,
3804 cls_name: str | None = None,
3805 ref: str | None = None,
3806 metadata: dict[str, Any] | None = None,
3807 serialization: SerSchema | None = None,
3808) -> NamedTupleSchema:
3809 """
3810 Returns a schema for a named tuple, e.g.:
3812 ```py
3813 from typing import NamedTuple
3815 from pydantic_core import SchemaValidator, core_schema
3817 class Point(NamedTuple):
3818 x: int
3819 y: int
3821 schema = core_schema.named_tuple_schema(
3822 Point,
3823 [
3824 core_schema.named_tuple_field(name='x', schema=core_schema.int_schema()),
3825 core_schema.named_tuple_field(name='y', schema=core_schema.int_schema()),
3826 ],
3827 )
3828 v = SchemaValidator(schema)
3829 assert v.validate_python((1, '2')) == Point(x=1, y=2)
3830 ```
3832 Fields are validated positionally when the input is a (named) tuple, list or JSON array,
3833 and by name when the input is a dictionary, mapping or JSON object. Instances of `cls`
3834 always revalidate. Strict mode is currently ignored, matching the behavior of the
3835 `'call'` core schema previously used for named tuples.
3837 Args:
3838 cls: The named tuple class, used to construct instances and perform instance checks
3839 fields: The fields to use for the named tuple, in order
3840 cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`)
3841 ref: optional unique identifier of the schema, used to reference the schema in other places
3842 metadata: Any other information you want to include with the schema, not used by pydantic-core
3843 serialization: Custom serialization schema
3844 """
3845 return _dict_not_none( 1abcdefghijklmnopqr
3846 type='named-tuple',
3847 cls=cls,
3848 fields=fields,
3849 cls_name=cls_name,
3850 ref=ref,
3851 metadata=metadata,
3852 serialization=serialization,
3853 )
3856class ArgumentsParameter(TypedDict, total=False): 1abcdefghijklsmnopqr
3857 name: Required[str] 1abcdefghijklsmnopqr
3858 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3859 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] # default positional_or_keyword 1abcdefghijklsmnopqr
3860 alias: str | list[str | int] | list[list[str | int]] 1abcdefghijklsmnopqr
3863@deprecated('`arguments_parameter()` is deprecated, use `arguments_v3_parameter()` instead.') 1abcdefghijklsmnopqr
3864def arguments_parameter( 1abcdefghijklsmnopqr
3865 name: str,
3866 schema: CoreSchema,
3867 *,
3868 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None,
3869 alias: str | list[str | int] | list[list[str | int]] | None = None,
3870) -> ArgumentsParameter:
3871 """
3872 Returns a schema that matches an argument parameter.
3874 Deprecated: use [`arguments_v3_parameter()`][pydantic_core.core_schema.arguments_v3_parameter] instead.
3876 Args:
3877 name: The name to use for the argument parameter
3878 schema: The schema to use for the argument parameter
3879 mode: The mode to use for the argument parameter
3880 alias: The alias to use for the argument parameter
3881 """
3882 return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias) 1abcdefghijklmnopqr
3885VarKwargsMode: TypeAlias = Literal['uniform', 'unpacked-typed-dict'] 1abcdefghijklsmnopqr
3888class ArgumentsSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
3889 type: Required[Literal['arguments']] 1abcdefghijklsmnopqr
3890 arguments_schema: Required[list[ArgumentsParameter]] 1abcdefghijklsmnopqr
3891 validate_by_name: bool 1abcdefghijklsmnopqr
3892 validate_by_alias: bool 1abcdefghijklsmnopqr
3893 var_args_schema: CoreSchema 1abcdefghijklsmnopqr
3894 var_kwargs_mode: VarKwargsMode 1abcdefghijklsmnopqr
3895 var_kwargs_schema: CoreSchema 1abcdefghijklsmnopqr
3896 ref: str 1abcdefghijklsmnopqr
3897 metadata: dict[str, Any] 1abcdefghijklsmnopqr
3898 serialization: SerSchema 1abcdefghijklsmnopqr
3901@deprecated('`arguments_schema()` is deprecated, use `arguments_v3_schema()` instead.') 1abcdefghijklsmnopqr
3902def arguments_schema( 1abcdefghijklsmnopqr
3903 arguments: list[ArgumentsParameter],
3904 *,
3905 validate_by_name: bool | None = None,
3906 validate_by_alias: bool | None = None,
3907 var_args_schema: CoreSchema | None = None,
3908 var_kwargs_mode: VarKwargsMode | None = None,
3909 var_kwargs_schema: CoreSchema | None = None,
3910 ref: str | None = None,
3911 metadata: dict[str, Any] | None = None,
3912 serialization: SerSchema | None = None,
3913) -> ArgumentsSchema:
3914 """
3915 Returns a schema that matches an arguments schema.
3917 Deprecated: use [`arguments_v3_schema()`][pydantic_core.core_schema.arguments_v3_schema] instead.
3919 Args:
3920 arguments: The arguments to use for the arguments schema
3921 validate_by_name: Whether to populate by the parameter names, defaults to `False`.
3922 validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`.
3923 var_args_schema: The variable args schema to use for the arguments schema
3924 var_kwargs_mode: The validation mode to use for variadic keyword arguments. If `'uniform'`, every value of the
3925 keyword arguments will be validated against the `var_kwargs_schema` schema. If `'unpacked-typed-dict'`,
3926 the `var_kwargs_schema` argument must be a [`typed_dict_schema`][pydantic_core.core_schema.typed_dict_schema]
3927 var_kwargs_schema: The variable kwargs schema to use for the arguments schema
3928 ref: optional unique identifier of the schema, used to reference the schema in other places
3929 metadata: Any other information you want to include with the schema, not used by pydantic-core
3930 serialization: Custom serialization schema
3931 """
3932 return _dict_not_none( 1abcdefghijklmnopqr
3933 type='arguments',
3934 arguments_schema=arguments,
3935 validate_by_name=validate_by_name,
3936 validate_by_alias=validate_by_alias,
3937 var_args_schema=var_args_schema,
3938 var_kwargs_mode=var_kwargs_mode,
3939 var_kwargs_schema=var_kwargs_schema,
3940 ref=ref,
3941 metadata=metadata,
3942 serialization=serialization,
3943 )
3946class ArgumentsV3Parameter(TypedDict, total=False): 1abcdefghijklsmnopqr
3947 name: Required[str] 1abcdefghijklsmnopqr
3948 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
3949 mode: Literal[ 1abcdefghijklsmnopqr
3950 'positional_only',
3951 'positional_or_keyword',
3952 'keyword_only',
3953 'var_args',
3954 'var_kwargs_uniform',
3955 'var_kwargs_unpacked_typed_dict',
3956 ] # default positional_or_keyword
3957 alias: str | list[str | int] | list[list[str | int]] 1abcdefghijklsmnopqr
3960def arguments_v3_parameter( 1abcdefghijklsmnopqr
3961 name: str,
3962 schema: CoreSchema,
3963 *,
3964 mode: Literal[
3965 'positional_only',
3966 'positional_or_keyword',
3967 'keyword_only',
3968 'var_args',
3969 'var_kwargs_uniform',
3970 'var_kwargs_unpacked_typed_dict',
3971 ]
3972 | None = None,
3973 alias: str | list[str | int] | list[list[str | int]] | None = None,
3974) -> ArgumentsV3Parameter:
3975 """
3976 Returns a schema that matches an argument parameter, e.g.:
3978 ```py
3979 from pydantic_core import SchemaValidator, core_schema
3981 param = core_schema.arguments_v3_parameter(
3982 name='a', schema=core_schema.str_schema(), mode='positional_only'
3983 )
3984 schema = core_schema.arguments_v3_schema([param])
3985 v = SchemaValidator(schema)
3986 assert v.validate_python({'a': 'hello'}) == (('hello',), {})
3987 ```
3989 Args:
3990 name: The name to use for the argument parameter
3991 schema: The schema to use for the argument parameter
3992 mode: The mode to use for the argument parameter
3993 alias: The alias to use for the argument parameter
3994 """
3995 return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias) 1abcdefghijklmnopqr
3998class ArgumentsV3Schema(TypedDict, total=False): 1abcdefghijklsmnopqr
3999 type: Required[Literal['arguments-v3']] 1abcdefghijklsmnopqr
4000 arguments_schema: Required[list[ArgumentsV3Parameter]] 1abcdefghijklsmnopqr
4001 validate_by_name: bool 1abcdefghijklsmnopqr
4002 validate_by_alias: bool 1abcdefghijklsmnopqr
4003 extra_behavior: Literal['forbid', 'ignore'] # 'allow' doesn't make sense here. 1abcdefghijklsmnopqr
4004 ref: str 1abcdefghijklsmnopqr
4005 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4006 serialization: SerSchema 1abcdefghijklsmnopqr
4009def arguments_v3_schema( 1abcdefghijklsmnopqr
4010 arguments: list[ArgumentsV3Parameter],
4011 *,
4012 validate_by_name: bool | None = None,
4013 validate_by_alias: bool | None = None,
4014 extra_behavior: Literal['forbid', 'ignore'] | None = None,
4015 ref: str | None = None,
4016 metadata: dict[str, Any] | None = None,
4017 serialization: SerSchema | None = None,
4018) -> ArgumentsV3Schema:
4019 """
4020 Returns a schema that matches an arguments schema, e.g.:
4022 ```py
4023 from pydantic_core import SchemaValidator, core_schema
4025 param_a = core_schema.arguments_v3_parameter(
4026 name='a', schema=core_schema.str_schema(), mode='positional_only'
4027 )
4028 param_b = core_schema.arguments_v3_parameter(
4029 name='kwargs', schema=core_schema.bool_schema(), mode='var_kwargs_uniform'
4030 )
4031 schema = core_schema.arguments_v3_schema([param_a, param_b])
4032 v = SchemaValidator(schema)
4033 assert v.validate_python({'a': 'hi', 'kwargs': {'b': True}}) == (('hi',), {'b': True})
4034 ```
4036 Pydantic uses this schema as the arguments schema of [`call_schema()`][pydantic_core.core_schema.call_schema].
4038 Args:
4039 arguments: The arguments to use for the arguments schema.
4040 validate_by_name: Whether to populate by the parameter names, defaults to `False`.
4041 validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`.
4042 extra_behavior: The extra behavior to use.
4043 ref: optional unique identifier of the schema, used to reference the schema in other places.
4044 metadata: Any other information you want to include with the schema, not used by pydantic-core.
4045 serialization: Custom serialization schema.
4046 """
4047 return _dict_not_none( 1abcdefghijklmnopqr
4048 type='arguments-v3',
4049 arguments_schema=arguments,
4050 validate_by_name=validate_by_name,
4051 validate_by_alias=validate_by_alias,
4052 extra_behavior=extra_behavior,
4053 ref=ref,
4054 metadata=metadata,
4055 serialization=serialization,
4056 )
4059class CallSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
4060 type: Required[Literal['call']] 1abcdefghijklsmnopqr
4061 arguments_schema: Required[CoreSchema] 1abcdefghijklsmnopqr
4062 function: Required[Callable[..., Any]] 1abcdefghijklsmnopqr
4063 function_name: str # default function.__name__ 1abcdefghijklsmnopqr
4064 return_schema: CoreSchema 1abcdefghijklsmnopqr
4065 ref: str 1abcdefghijklsmnopqr
4066 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4067 serialization: SerSchema 1abcdefghijklsmnopqr
4070def call_schema( 1abcdefghijklsmnopqr
4071 arguments: CoreSchema,
4072 function: Callable[..., Any],
4073 *,
4074 function_name: str | None = None,
4075 return_schema: CoreSchema | None = None,
4076 ref: str | None = None,
4077 metadata: dict[str, Any] | None = None,
4078 serialization: SerSchema | None = None,
4079) -> CallSchema:
4080 """
4081 Returns a schema that matches an arguments schema, then calls a function, e.g.:
4083 ```py
4084 from pydantic_core import SchemaValidator, core_schema
4086 param_a = core_schema.arguments_v3_parameter(
4087 name='a', schema=core_schema.str_schema(), mode='positional_only'
4088 )
4089 param_b = core_schema.arguments_v3_parameter(
4090 name='b', schema=core_schema.bool_schema(), mode='positional_only'
4091 )
4092 args_schema = core_schema.arguments_v3_schema([param_a, param_b])
4094 schema = core_schema.call_schema(
4095 arguments=args_schema,
4096 function=lambda a, b: a + str(not b),
4097 return_schema=core_schema.str_schema(),
4098 )
4099 v = SchemaValidator(schema)
4100 assert v.validate_python({'a': 'hello', 'b': True}) == 'helloFalse'
4101 ```
4103 Args:
4104 arguments: The arguments to use for the arguments schema
4105 function: The function to use for the call schema
4106 function_name: The function name to use for the call schema, if not provided `function.__name__` is used
4107 return_schema: The return schema to use for the call schema
4108 ref: optional unique identifier of the schema, used to reference the schema in other places
4109 metadata: Any other information you want to include with the schema, not used by pydantic-core
4110 serialization: Custom serialization schema
4111 """
4112 return _dict_not_none( 1abcdefghijklmnopqr
4113 type='call',
4114 arguments_schema=arguments,
4115 function=function,
4116 function_name=function_name,
4117 return_schema=return_schema,
4118 ref=ref,
4119 metadata=metadata,
4120 serialization=serialization,
4121 )
4124class CustomErrorSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
4125 type: Required[Literal['custom-error']] 1abcdefghijklsmnopqr
4126 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
4127 custom_error_type: Required[str] 1abcdefghijklsmnopqr
4128 custom_error_message: str 1abcdefghijklsmnopqr
4129 custom_error_context: dict[str, str | int | float] 1abcdefghijklsmnopqr
4130 ref: str 1abcdefghijklsmnopqr
4131 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4132 serialization: SerSchema 1abcdefghijklsmnopqr
4135def custom_error_schema( 1abcdefghijklsmnopqr
4136 schema: CoreSchema,
4137 custom_error_type: str,
4138 *,
4139 custom_error_message: str | None = None,
4140 custom_error_context: dict[str, Any] | None = None,
4141 ref: str | None = None,
4142 metadata: dict[str, Any] | None = None,
4143 serialization: SerSchema | None = None,
4144) -> CustomErrorSchema:
4145 """
4146 Returns a schema that matches a custom error value, e.g.:
4148 ```py
4149 from pydantic_core import SchemaValidator, core_schema
4151 schema = core_schema.custom_error_schema(
4152 schema=core_schema.int_schema(),
4153 custom_error_type='MyError',
4154 custom_error_message='Error msg',
4155 )
4156 v = SchemaValidator(schema)
4157 v.validate_python(1)
4158 ```
4160 Args:
4161 schema: The schema to use for the custom error schema
4162 custom_error_type: The custom error type to use for the custom error schema
4163 custom_error_message: The custom error message to use for the custom error schema
4164 custom_error_context: The custom error context to use for the custom error schema
4165 ref: optional unique identifier of the schema, used to reference the schema in other places
4166 metadata: Any other information you want to include with the schema, not used by pydantic-core
4167 serialization: Custom serialization schema
4168 """
4169 return _dict_not_none( 1abcdefghijklmnopqr
4170 type='custom-error',
4171 schema=schema,
4172 custom_error_type=custom_error_type,
4173 custom_error_message=custom_error_message,
4174 custom_error_context=custom_error_context,
4175 ref=ref,
4176 metadata=metadata,
4177 serialization=serialization,
4178 )
4181class JsonSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
4182 type: Required[Literal['json']] 1abcdefghijklsmnopqr
4183 schema: CoreSchema 1abcdefghijklsmnopqr
4184 ref: str 1abcdefghijklsmnopqr
4185 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4186 serialization: SerSchema 1abcdefghijklsmnopqr
4189def json_schema( 1abcdefghijklsmnopqr
4190 schema: CoreSchema | None = None,
4191 *,
4192 ref: str | None = None,
4193 metadata: dict[str, Any] | None = None,
4194 serialization: SerSchema | None = None,
4195) -> JsonSchema:
4196 """
4197 Returns a schema that matches a JSON value, e.g.:
4199 ```py
4200 from pydantic_core import SchemaValidator, core_schema
4202 dict_schema = core_schema.model_fields_schema(
4203 {
4204 'field_a': core_schema.model_field(core_schema.str_schema()),
4205 'field_b': core_schema.model_field(core_schema.bool_schema()),
4206 },
4207 )
4209 class MyModel:
4210 __slots__ = (
4211 '__dict__',
4212 '__pydantic_extra__',
4213 '__pydantic_fields_set__',
4214 '__pydantic_private__',
4215 )
4216 field_a: str
4217 field_b: bool
4219 json_schema = core_schema.json_schema(schema=dict_schema)
4220 schema = core_schema.model_schema(cls=MyModel, schema=json_schema)
4221 v = SchemaValidator(schema)
4222 m = v.validate_python('{"field_a": "hello", "field_b": true}')
4223 assert isinstance(m, MyModel)
4224 ```
4226 Args:
4227 schema: The schema to use for the JSON schema
4228 ref: optional unique identifier of the schema, used to reference the schema in other places
4229 metadata: Any other information you want to include with the schema, not used by pydantic-core
4230 serialization: Custom serialization schema
4231 """
4232 return _dict_not_none(type='json', schema=schema, ref=ref, metadata=metadata, serialization=serialization) 1abcdefghijklmnopqr
4235class UrlSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
4236 type: Required[Literal['url']] 1abcdefghijklsmnopqr
4237 max_length: int 1abcdefghijklsmnopqr
4238 allowed_schemes: list[str] 1abcdefghijklsmnopqr
4239 host_required: bool # default False 1abcdefghijklsmnopqr
4240 default_host: str 1abcdefghijklsmnopqr
4241 default_port: int 1abcdefghijklsmnopqr
4242 default_path: str 1abcdefghijklsmnopqr
4243 strict: bool 1abcdefghijklsmnopqr
4244 ref: str 1abcdefghijklsmnopqr
4245 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4246 serialization: SerSchema 1abcdefghijklsmnopqr
4249def url_schema( 1abcdefghijklsmnopqr
4250 *,
4251 max_length: int | None = None,
4252 allowed_schemes: list[str] | None = None,
4253 host_required: bool | None = None,
4254 default_host: str | None = None,
4255 default_port: int | None = None,
4256 default_path: str | None = None,
4257 preserve_empty_path: bool | None = None,
4258 strict: bool | None = None,
4259 ref: str | None = None,
4260 metadata: dict[str, Any] | None = None,
4261 serialization: SerSchema | None = None,
4262) -> UrlSchema:
4263 """
4264 Returns a schema that matches a URL value, e.g.:
4266 ```py
4267 from pydantic_core import SchemaValidator, core_schema
4269 schema = core_schema.url_schema()
4270 v = SchemaValidator(schema)
4271 print(v.validate_python('https://example.com'))
4272 #> https://example.com/
4273 ```
4275 Args:
4276 max_length: The maximum length of the URL
4277 allowed_schemes: The allowed URL schemes
4278 host_required: Whether the URL must have a host
4279 default_host: The default host to use if the URL does not have a host
4280 default_port: The default port to use if the URL does not have a port
4281 default_path: The default path to use if the URL does not have a path
4282 preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False
4283 strict: Whether to use strict URL parsing
4284 ref: optional unique identifier of the schema, used to reference the schema in other places
4285 metadata: Any other information you want to include with the schema, not used by pydantic-core
4286 serialization: Custom serialization schema
4287 """
4288 return _dict_not_none( 1abcdefghijklsmnopqr
4289 type='url',
4290 max_length=max_length,
4291 allowed_schemes=allowed_schemes,
4292 host_required=host_required,
4293 default_host=default_host,
4294 default_port=default_port,
4295 default_path=default_path,
4296 preserve_empty_path=preserve_empty_path,
4297 strict=strict,
4298 ref=ref,
4299 metadata=metadata,
4300 serialization=serialization,
4301 )
4304class MultiHostUrlSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
4305 type: Required[Literal['multi-host-url']] 1abcdefghijklsmnopqr
4306 max_length: int 1abcdefghijklsmnopqr
4307 allowed_schemes: list[str] 1abcdefghijklsmnopqr
4308 host_required: bool # default False 1abcdefghijklsmnopqr
4309 default_host: str 1abcdefghijklsmnopqr
4310 default_port: int 1abcdefghijklsmnopqr
4311 default_path: str 1abcdefghijklsmnopqr
4312 strict: bool 1abcdefghijklsmnopqr
4313 ref: str 1abcdefghijklsmnopqr
4314 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4315 serialization: SerSchema 1abcdefghijklsmnopqr
4318def multi_host_url_schema( 1abcdefghijklsmnopqr
4319 *,
4320 max_length: int | None = None,
4321 allowed_schemes: list[str] | None = None,
4322 host_required: bool | None = None,
4323 default_host: str | None = None,
4324 default_port: int | None = None,
4325 default_path: str | None = None,
4326 preserve_empty_path: bool | None = None,
4327 strict: bool | None = None,
4328 ref: str | None = None,
4329 metadata: dict[str, Any] | None = None,
4330 serialization: SerSchema | None = None,
4331) -> MultiHostUrlSchema:
4332 """
4333 Returns a schema that matches a URL value with possibly multiple hosts, e.g.:
4335 ```py
4336 from pydantic_core import SchemaValidator, core_schema
4338 schema = core_schema.multi_host_url_schema()
4339 v = SchemaValidator(schema)
4340 print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1'))
4341 #> redis://localhost,0.0.0.0,127.0.0.1
4342 ```
4344 Args:
4345 max_length: The maximum length of the URL
4346 allowed_schemes: The allowed URL schemes
4347 host_required: Whether the URL must have a host
4348 default_host: The default host to use if the URL does not have a host
4349 default_port: The default port to use if the URL does not have a port
4350 default_path: The default path to use if the URL does not have a path
4351 preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False
4352 strict: Whether to use strict URL parsing
4353 ref: optional unique identifier of the schema, used to reference the schema in other places
4354 metadata: Any other information you want to include with the schema, not used by pydantic-core
4355 serialization: Custom serialization schema
4356 """
4357 return _dict_not_none( 1abcdefghijklsmnopqr
4358 type='multi-host-url',
4359 max_length=max_length,
4360 allowed_schemes=allowed_schemes,
4361 host_required=host_required,
4362 default_host=default_host,
4363 default_port=default_port,
4364 default_path=default_path,
4365 preserve_empty_path=preserve_empty_path,
4366 strict=strict,
4367 ref=ref,
4368 metadata=metadata,
4369 serialization=serialization,
4370 )
4373class DefinitionsSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
4374 type: Required[Literal['definitions']] 1abcdefghijklsmnopqr
4375 schema: Required[CoreSchema] 1abcdefghijklsmnopqr
4376 definitions: Required[list[CoreSchema]] 1abcdefghijklsmnopqr
4377 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4378 serialization: SerSchema 1abcdefghijklsmnopqr
4381def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema: 1abcdefghijklsmnopqr
4382 """
4383 Build a schema that contains both an inner schema and a list of definitions which can be used
4384 within the inner schema.
4386 ```py
4387 from pydantic_core import SchemaValidator, core_schema
4389 schema = core_schema.definitions_schema(
4390 core_schema.list_schema(core_schema.definition_reference_schema('foobar')),
4391 [core_schema.int_schema(ref='foobar')],
4392 )
4393 v = SchemaValidator(schema)
4394 assert v.validate_python([1, 2, '3']) == [1, 2, 3]
4395 ```
4397 Args:
4398 schema: The inner schema
4399 definitions: List of definitions which can be referenced within inner schema
4400 """
4401 return DefinitionsSchema(type='definitions', schema=schema, definitions=definitions) 1abcdefghijklsmnopqr
4404class DefinitionReferenceSchema(TypedDict, total=False): 1abcdefghijklsmnopqr
4405 type: Required[Literal['definition-ref']] 1abcdefghijklsmnopqr
4406 schema_ref: Required[str] 1abcdefghijklsmnopqr
4407 ref: str 1abcdefghijklsmnopqr
4408 metadata: dict[str, Any] 1abcdefghijklsmnopqr
4409 serialization: SerSchema 1abcdefghijklsmnopqr
4412def definition_reference_schema( 1abcdefghijklsmnopqr
4413 schema_ref: str,
4414 ref: str | None = None,
4415 metadata: dict[str, Any] | None = None,
4416 serialization: SerSchema | None = None,
4417) -> DefinitionReferenceSchema:
4418 """
4419 Returns a schema that points to a schema stored in "definitions", this is useful for nested recursive
4420 models and also when you want to define validators separately from the main schema, e.g.:
4422 ```py
4423 from pydantic_core import SchemaValidator, core_schema
4425 schema_definition = core_schema.definition_reference_schema('list-schema')
4426 schema = core_schema.definitions_schema(
4427 schema=schema_definition,
4428 definitions=[
4429 core_schema.list_schema(items_schema=schema_definition, ref='list-schema'),
4430 ],
4431 )
4432 v = SchemaValidator(schema)
4433 assert v.validate_python([()]) == [[]]
4434 ```
4436 Args:
4437 schema_ref: The schema ref to use for the definition reference schema
4438 metadata: Any other information you want to include with the schema, not used by pydantic-core
4439 serialization: Custom serialization schema
4440 """
4441 return _dict_not_none( 1abcdefghijklsmnopqr
4442 type='definition-ref', schema_ref=schema_ref, ref=ref, metadata=metadata, serialization=serialization
4443 )
4446MYPY = False 1abcdefghijklsmnopqr
4447# See https://github.com/python/mypy/issues/14034 for details, in summary mypy is extremely slow to process this
4448# union which kills performance not just for pydantic, but even for code using pydantic
4449if not MYPY: 4449 ↛ 4511line 4449 didn't jump to line 4511 because the condition on line 4449 was always true1abcdefghijklsmnopqr
4450 CoreSchema: TypeAlias = ( 1abcdefghijklsmnopqr
4451 InvalidSchema
4452 | AnySchema
4453 | NoneSchema
4454 | BoolSchema
4455 | IntSchema
4456 | FloatSchema
4457 | DecimalSchema
4458 | FractionSchema
4459 | StringSchema
4460 | BytesSchema
4461 | DateSchema
4462 | TimeSchema
4463 | DatetimeSchema
4464 | TimedeltaSchema
4465 | LiteralSchema
4466 | MissingSentinelSchema
4467 | EllipsisSchema
4468 | EnumSchema
4469 | IsInstanceSchema
4470 | IsSubclassSchema
4471 | CallableSchema
4472 | ListSchema
4473 | DequeSchema
4474 | TupleSchema
4475 | SetSchema
4476 | FrozenSetSchema
4477 | GeneratorSchema
4478 | DictSchema
4479 | FrozenDictSchema
4480 | OrderedDictSchema
4481 | CounterSchema
4482 | AfterValidatorFunctionSchema
4483 | BeforeValidatorFunctionSchema
4484 | WrapValidatorFunctionSchema
4485 | PlainValidatorFunctionSchema
4486 | WithDefaultSchema
4487 | NullableSchema
4488 | UnionSchema
4489 | TaggedUnionSchema
4490 | ChainSchema
4491 | LaxOrStrictSchema
4492 | JsonOrPythonSchema
4493 | TypedDictSchema
4494 | ModelFieldsSchema
4495 | ModelSchema
4496 | DataclassArgsSchema
4497 | DataclassSchema
4498 | NamedTupleSchema
4499 | ArgumentsSchema
4500 | ArgumentsV3Schema
4501 | CallSchema
4502 | CustomErrorSchema
4503 | JsonSchema
4504 | UrlSchema
4505 | MultiHostUrlSchema
4506 | DefinitionsSchema
4507 | DefinitionReferenceSchema
4508 | UuidSchema
4509 | ComplexSchema
4510 )
4511elif False:
4512 CoreSchema: TypeAlias = Mapping[str, Any]
4515# to update this, call `pytest -k test_core_schema_type_literal` and copy the output
4516CoreSchemaType: TypeAlias = Literal[ 1abcdefghijklsmnopqr
4517 'invalid',
4518 'any',
4519 'none',
4520 'bool',
4521 'int',
4522 'float',
4523 'decimal',
4524 'fraction',
4525 'str',
4526 'bytes',
4527 'date',
4528 'time',
4529 'datetime',
4530 'timedelta',
4531 'literal',
4532 'missing-sentinel',
4533 'ellipsis',
4534 'enum',
4535 'is-instance',
4536 'is-subclass',
4537 'callable',
4538 'list',
4539 'deque',
4540 'tuple',
4541 'set',
4542 'frozenset',
4543 'generator',
4544 'dict',
4545 'frozendict',
4546 'ordered-dict',
4547 'counter',
4548 'function-after',
4549 'function-before',
4550 'function-wrap',
4551 'function-plain',
4552 'default',
4553 'nullable',
4554 'union',
4555 'tagged-union',
4556 'chain',
4557 'lax-or-strict',
4558 'json-or-python',
4559 'typed-dict',
4560 'model-fields',
4561 'model',
4562 'dataclass-args',
4563 'dataclass',
4564 'named-tuple',
4565 'arguments',
4566 'arguments-v3',
4567 'call',
4568 'custom-error',
4569 'json',
4570 'url',
4571 'multi-host-url',
4572 'definitions',
4573 'definition-ref',
4574 'uuid',
4575 'complex',
4576]
4578CoreSchemaFieldType: TypeAlias = Literal[ 1abcdefghijklsmnopqr
4579 'model-field', 'dataclass-field', 'typed-dict-field', 'named-tuple-field', 'computed-field'
4580]
4583# used in _pydantic_core/__init__.pyi::PydanticKnownError
4584# to update this, call `pytest -k test_all_errors` and copy the output
4585ErrorType: TypeAlias = Literal[ 1abcdefghijklsmnopqr
4586 'no_such_attribute',
4587 'json_invalid',
4588 'json_type',
4589 'needs_python_object',
4590 'recursion_loop',
4591 'recursion_depth_exceeded',
4592 'missing',
4593 'frozen_field',
4594 'frozen_instance',
4595 'extra_forbidden',
4596 'invalid_key',
4597 'get_attribute_error',
4598 'model_type',
4599 'model_attributes_type',
4600 'dataclass_type',
4601 'dataclass_exact_type',
4602 'named_tuple_type',
4603 'default_factory_not_called',
4604 'none_required',
4605 'greater_than',
4606 'greater_than_equal',
4607 'less_than',
4608 'less_than_equal',
4609 'multiple_of',
4610 'finite_number',
4611 'too_short',
4612 'too_long',
4613 'iterable_type',
4614 'iteration_error',
4615 'string_type',
4616 'string_unicode',
4617 'string_too_short',
4618 'string_too_long',
4619 'string_pattern_mismatch',
4620 'string_not_ascii',
4621 'enum',
4622 'dict_type',
4623 'frozen_dict_type',
4624 'ordered_dict_type',
4625 'counter_type',
4626 'mapping_type',
4627 'list_type',
4628 'deque_type',
4629 'tuple_type',
4630 'set_type',
4631 'set_item_not_hashable',
4632 'bool_type',
4633 'bool_parsing',
4634 'int_type',
4635 'int_parsing',
4636 'int_parsing_size',
4637 'int_from_float',
4638 'float_type',
4639 'float_parsing',
4640 'bytes_type',
4641 'bytes_too_short',
4642 'bytes_too_long',
4643 'bytes_invalid_encoding',
4644 'value_error',
4645 'assertion_error',
4646 'literal_error',
4647 'missing_sentinel_error',
4648 'ellipsis_error',
4649 'date_type',
4650 'date_parsing',
4651 'date_from_datetime_parsing',
4652 'date_from_datetime_inexact',
4653 'date_past',
4654 'date_future',
4655 'time_type',
4656 'time_parsing',
4657 'datetime_type',
4658 'datetime_parsing',
4659 'datetime_object_invalid',
4660 'datetime_from_date_parsing',
4661 'datetime_past',
4662 'datetime_future',
4663 'timezone_naive',
4664 'timezone_aware',
4665 'timezone_offset',
4666 'time_delta_type',
4667 'time_delta_parsing',
4668 'frozen_set_type',
4669 'is_instance_of',
4670 'is_subclass_of',
4671 'callable_type',
4672 'union_tag_invalid',
4673 'union_tag_not_found',
4674 'arguments_type',
4675 'missing_argument',
4676 'unexpected_keyword_argument',
4677 'missing_keyword_only_argument',
4678 'unexpected_positional_argument',
4679 'missing_positional_only_argument',
4680 'multiple_argument_values',
4681 'url_type',
4682 'url_parsing',
4683 'url_syntax_violation',
4684 'url_too_long',
4685 'url_scheme',
4686 'uuid_type',
4687 'uuid_parsing',
4688 'uuid_version',
4689 'decimal_type',
4690 'decimal_parsing',
4691 'decimal_max_digits',
4692 'decimal_max_places',
4693 'decimal_whole_digits',
4694 'fraction_type',
4695 'fraction_parsing',
4696 'complex_type',
4697 'complex_str_parsing',
4698]
4701def _dict_not_none(**kwargs: Any) -> Any: 1abcdefghijklsmnopqr
4702 return {k: v for k, v in kwargs.items() if v is not None} 1abcdefghijklsmnopqr
4705def iter_union_choices(union_schema: UnionSchema) -> Generator[CoreSchema]: 1abcdefghijklsmnopqr
4706 """Iterate over the choices of a `'union'` schema."""
4707 for choice in union_schema['choices']: 1abcdefghijklmnopqr
4708 if isinstance(choice, tuple): 4708 ↛ 4709line 4708 didn't jump to line 4709 because the condition on line 4708 was never true1abcdefghijklmnopqr
4709 yield choice[0]
4710 else:
4711 yield choice 1abcdefghijklmnopqr