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