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