Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pydantic_core/core_schema.py: 88%
731 statements
« prev ^ index » next coverage.py v7.2.3, created at 2023-04-27 07:38 +0000
« prev ^ index » next coverage.py v7.2.3, created at 2023-04-27 07:38 +0000
1from __future__ import annotations as _annotations
3import sys
4from collections.abc import Mapping
5from datetime import date, datetime, time, timedelta
6from typing import Any, Callable, Dict, List, Optional, Set, Type, Union
8if sys.version_info < (3, 11):
9 from typing_extensions import Protocol, Required, TypeAlias
10else:
11 from typing import Protocol, Required, TypeAlias
13if sys.version_info < (3, 9):
14 from typing_extensions import Literal, TypedDict
15else:
16 from typing import Literal, TypedDict
19def dict_not_none(**kwargs: Any) -> Any:
20 return {k: v for k, v in kwargs.items() if v is not None}
23ExtraBehavior = Literal['allow', 'forbid', 'ignore']
26class CoreConfig(TypedDict, total=False):
27 title: str
28 strict: bool
29 # higher priority configs take precedence of over lower, if priority matches the two configs are merged, default 0
30 config_choose_priority: int
31 # if configs are merged, which should take precedence, default 0, default means child takes precedence
32 config_merge_priority: int
33 # settings related to typed_dicts only
34 extra_fields_behavior: ExtraBehavior
35 typed_dict_total: bool # default: True
36 # used on typed-dicts and tagged union keys
37 from_attributes: bool
38 # whether to use the used alias (or first alias for "field required" errors) instead of field_names
39 # to construct error `loc`s, default True
40 loc_by_alias: bool
41 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
42 revalidate_instances: Literal['always', 'never', 'subclass-instances']
43 # whether to validate default values during validation, default False
44 validate_default: bool
45 # used on typed-dicts and arguments
46 populate_by_name: bool # replaces `allow_population_by_field_name` in pydantic v1
47 # fields related to string fields only
48 str_max_length: int
49 str_min_length: int
50 str_strip_whitespace: bool
51 str_to_lower: bool
52 str_to_upper: bool
53 # fields related to float fields only
54 allow_inf_nan: bool # default: True
55 # the config options are used to customise serialization to JSON
56 ser_json_timedelta: Literal['iso8601', 'float'] # default: 'iso8601'
57 ser_json_bytes: Literal['utf8', 'base64'] # default: 'utf8'
60IncExCall: TypeAlias = 'set[int | str] | dict[int | str, IncExCall] | None'
63class SerializationInfo(Protocol):
64 @property
65 def include(self) -> IncExCall:
66 ...
68 @property
69 def exclude(self) -> IncExCall:
70 ...
72 @property
73 def mode(self) -> str:
74 ...
76 @property
77 def by_alias(self) -> bool:
78 ...
80 @property
81 def exclude_unset(self) -> bool:
82 ...
84 @property
85 def exclude_defaults(self) -> bool:
86 ...
88 @property
89 def exclude_none(self) -> bool:
90 ...
92 @property
93 def round_trip(self) -> bool:
94 ...
96 def mode_is_json(self) -> bool:
97 ...
99 def __str__(self) -> str:
100 ...
102 def __repr__(self) -> str:
103 ...
106class FieldSerializationInfo(SerializationInfo, Protocol):
107 @property
108 def field_name(self) -> str:
109 ...
112class ValidationInfo(Protocol):
113 """
114 Argument passed to validation functions.
115 """
117 @property
118 def context(self) -> Dict[str, Any]:
119 """Current validation context."""
120 ...
122 @property
123 def config(self) -> CoreConfig | None:
124 """The CoreConfig that applies to this validation."""
125 ...
128class FieldValidationInfo(ValidationInfo, Protocol):
129 """
130 Argument passed to model field validation functions.
131 """
133 @property
134 def data(self) -> Dict[str, Any]:
135 """All of the fields and data being validated for this model."""
136 ...
138 @property
139 def field_name(self) -> str:
140 """
141 The name of the current field being validated if this validator is
142 attached to a model field.
143 """
144 ...
147ExpectedSerializationTypes = Literal[
148 'none',
149 'int',
150 'bool',
151 'float',
152 'str',
153 'bytes',
154 'bytearray',
155 'list',
156 'tuple',
157 'set',
158 'frozenset',
159 'generator',
160 'dict',
161 'datetime',
162 'date',
163 'time',
164 'timedelta',
165 'url',
166 'multi-host-url',
167 'json',
168]
171class SimpleSerSchema(TypedDict, total=False):
172 type: Required[ExpectedSerializationTypes]
175def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema:
176 """
177 Returns a schema for serialization with a custom type.
179 Args:
180 type: The type to use for serialization
181 """
182 return SimpleSerSchema(type=type)
185# (__input_value: Any) -> Any
186GeneralPlainNoInfoSerializerFunction = Callable[[Any], Any]
187# (__input_value: Any, __info: FieldSerializationInfo) -> Any
188GeneralPlainInfoSerializerFunction = Callable[[Any, SerializationInfo], Any]
189# (__model: Any, __input_value: Any) -> Any
190FieldPlainNoInfoSerializerFunction = Callable[[Any, Any], Any]
191# (__model: Any, __input_value: Any, __info: FieldSerializationInfo) -> Any
192FieldPlainInfoSerializerFunction = Callable[[Any, Any, FieldSerializationInfo], Any]
193SerializerFunction = Union[
194 GeneralPlainNoInfoSerializerFunction,
195 GeneralPlainInfoSerializerFunction,
196 FieldPlainNoInfoSerializerFunction,
197 FieldPlainInfoSerializerFunction,
198]
201# must match `src/serializers/ob_type.rs::ObType`
202JsonReturnTypes = Literal[
203 'none',
204 'int',
205 'int_subclass',
206 'bool',
207 'float',
208 'float_subclass',
209 'decimal',
210 'str',
211 'str_subclass',
212 'bytes',
213 'bytearray',
214 'list',
215 'tuple',
216 'set',
217 'frozenset',
218 'generator',
219 'dict',
220 'datetime',
221 'date',
222 'time',
223 'timedelta',
224 'url',
225 'multi_host_url',
226 'dataclass',
227 'model',
228 'enum',
229 'path',
230]
232WhenUsed = Literal['always', 'unless-none', 'json', 'json-unless-none']
233"""
234Values have the following meanings:
235* `'always'` means always use
236* `'unless-none'` means use unless the value is `None`
237* `'json'` means use when serializing to JSON
238* `'json-unless-none'` means use when serializing to JSON and the value is not `None`
239"""
242class PlainSerializerFunctionSerSchema(TypedDict, total=False):
243 type: Required[Literal['function-plain']]
244 function: Required[SerializerFunction]
245 is_field_serializer: bool # default False
246 info_arg: bool # default False
247 json_return_type: JsonReturnTypes
248 when_used: WhenUsed # default: 'always'
251def plain_serializer_function_ser_schema(
252 function: SerializerFunction,
253 *,
254 is_field_serializer: bool | None = None,
255 info_arg: bool | None = None,
256 json_return_type: JsonReturnTypes | None = None,
257 when_used: WhenUsed = 'always',
258) -> PlainSerializerFunctionSerSchema:
259 """
260 Returns a schema for serialization with a function, can be either a "general" or "field" function.
262 Args:
263 function: The function to use for serialization
264 is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
265 and `info` includes `field_name`
266 info_arg: Whether the function takes an `__info` argument
267 json_return_type: The type that the function returns if `mode='json'`
268 when_used: When the function should be called
269 """
270 if when_used == 'always':
271 # just to avoid extra elements in schema, and to use the actual default defined in rust
272 when_used = None # type: ignore
273 return dict_not_none(
274 type='function-plain',
275 function=function,
276 is_field_serializer=is_field_serializer,
277 info_arg=info_arg,
278 json_return_type=json_return_type,
279 when_used=when_used,
280 )
283class SerializerFunctionWrapHandler(Protocol): # pragma: no cover
284 def __call__(self, __input_value: Any, __index_key: int | str | None = None) -> Any:
285 ...
288# (__input_value: Any, __serializer: SerializerFunctionWrapHandler) -> Any
289GeneralWrapNoInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler], Any]
290# (__input_value: Any, __serializer: SerializerFunctionWrapHandler, __info: SerializationInfo) -> Any
291GeneralWrapInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo], Any]
292# (__model: Any, __input_value: Any, __serializer: SerializerFunctionWrapHandler) -> Any
293FieldWrapNoInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler], Any]
294# (__model: Any, __input_value: Any, __serializer: SerializerFunctionWrapHandler, __info: FieldSerializationInfo) -> Any
295FieldWrapInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo], Any]
296WrapSerializerFunction = Union[
297 GeneralWrapNoInfoSerializerFunction,
298 GeneralWrapInfoSerializerFunction,
299 FieldWrapNoInfoSerializerFunction,
300 FieldWrapInfoSerializerFunction,
301]
304class WrapSerializerFunctionSerSchema(TypedDict, total=False):
305 type: Required[Literal['function-wrap']]
306 function: Required[WrapSerializerFunction]
307 is_field_serializer: bool # default False
308 info_arg: bool # default False
309 schema: CoreSchema # if omitted, the schema on which this serializer is defined is used
310 json_return_type: JsonReturnTypes
311 when_used: WhenUsed # default: 'always'
314def wrap_serializer_function_ser_schema(
315 function: WrapSerializerFunction,
316 *,
317 is_field_serializer: bool | None = None,
318 info_arg: bool | None = None,
319 schema: CoreSchema | None = None,
320 json_return_type: JsonReturnTypes | None = None,
321 when_used: WhenUsed = 'always',
322) -> WrapSerializerFunctionSerSchema:
323 """
324 Returns a schema for serialization with a wrap function, can be either a "general" or "field" function.
326 Args:
327 function: The function to use for serialization
328 is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
329 and `info` includes `field_name`
330 info_arg: Whether the function takes an `__info` argument
331 schema: The schema to use for the inner serialization
332 json_return_type: The type that the function returns if `mode='json'`
333 when_used: When the function should be called
334 """
335 if when_used == 'always':
336 # just to avoid extra elements in schema, and to use the actual default defined in rust
337 when_used = None # type: ignore
338 return dict_not_none(
339 type='function-wrap',
340 function=function,
341 is_field_serializer=is_field_serializer,
342 info_arg=info_arg,
343 schema=schema,
344 json_return_type=json_return_type,
345 when_used=when_used,
346 )
349class FormatSerSchema(TypedDict, total=False):
350 type: Required[Literal['format']]
351 formatting_string: Required[str]
352 when_used: WhenUsed # default: 'json-unless-none'
355def format_ser_schema(formatting_string: str, *, when_used: WhenUsed = 'json-unless-none') -> FormatSerSchema:
356 """
357 Returns a schema for serialization using python's `format` method.
359 Args:
360 formatting_string: String defining the format to use
361 when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
362 """
363 if when_used == 'json-unless-none':
364 # just to avoid extra elements in schema, and to use the actual default defined in rust
365 when_used = None # type: ignore
366 return dict_not_none(type='format', formatting_string=formatting_string, when_used=when_used)
369class ToStringSerSchema(TypedDict, total=False):
370 type: Required[Literal['to-string']]
371 when_used: WhenUsed # default: 'json-unless-none'
374def to_string_ser_schema(*, when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema:
375 """
376 Returns a schema for serialization using python's `str()` / `__str__` method.
378 Args:
379 when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
380 """
381 s = dict(type='to-string')
382 if when_used != 'json-unless-none':
383 # just to avoid extra elements in schema, and to use the actual default defined in rust
384 s['when_used'] = when_used
385 return s # type: ignore
388class ModelSerSchema(TypedDict, total=False):
389 type: Required[Literal['model']]
390 cls: Required[Type[Any]]
391 schema: Required[CoreSchema]
394def model_ser_schema(cls: Type[Any], schema: CoreSchema) -> ModelSerSchema:
395 """
396 Returns a schema for serialization using a model.
398 Args:
399 cls: The expected class type, used to generate warnings if the wrong type is passed
400 schema: Internal schema to use to serialize the model dict
401 """
402 return ModelSerSchema(type='model', cls=cls, schema=schema)
405SerSchema = Union[
406 SimpleSerSchema,
407 PlainSerializerFunctionSerSchema,
408 WrapSerializerFunctionSerSchema,
409 FormatSerSchema,
410 ToStringSerSchema,
411 ModelSerSchema,
412]
415class ComputedField(TypedDict, total=False):
416 type: Required[Literal['computed-field']]
417 property_name: Required[str]
418 json_return_type: JsonReturnTypes
419 alias: str
422def computed_field(
423 property_name: str, *, json_return_type: JsonReturnTypes | None = None, alias: str | None = None
424) -> ComputedField:
425 """
426 ComputedFields are properties of a model or dataclass that are included in serialization.
428 Args:
429 property_name: The name of the property on the model or dataclass
430 json_return_type: The type that the property returns if `mode='json'`
431 alias: The name to use in the serialized output
432 """
433 return dict_not_none(
434 type='computed-field', property_name=property_name, json_return_type=json_return_type, alias=alias
435 )
438class AnySchema(TypedDict, total=False):
439 type: Required[Literal['any']]
440 ref: str
441 metadata: Any
442 serialization: SerSchema
445def any_schema(*, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None) -> AnySchema:
446 """
447 Returns a schema that matches any value, e.g.:
449 ```py
450 from pydantic_core import SchemaValidator, core_schema
452 schema = core_schema.any_schema()
453 v = SchemaValidator(schema)
454 assert v.validate_python(1) == 1
455 ```
457 Args:
458 ref: optional unique identifier of the schema, used to reference the schema in other places
459 metadata: Any other information you want to include with the schema, not used by pydantic-core
460 serialization: Custom serialization schema
461 """
462 return dict_not_none(type='any', ref=ref, metadata=metadata, serialization=serialization)
465class NoneSchema(TypedDict, total=False):
466 type: Required[Literal['none']]
467 ref: str
468 metadata: Any
469 serialization: SerSchema
472def none_schema(*, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None) -> NoneSchema:
473 """
474 Returns a schema that matches a None value, e.g.:
476 ```py
477 from pydantic_core import SchemaValidator, core_schema
479 schema = core_schema.none_schema()
480 v = SchemaValidator(schema)
481 assert v.validate_python(None) is None
482 ```
484 Args:
485 ref: optional unique identifier of the schema, used to reference the schema in other places
486 metadata: Any other information you want to include with the schema, not used by pydantic-core
487 serialization: Custom serialization schema
488 """
489 return dict_not_none(type='none', ref=ref, metadata=metadata, serialization=serialization)
492class BoolSchema(TypedDict, total=False):
493 type: Required[Literal['bool']]
494 strict: bool
495 ref: str
496 metadata: Any
497 serialization: SerSchema
500def bool_schema(
501 strict: bool | None = None, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None
502) -> BoolSchema:
503 """
504 Returns a schema that matches a bool value, e.g.:
506 ```py
507 from pydantic_core import SchemaValidator, core_schema
509 schema = core_schema.bool_schema()
510 v = SchemaValidator(schema)
511 assert v.validate_python('True') is True
512 ```
514 Args:
515 strict: Whether the value should be a bool or a value that can be converted to a bool
516 ref: optional unique identifier of the schema, used to reference the schema in other places
517 metadata: Any other information you want to include with the schema, not used by pydantic-core
518 serialization: Custom serialization schema
519 """
520 return dict_not_none(type='bool', strict=strict, ref=ref, metadata=metadata, serialization=serialization)
523class IntSchema(TypedDict, total=False):
524 type: Required[Literal['int']]
525 multiple_of: int
526 le: int
527 ge: int
528 lt: int
529 gt: int
530 strict: bool
531 ref: str
532 metadata: Any
533 serialization: SerSchema
536def int_schema(
537 *,
538 multiple_of: int | None = None,
539 le: int | None = None,
540 ge: int | None = None,
541 lt: int | None = None,
542 gt: int | None = None,
543 strict: bool | None = None,
544 ref: str | None = None,
545 metadata: Any = None,
546 serialization: SerSchema | None = None,
547) -> IntSchema:
548 """
549 Returns a schema that matches a int value, e.g.:
551 ```py
552 from pydantic_core import SchemaValidator, core_schema
554 schema = core_schema.int_schema(multiple_of=2, le=6, ge=2)
555 v = SchemaValidator(schema)
556 assert v.validate_python('4') == 4
557 ```
559 Args:
560 multiple_of: The value must be a multiple of this number
561 le: The value must be less than or equal to this number
562 ge: The value must be greater than or equal to this number
563 lt: The value must be strictly less than this number
564 gt: The value must be strictly greater than this number
565 strict: Whether the value should be a int or a value that can be converted to a int
566 ref: optional unique identifier of the schema, used to reference the schema in other places
567 metadata: Any other information you want to include with the schema, not used by pydantic-core
568 serialization: Custom serialization schema
569 """
570 return dict_not_none(
571 type='int',
572 multiple_of=multiple_of,
573 le=le,
574 ge=ge,
575 lt=lt,
576 gt=gt,
577 strict=strict,
578 ref=ref,
579 metadata=metadata,
580 serialization=serialization,
581 )
584class FloatSchema(TypedDict, total=False):
585 type: Required[Literal['float']]
586 allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: True
587 multiple_of: float
588 le: float
589 ge: float
590 lt: float
591 gt: float
592 strict: bool
593 ref: str
594 metadata: Any
595 serialization: SerSchema
598def float_schema(
599 *,
600 allow_inf_nan: bool | None = None,
601 multiple_of: float | None = None,
602 le: float | None = None,
603 ge: float | None = None,
604 lt: float | None = None,
605 gt: float | None = None,
606 strict: bool | None = None,
607 ref: str | None = None,
608 metadata: Any = None,
609 serialization: SerSchema | None = None,
610) -> FloatSchema:
611 """
612 Returns a schema that matches a float value, e.g.:
614 ```py
615 from pydantic_core import SchemaValidator, core_schema
617 schema = core_schema.float_schema(le=0.8, ge=0.2)
618 v = SchemaValidator(schema)
619 assert v.validate_python('0.5') == 0.5
620 ```
622 Args:
623 allow_inf_nan: Whether to allow inf and nan values
624 multiple_of: The value must be a multiple of this number
625 le: The value must be less than or equal to this number
626 ge: The value must be greater than or equal to this number
627 lt: The value must be strictly less than this number
628 gt: The value must be strictly greater than this number
629 strict: Whether the value should be a float or a value that can be converted to a float
630 ref: optional unique identifier of the schema, used to reference the schema in other places
631 metadata: Any other information you want to include with the schema, not used by pydantic-core
632 serialization: Custom serialization schema
633 """
634 return dict_not_none(
635 type='float',
636 allow_inf_nan=allow_inf_nan,
637 multiple_of=multiple_of,
638 le=le,
639 ge=ge,
640 lt=lt,
641 gt=gt,
642 strict=strict,
643 ref=ref,
644 metadata=metadata,
645 serialization=serialization,
646 )
649class StringSchema(TypedDict, total=False):
650 type: Required[Literal['str']]
651 pattern: str
652 max_length: int
653 min_length: int
654 strip_whitespace: bool
655 to_lower: bool
656 to_upper: bool
657 strict: bool
658 ref: str
659 metadata: Any
660 serialization: SerSchema
663def str_schema(
664 *,
665 pattern: str | None = None,
666 max_length: int | None = None,
667 min_length: int | None = None,
668 strip_whitespace: bool | None = None,
669 to_lower: bool | None = None,
670 to_upper: bool | None = None,
671 strict: bool | None = None,
672 ref: str | None = None,
673 metadata: Any = None,
674 serialization: SerSchema | None = None,
675) -> StringSchema:
676 """
677 Returns a schema that matches a string value, e.g.:
679 ```py
680 from pydantic_core import SchemaValidator, core_schema
682 schema = core_schema.str_schema(max_length=10, min_length=2)
683 v = SchemaValidator(schema)
684 assert v.validate_python('hello') == 'hello'
685 ```
687 Args:
688 pattern: A regex pattern that the value must match
689 max_length: The value must be at most this length
690 min_length: The value must be at least this length
691 strip_whitespace: Whether to strip whitespace from the value
692 to_lower: Whether to convert the value to lowercase
693 to_upper: Whether to convert the value to uppercase
694 strict: Whether the value should be a string or a value that can be converted to a string
695 ref: optional unique identifier of the schema, used to reference the schema in other places
696 metadata: Any other information you want to include with the schema, not used by pydantic-core
697 serialization: Custom serialization schema
698 """
699 return dict_not_none(
700 type='str',
701 pattern=pattern,
702 max_length=max_length,
703 min_length=min_length,
704 strip_whitespace=strip_whitespace,
705 to_lower=to_lower,
706 to_upper=to_upper,
707 strict=strict,
708 ref=ref,
709 metadata=metadata,
710 serialization=serialization,
711 )
714class BytesSchema(TypedDict, total=False):
715 type: Required[Literal['bytes']]
716 max_length: int
717 min_length: int
718 strict: bool
719 ref: str
720 metadata: Any
721 serialization: SerSchema
724def bytes_schema(
725 *,
726 max_length: int | None = None,
727 min_length: int | None = None,
728 strict: bool | None = None,
729 ref: str | None = None,
730 metadata: Any = None,
731 serialization: SerSchema | None = None,
732) -> BytesSchema:
733 """
734 Returns a schema that matches a bytes value, e.g.:
736 ```py
737 from pydantic_core import SchemaValidator, core_schema
739 schema = core_schema.bytes_schema(max_length=10, min_length=2)
740 v = SchemaValidator(schema)
741 assert v.validate_python(b'hello') == b'hello'
742 ```
744 Args:
745 max_length: The value must be at most this length
746 min_length: The value must be at least this length
747 strict: Whether the value should be a bytes or a value that can be converted to a bytes
748 ref: optional unique identifier of the schema, used to reference the schema in other places
749 metadata: Any other information you want to include with the schema, not used by pydantic-core
750 serialization: Custom serialization schema
751 """
752 return dict_not_none(
753 type='bytes',
754 max_length=max_length,
755 min_length=min_length,
756 strict=strict,
757 ref=ref,
758 metadata=metadata,
759 serialization=serialization,
760 )
763class DateSchema(TypedDict, total=False):
764 type: Required[Literal['date']]
765 strict: bool
766 le: date
767 ge: date
768 lt: date
769 gt: date
770 now_op: Literal['past', 'future']
771 # defaults to current local utc offset from `time.localtime().tm_gmtoff`
772 # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py
773 now_utc_offset: int
774 ref: str
775 metadata: Any
776 serialization: SerSchema
779def date_schema(
780 *,
781 strict: bool | None = None,
782 le: date | None = None,
783 ge: date | None = None,
784 lt: date | None = None,
785 gt: date | None = None,
786 now_op: Literal['past', 'future'] | None = None,
787 now_utc_offset: int | None = None,
788 ref: str | None = None,
789 metadata: Any = None,
790 serialization: SerSchema | None = None,
791) -> DateSchema:
792 """
793 Returns a schema that matches a date value, e.g.:
795 ```py
796 from datetime import date
797 from pydantic_core import SchemaValidator, core_schema
799 schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1))
800 v = SchemaValidator(schema)
801 assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1)
802 ```
804 Args:
805 strict: Whether the value should be a date or a value that can be converted to a date
806 le: The value must be less than or equal to this date
807 ge: The value must be greater than or equal to this date
808 lt: The value must be strictly less than this date
809 gt: The value must be strictly greater than this date
810 now_op: The value must be in the past or future relative to the current date
811 now_utc_offset: The value must be in the past or future relative to the current date with this utc offset
812 ref: optional unique identifier of the schema, used to reference the schema in other places
813 metadata: Any other information you want to include with the schema, not used by pydantic-core
814 serialization: Custom serialization schema
815 """
816 return dict_not_none(
817 type='date',
818 strict=strict,
819 le=le,
820 ge=ge,
821 lt=lt,
822 gt=gt,
823 now_op=now_op,
824 now_utc_offset=now_utc_offset,
825 ref=ref,
826 metadata=metadata,
827 serialization=serialization,
828 )
831class TimeSchema(TypedDict, total=False):
832 type: Required[Literal['time']]
833 strict: bool
834 le: time
835 ge: time
836 lt: time
837 gt: time
838 ref: str
839 metadata: Any
840 serialization: SerSchema
843def time_schema(
844 *,
845 strict: bool | None = None,
846 le: time | None = None,
847 ge: time | None = None,
848 lt: time | None = None,
849 gt: time | None = None,
850 ref: str | None = None,
851 metadata: Any = None,
852 serialization: SerSchema | None = None,
853) -> TimeSchema:
854 """
855 Returns a schema that matches a time value, e.g.:
857 ```py
858 from datetime import time
859 from pydantic_core import SchemaValidator, core_schema
861 schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0))
862 v = SchemaValidator(schema)
863 assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0)
864 ```
866 Args:
867 strict: Whether the value should be a time or a value that can be converted to a time
868 le: The value must be less than or equal to this time
869 ge: The value must be greater than or equal to this time
870 lt: The value must be strictly less than this time
871 gt: The value must be strictly greater than this time
872 ref: optional unique identifier of the schema, used to reference the schema in other places
873 metadata: Any other information you want to include with the schema, not used by pydantic-core
874 serialization: Custom serialization schema
875 """
876 return dict_not_none(
877 type='time', strict=strict, le=le, ge=ge, lt=lt, gt=gt, ref=ref, metadata=metadata, serialization=serialization
878 )
881class DatetimeSchema(TypedDict, total=False):
882 type: Required[Literal['datetime']]
883 strict: bool
884 le: datetime
885 ge: datetime
886 lt: datetime
887 gt: datetime
888 now_op: Literal['past', 'future']
889 tz_constraint: Literal['aware', 'naive']
890 # defaults to current local utc offset from `time.localtime().tm_gmtoff`
891 # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py
892 now_utc_offset: int
893 ref: str
894 metadata: Any
895 serialization: SerSchema
898def datetime_schema(
899 *,
900 strict: bool | None = None,
901 le: datetime | None = None,
902 ge: datetime | None = None,
903 lt: datetime | None = None,
904 gt: datetime | None = None,
905 now_op: Literal['past', 'future'] | None = None,
906 tz_constraint: Literal['aware', 'naive'] | None = None,
907 now_utc_offset: int | None = None,
908 ref: str | None = None,
909 metadata: Any = None,
910 serialization: SerSchema | None = None,
911) -> DatetimeSchema:
912 """
913 Returns a schema that matches a datetime value, e.g.:
915 ```py
916 from datetime import datetime
917 from pydantic_core import SchemaValidator, core_schema
919 schema = core_schema.datetime_schema()
920 v = SchemaValidator(schema)
921 now = datetime.now()
922 assert v.validate_python(str(now)) == now
923 ```
925 Args:
926 strict: Whether the value should be a datetime or a value that can be converted to a datetime
927 le: The value must be less than or equal to this datetime
928 ge: The value must be greater than or equal to this datetime
929 lt: The value must be strictly less than this datetime
930 gt: The value must be strictly greater than this datetime
931 now_op: The value must be in the past or future relative to the current datetime
932 tz_constraint: The value must be timezone aware or naive
933 now_utc_offset: The value must be in the past or future relative to the current datetime with this utc offset
934 ref: optional unique identifier of the schema, used to reference the schema in other places
935 metadata: Any other information you want to include with the schema, not used by pydantic-core
936 serialization: Custom serialization schema
937 """
938 return dict_not_none(
939 type='datetime',
940 strict=strict,
941 le=le,
942 ge=ge,
943 lt=lt,
944 gt=gt,
945 now_op=now_op,
946 tz_constraint=tz_constraint,
947 now_utc_offset=now_utc_offset,
948 ref=ref,
949 metadata=metadata,
950 serialization=serialization,
951 )
954class TimedeltaSchema(TypedDict, total=False):
955 type: Required[Literal['timedelta']]
956 strict: bool
957 le: timedelta
958 ge: timedelta
959 lt: timedelta
960 gt: timedelta
961 ref: str
962 metadata: Any
963 serialization: SerSchema
966def timedelta_schema(
967 *,
968 strict: bool | None = None,
969 le: timedelta | None = None,
970 ge: timedelta | None = None,
971 lt: timedelta | None = None,
972 gt: timedelta | None = None,
973 ref: str | None = None,
974 metadata: Any = None,
975 serialization: SerSchema | None = None,
976) -> TimedeltaSchema:
977 """
978 Returns a schema that matches a timedelta value, e.g.:
980 ```py
981 from datetime import timedelta
982 from pydantic_core import SchemaValidator, core_schema
984 schema = core_schema.timedelta_schema(le=timedelta(days=1), ge=timedelta(days=0))
985 v = SchemaValidator(schema)
986 assert v.validate_python(timedelta(hours=12)) == timedelta(hours=12)
987 ```
989 Args:
990 strict: Whether the value should be a timedelta or a value that can be converted to a timedelta
991 le: The value must be less than or equal to this timedelta
992 ge: The value must be greater than or equal to this timedelta
993 lt: The value must be strictly less than this timedelta
994 gt: The value must be strictly greater than this timedelta
995 ref: optional unique identifier of the schema, used to reference the schema in other places
996 metadata: Any other information you want to include with the schema, not used by pydantic-core
997 serialization: Custom serialization schema
998 """
999 return dict_not_none(
1000 type='timedelta',
1001 strict=strict,
1002 le=le,
1003 ge=ge,
1004 lt=lt,
1005 gt=gt,
1006 ref=ref,
1007 metadata=metadata,
1008 serialization=serialization,
1009 )
1012class LiteralSchema(TypedDict, total=False):
1013 type: Required[Literal['literal']]
1014 expected: Required[List[Any]]
1015 ref: str
1016 metadata: Any
1017 serialization: SerSchema
1020def literal_schema(
1021 expected: list[Any], *, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None
1022) -> LiteralSchema:
1023 """
1024 Returns a schema that matches a literal value, e.g.:
1026 ```py
1027 from pydantic_core import SchemaValidator, core_schema
1029 schema = core_schema.literal_schema(['hello', 'world'])
1030 v = SchemaValidator(schema)
1031 assert v.validate_python('hello') == 'hello'
1032 ```
1034 Args:
1035 expected: The value must be one of these values
1036 ref: optional unique identifier of the schema, used to reference the schema in other places
1037 metadata: Any other information you want to include with the schema, not used by pydantic-core
1038 serialization: Custom serialization schema
1039 """
1040 return dict_not_none(type='literal', expected=expected, ref=ref, metadata=metadata, serialization=serialization)
1043# must match input/parse_json.rs::JsonType::try_from
1044JsonType = Literal['null', 'bool', 'int', 'float', 'str', 'list', 'dict']
1047class IsInstanceSchema(TypedDict, total=False):
1048 type: Required[Literal['is-instance']]
1049 cls: Required[Any]
1050 cls_repr: str
1051 json_types: Set[JsonType]
1052 json_function: Callable[[Any], Any]
1053 ref: str
1054 metadata: Any
1055 serialization: SerSchema
1058def is_instance_schema(
1059 cls: Any,
1060 *,
1061 json_types: Set[JsonType] | None = None,
1062 json_function: Callable[[Any], Any] | None = None,
1063 cls_repr: str | None = None,
1064 ref: str | None = None,
1065 metadata: Any = None,
1066 serialization: SerSchema | None = None,
1067) -> IsInstanceSchema:
1068 """
1069 Returns a schema that checks if a value is an instance of a class, equivalent to python's `isinstnace` method, e.g.:
1071 ```py
1072 from pydantic_core import SchemaValidator, core_schema
1074 class A:
1075 pass
1077 schema = core_schema.is_instance_schema(cls=A)
1078 v = SchemaValidator(schema)
1079 v.validate_python(A())
1080 ```
1082 Args:
1083 cls: The value must be an instance of this class
1084 json_types: When parsing JSON directly, the value must be one of these json types
1085 json_function: When parsing JSON directly, If provided, the JSON value is passed to this
1086 function and the return value used as the output value
1087 cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
1088 ref: optional unique identifier of the schema, used to reference the schema in other places
1089 metadata: Any other information you want to include with the schema, not used by pydantic-core
1090 serialization: Custom serialization schema
1091 """
1092 return dict_not_none(
1093 type='is-instance',
1094 cls=cls,
1095 json_types=json_types,
1096 json_function=json_function,
1097 cls_repr=cls_repr,
1098 ref=ref,
1099 metadata=metadata,
1100 serialization=serialization,
1101 )
1104class IsSubclassSchema(TypedDict, total=False):
1105 type: Required[Literal['is-subclass']]
1106 cls: Required[Type[Any]]
1107 cls_repr: str
1108 ref: str
1109 metadata: Any
1110 serialization: SerSchema
1113def is_subclass_schema(
1114 cls: Type[Any],
1115 *,
1116 cls_repr: str | None = None,
1117 ref: str | None = None,
1118 metadata: Any = None,
1119 serialization: SerSchema | None = None,
1120) -> IsInstanceSchema:
1121 """
1122 Returns a schema that checks if a value is a subtype of a class, equivalent to python's `issubclass` method, e.g.:
1124 ```py
1125 from pydantic_core import SchemaValidator, core_schema
1127 class A:
1128 pass
1130 class B(A):
1131 pass
1133 schema = core_schema.is_subclass_schema(cls=A)
1134 v = SchemaValidator(schema)
1135 v.validate_python(B)
1136 ```
1138 Args:
1139 cls: The value must be a subclass of this class
1140 cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
1141 ref: optional unique identifier of the schema, used to reference the schema in other places
1142 metadata: Any other information you want to include with the schema, not used by pydantic-core
1143 serialization: Custom serialization schema
1144 """
1145 return dict_not_none(
1146 type='is-subclass', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization
1147 )
1150class CallableSchema(TypedDict, total=False):
1151 type: Required[Literal['callable']]
1152 ref: str
1153 metadata: Any
1154 serialization: SerSchema
1157def callable_schema(
1158 *, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None
1159) -> CallableSchema:
1160 """
1161 Returns a schema that checks if a value is callable, equivalent to python's `callable` method, e.g.:
1163 ```py
1164 from pydantic_core import SchemaValidator, core_schema
1166 schema = core_schema.callable_schema()
1167 v = SchemaValidator(schema)
1168 v.validate_python(min)
1169 ```
1171 Args:
1172 ref: optional unique identifier of the schema, used to reference the schema in other places
1173 metadata: Any other information you want to include with the schema, not used by pydantic-core
1174 serialization: Custom serialization schema
1175 """
1176 return dict_not_none(type='callable', ref=ref, metadata=metadata, serialization=serialization)
1179class IncExSeqSerSchema(TypedDict, total=False):
1180 type: Required[Literal['include-exclude-sequence']]
1181 include: Set[int]
1182 exclude: Set[int]
1185def filter_seq_schema(*, include: Set[int] | None = None, exclude: Set[int] | None = None) -> IncExSeqSerSchema:
1186 return dict_not_none(type='include-exclude-sequence', include=include, exclude=exclude)
1189IncExSeqOrElseSerSchema = Union[IncExSeqSerSchema, SerSchema]
1192class ListSchema(TypedDict, total=False):
1193 type: Required[Literal['list']]
1194 items_schema: CoreSchema
1195 min_length: int
1196 max_length: int
1197 strict: bool
1198 allow_any_iter: bool
1199 ref: str
1200 metadata: Any
1201 serialization: IncExSeqOrElseSerSchema
1204def list_schema(
1205 items_schema: CoreSchema | None = None,
1206 *,
1207 min_length: int | None = None,
1208 max_length: int | None = None,
1209 strict: bool | None = None,
1210 allow_any_iter: bool | None = None,
1211 ref: str | None = None,
1212 metadata: Any = None,
1213 serialization: IncExSeqOrElseSerSchema | None = None,
1214) -> ListSchema:
1215 """
1216 Returns a schema that matches a list value, e.g.:
1218 ```py
1219 from pydantic_core import SchemaValidator, core_schema
1221 schema = core_schema.list_schema(core_schema.int_schema(), min_length=0, max_length=10)
1222 v = SchemaValidator(schema)
1223 assert v.validate_python(['4']) == [4]
1224 ```
1226 Args:
1227 items_schema: The value must be a list of items that match this schema
1228 min_length: The value must be a list with at least this many items
1229 max_length: The value must be a list with at most this many items
1230 strict: The value must be a list with exactly this many items
1231 allow_any_iter: Whether the value can be any iterable
1232 ref: optional unique identifier of the schema, used to reference the schema in other places
1233 metadata: Any other information you want to include with the schema, not used by pydantic-core
1234 serialization: Custom serialization schema
1235 """
1236 return dict_not_none(
1237 type='list',
1238 items_schema=items_schema,
1239 min_length=min_length,
1240 max_length=max_length,
1241 strict=strict,
1242 allow_any_iter=allow_any_iter,
1243 ref=ref,
1244 metadata=metadata,
1245 serialization=serialization,
1246 )
1249class TuplePositionalSchema(TypedDict, total=False):
1250 type: Required[Literal['tuple-positional']]
1251 items_schema: Required[List[CoreSchema]]
1252 extra_schema: CoreSchema
1253 strict: bool
1254 ref: str
1255 metadata: Any
1256 serialization: IncExSeqOrElseSerSchema
1259def tuple_positional_schema(
1260 items_schema: list[CoreSchema],
1261 *,
1262 extra_schema: CoreSchema | None = None,
1263 strict: bool | None = None,
1264 ref: str | None = None,
1265 metadata: Any = None,
1266 serialization: IncExSeqOrElseSerSchema | None = None,
1267) -> TuplePositionalSchema:
1268 """
1269 Returns a schema that matches a tuple of schemas, e.g.:
1271 ```py
1272 from pydantic_core import SchemaValidator, core_schema
1274 schema = core_schema.tuple_positional_schema(
1275 [core_schema.int_schema(), core_schema.str_schema()]
1276 )
1277 v = SchemaValidator(schema)
1278 assert v.validate_python((1, 'hello')) == (1, 'hello')
1279 ```
1281 Args:
1282 items_schema: The value must be a tuple with items that match these schemas
1283 extra_schema: The value must be a tuple with items that match this schema
1284 This was inspired by JSON schema's `prefixItems` and `items` fields.
1285 In python's `typing.Tuple`, you can't specify a type for "extra" items -- they must all be the same type
1286 if the length is variable. So this field won't be set from a `typing.Tuple` annotation on a pydantic model.
1287 strict: The value must be a tuple with exactly this many items
1288 ref: optional unique identifier of the schema, used to reference the schema in other places
1289 metadata: Any other information you want to include with the schema, not used by pydantic-core
1290 serialization: Custom serialization schema
1291 """
1292 return dict_not_none(
1293 type='tuple-positional',
1294 items_schema=items_schema,
1295 extra_schema=extra_schema,
1296 strict=strict,
1297 ref=ref,
1298 metadata=metadata,
1299 serialization=serialization,
1300 )
1303class TupleVariableSchema(TypedDict, total=False):
1304 type: Required[Literal['tuple-variable']]
1305 items_schema: CoreSchema
1306 min_length: int
1307 max_length: int
1308 strict: bool
1309 ref: str
1310 metadata: Any
1311 serialization: IncExSeqOrElseSerSchema
1314def tuple_variable_schema(
1315 items_schema: CoreSchema | None = None,
1316 *,
1317 min_length: int | None = None,
1318 max_length: int | None = None,
1319 strict: bool | None = None,
1320 ref: str | None = None,
1321 metadata: Any = None,
1322 serialization: IncExSeqOrElseSerSchema | None = None,
1323) -> TupleVariableSchema:
1324 """
1325 Returns a schema that matches a tuple of a given schema, e.g.:
1327 ```py
1328 from pydantic_core import SchemaValidator, core_schema
1330 schema = core_schema.tuple_variable_schema(
1331 items_schema=core_schema.int_schema(), min_length=0, max_length=10
1332 )
1333 v = SchemaValidator(schema)
1334 assert v.validate_python(('1', 2, 3)) == (1, 2, 3)
1335 ```
1337 Args:
1338 items_schema: The value must be a tuple with items that match this schema
1339 min_length: The value must be a tuple with at least this many items
1340 max_length: The value must be a tuple with at most this many items
1341 strict: The value must be a tuple with exactly this many items
1342 ref: optional unique identifier of the schema, used to reference the schema in other places
1343 metadata: Any other information you want to include with the schema, not used by pydantic-core
1344 serialization: Custom serialization schema
1345 """
1346 return dict_not_none(
1347 type='tuple-variable',
1348 items_schema=items_schema,
1349 min_length=min_length,
1350 max_length=max_length,
1351 strict=strict,
1352 ref=ref,
1353 metadata=metadata,
1354 serialization=serialization,
1355 )
1358class SetSchema(TypedDict, total=False):
1359 type: Required[Literal['set']]
1360 items_schema: CoreSchema
1361 min_length: int
1362 max_length: int
1363 generator_max_length: int
1364 strict: bool
1365 ref: str
1366 metadata: Any
1367 serialization: SerSchema
1370def set_schema(
1371 items_schema: CoreSchema | None = None,
1372 *,
1373 min_length: int | None = None,
1374 max_length: int | None = None,
1375 generator_max_length: int | None = None,
1376 strict: bool | None = None,
1377 ref: str | None = None,
1378 metadata: Any = None,
1379 serialization: SerSchema | None = None,
1380) -> SetSchema:
1381 """
1382 Returns a schema that matches a set of a given schema, e.g.:
1384 ```py
1385 from pydantic_core import SchemaValidator, core_schema
1387 schema = core_schema.set_schema(
1388 items_schema=core_schema.int_schema(), min_length=0, max_length=10
1389 )
1390 v = SchemaValidator(schema)
1391 assert v.validate_python({1, '2', 3}) == {1, 2, 3}
1392 ```
1394 Args:
1395 items_schema: The value must be a set with items that match this schema
1396 min_length: The value must be a set with at least this many items
1397 max_length: The value must be a set with at most this many items
1398 generator_max_length: At most this many items will be read from a generator before failing validation
1399 This is important because generators can be infinite, and even with a `max_length` on the set,
1400 an infinite generator could run forever without producing more than `max_length` distinct items.
1401 strict: The value must be a set with exactly this many items
1402 ref: optional unique identifier of the schema, used to reference the schema in other places
1403 metadata: Any other information you want to include with the schema, not used by pydantic-core
1404 serialization: Custom serialization schema
1405 """
1406 return dict_not_none(
1407 type='set',
1408 items_schema=items_schema,
1409 min_length=min_length,
1410 max_length=max_length,
1411 generator_max_length=generator_max_length,
1412 strict=strict,
1413 ref=ref,
1414 metadata=metadata,
1415 serialization=serialization,
1416 )
1419class FrozenSetSchema(TypedDict, total=False):
1420 type: Required[Literal['frozenset']]
1421 items_schema: CoreSchema
1422 min_length: int
1423 max_length: int
1424 generator_max_length: int
1425 strict: bool
1426 ref: str
1427 metadata: Any
1428 serialization: SerSchema
1431def frozenset_schema(
1432 items_schema: CoreSchema | None = None,
1433 *,
1434 min_length: int | None = None,
1435 max_length: int | None = None,
1436 generator_max_length: int | None = None,
1437 strict: bool | None = None,
1438 ref: str | None = None,
1439 metadata: Any = None,
1440 serialization: SerSchema | None = None,
1441) -> FrozenSetSchema:
1442 """
1443 Returns a schema that matches a frozenset of a given schema, e.g.:
1445 ```py
1446 from pydantic_core import SchemaValidator, core_schema
1448 schema = core_schema.frozenset_schema(
1449 items_schema=core_schema.int_schema(), min_length=0, max_length=10
1450 )
1451 v = SchemaValidator(schema)
1452 assert v.validate_python(frozenset(range(3))) == frozenset({0, 1, 2})
1453 ```
1455 Args:
1456 items_schema: The value must be a frozenset with items that match this schema
1457 min_length: The value must be a frozenset with at least this many items
1458 max_length: The value must be a frozenset with at most this many items
1459 generator_max_length: The value must generate a frozenset with at most this many items
1460 strict: The value must be a frozenset with exactly this many items
1461 ref: optional unique identifier of the schema, used to reference the schema in other places
1462 metadata: Any other information you want to include with the schema, not used by pydantic-core
1463 serialization: Custom serialization schema
1464 """
1465 return dict_not_none(
1466 type='frozenset',
1467 items_schema=items_schema,
1468 min_length=min_length,
1469 max_length=max_length,
1470 generator_max_length=generator_max_length,
1471 strict=strict,
1472 ref=ref,
1473 metadata=metadata,
1474 serialization=serialization,
1475 )
1478class GeneratorSchema(TypedDict, total=False):
1479 type: Required[Literal['generator']]
1480 items_schema: CoreSchema
1481 min_length: int
1482 max_length: int
1483 ref: str
1484 metadata: Any
1485 serialization: IncExSeqOrElseSerSchema
1488def generator_schema(
1489 items_schema: CoreSchema | None = None,
1490 *,
1491 min_length: int | None = None,
1492 max_length: int | None = None,
1493 ref: str | None = None,
1494 metadata: Any = None,
1495 serialization: IncExSeqOrElseSerSchema | None = None,
1496) -> GeneratorSchema:
1497 """
1498 Returns a schema that matches a generator value, e.g.:
1500 ```py
1501 from typing import Iterator
1502 from pydantic_core import SchemaValidator, core_schema
1504 def gen() -> Iterator[int]:
1505 yield 1
1507 schema = core_schema.generator_schema(items_schema=core_schema.int_schema())
1508 v = SchemaValidator(schema)
1509 v.validate_python(gen())
1510 ```
1512 Unlike other types, validated generators do not raise ValidationErrors eagerly,
1513 but instead will raise a ValidationError when a violating value is actually read from the generator.
1514 This is to ensure that "validated" generators retain the benefit of lazy evaluation.
1516 Args:
1517 items_schema: The value must be a generator with items that match this schema
1518 min_length: The value must be a generator that yields at least this many items
1519 max_length: The value must be a generator that yields at most this many items
1520 ref: optional unique identifier of the schema, used to reference the schema in other places
1521 metadata: Any other information you want to include with the schema, not used by pydantic-core
1522 serialization: Custom serialization schema
1523 """
1524 return dict_not_none(
1525 type='generator',
1526 items_schema=items_schema,
1527 min_length=min_length,
1528 max_length=max_length,
1529 ref=ref,
1530 metadata=metadata,
1531 serialization=serialization,
1532 )
1535IncExDict = Set[Union[int, str]]
1538class IncExDictSerSchema(TypedDict, total=False):
1539 type: Required[Literal['include-exclude-dict']]
1540 include: IncExDict
1541 exclude: IncExDict
1544def filter_dict_schema(*, include: IncExDict | None = None, exclude: IncExDict | None = None) -> IncExDictSerSchema:
1545 return dict_not_none(type='include-exclude-dict', include=include, exclude=exclude)
1548IncExDictOrElseSerSchema = Union[IncExDictSerSchema, SerSchema]
1551class DictSchema(TypedDict, total=False):
1552 type: Required[Literal['dict']]
1553 keys_schema: CoreSchema # default: AnySchema
1554 values_schema: CoreSchema # default: AnySchema
1555 min_length: int
1556 max_length: int
1557 strict: bool
1558 ref: str
1559 metadata: Any
1560 serialization: IncExDictOrElseSerSchema
1563def dict_schema(
1564 keys_schema: CoreSchema | None = None,
1565 values_schema: CoreSchema | None = None,
1566 *,
1567 min_length: int | None = None,
1568 max_length: int | None = None,
1569 strict: bool | None = None,
1570 ref: str | None = None,
1571 metadata: Any = None,
1572 serialization: SerSchema | None = None,
1573) -> DictSchema:
1574 """
1575 Returns a schema that matches a dict value, e.g.:
1577 ```py
1578 from pydantic_core import SchemaValidator, core_schema
1580 schema = core_schema.dict_schema(
1581 keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
1582 )
1583 v = SchemaValidator(schema)
1584 assert v.validate_python({'a': '1', 'b': 2}) == {'a': 1, 'b': 2}
1585 ```
1587 Args:
1588 keys_schema: The value must be a dict with keys that match this schema
1589 values_schema: The value must be a dict with values that match this schema
1590 min_length: The value must be a dict with at least this many items
1591 max_length: The value must be a dict with at most this many items
1592 strict: Whether the keys and values should be validated with strict mode
1593 ref: optional unique identifier of the schema, used to reference the schema in other places
1594 metadata: Any other information you want to include with the schema, not used by pydantic-core
1595 serialization: Custom serialization schema
1596 """
1597 return dict_not_none(
1598 type='dict',
1599 keys_schema=keys_schema,
1600 values_schema=values_schema,
1601 min_length=min_length,
1602 max_length=max_length,
1603 strict=strict,
1604 ref=ref,
1605 metadata=metadata,
1606 serialization=serialization,
1607 )
1610# (__input_value: Any) -> Any
1611NoInfoValidatorFunction = Callable[[Any], Any]
1614class NoInfoValidatorFunctionSchema(TypedDict):
1615 type: Literal['no-info']
1616 function: NoInfoValidatorFunction
1619# (__input_value: Any, __info: ValidationInfo) -> Any
1620GeneralValidatorFunction = Callable[[Any, ValidationInfo], Any]
1623class GeneralValidatorFunctionSchema(TypedDict):
1624 type: Literal['general']
1625 function: GeneralValidatorFunction
1628# (__input_value: Any, __info: FieldValidationInfo) -> Any
1629FieldValidatorFunction = Callable[[Any, FieldValidationInfo], Any]
1632class FieldValidatorFunctionSchema(TypedDict):
1633 type: Literal['field']
1634 function: FieldValidatorFunction
1637ValidationFunction = Union[NoInfoValidatorFunctionSchema, FieldValidatorFunctionSchema, GeneralValidatorFunctionSchema]
1640class _ValidatorFunctionSchema(TypedDict, total=False):
1641 function: Required[ValidationFunction]
1642 schema: Required[CoreSchema]
1643 ref: str
1644 metadata: Any
1645 serialization: SerSchema
1648class BeforeValidatorFunctionSchema(_ValidatorFunctionSchema, total=False):
1649 type: Required[Literal['function-before']]
1652def no_info_before_validator_function(
1653 function: NoInfoValidatorFunction,
1654 schema: CoreSchema,
1655 *,
1656 ref: str | None = None,
1657 metadata: Any = None,
1658 serialization: SerSchema | None = None,
1659) -> BeforeValidatorFunctionSchema:
1660 """
1661 Returns a schema that calls a validator function before validating, no info is provided, e.g.:
1663 ```py
1664 from pydantic_core import SchemaValidator, core_schema
1666 def fn(v: bytes) -> str:
1667 return v.decode() + 'world'
1669 func_schema = core_schema.no_info_before_validator_function(
1670 function=fn, schema=core_schema.str_schema()
1671 )
1672 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
1674 v = SchemaValidator(schema)
1675 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
1676 ```
1678 Args:
1679 function: The validator function to call
1680 schema: The schema to validate the output of the validator function
1681 ref: optional unique identifier of the schema, used to reference the schema in other places
1682 metadata: Any other information you want to include with the schema, not used by pydantic-core
1683 serialization: Custom serialization schema
1684 """
1685 return dict_not_none(
1686 type='function-before',
1687 function={'type': 'no-info', 'function': function},
1688 schema=schema,
1689 ref=ref,
1690 metadata=metadata,
1691 serialization=serialization,
1692 )
1695def field_before_validator_function(
1696 function: FieldValidatorFunction,
1697 schema: CoreSchema,
1698 *,
1699 ref: str | None = None,
1700 metadata: Any = None,
1701 serialization: SerSchema | None = None,
1702) -> BeforeValidatorFunctionSchema:
1703 """
1704 Returns a schema that calls a validator function before validating the function is called with information
1705 about the field being validated, e.g.:
1707 ```py
1708 from pydantic_core import SchemaValidator, core_schema
1710 def fn(v: bytes, info: core_schema.FieldValidationInfo) -> str:
1711 assert info.data is not None
1712 assert info.field_name is not None
1713 return v.decode() + 'world'
1715 func_schema = core_schema.field_before_validator_function(
1716 function=fn, schema=core_schema.str_schema()
1717 )
1718 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
1720 v = SchemaValidator(schema)
1721 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
1722 ```
1724 Args:
1725 function: The validator function to call
1726 schema: The schema to validate the output of the validator function
1727 ref: optional unique identifier of the schema, used to reference the schema in other places
1728 metadata: Any other information you want to include with the schema, not used by pydantic-core
1729 serialization: Custom serialization schema
1730 """
1731 return dict_not_none(
1732 type='function-before',
1733 function={'type': 'field', 'function': function},
1734 schema=schema,
1735 ref=ref,
1736 metadata=metadata,
1737 serialization=serialization,
1738 )
1741def general_before_validator_function(
1742 function: GeneralValidatorFunction,
1743 schema: CoreSchema,
1744 *,
1745 ref: str | None = None,
1746 metadata: Any = None,
1747 serialization: SerSchema | None = None,
1748) -> BeforeValidatorFunctionSchema:
1749 """
1750 Returns a schema that calls a validator function before validating the provided schema, e.g.:
1752 ```py
1753 from typing import Any
1754 from pydantic_core import SchemaValidator, core_schema
1756 def fn(v: Any, info: core_schema.ValidationInfo) -> str:
1757 v_str = str(v)
1758 assert 'hello' in v_str
1759 return v_str + 'world'
1761 schema = core_schema.general_before_validator_function(
1762 function=fn, schema=core_schema.str_schema()
1763 )
1764 v = SchemaValidator(schema)
1765 assert v.validate_python(b'hello ') == "b'hello 'world"
1766 ```
1768 Args:
1769 function: The validator function to call
1770 schema: The schema to validate the output of the validator function
1771 ref: optional unique identifier of the schema, used to reference the schema in other places
1772 metadata: Any other information you want to include with the schema, not used by pydantic-core
1773 serialization: Custom serialization schema
1774 """
1775 return dict_not_none(
1776 type='function-before',
1777 function={'type': 'general', 'function': function},
1778 schema=schema,
1779 ref=ref,
1780 metadata=metadata,
1781 serialization=serialization,
1782 )
1785class AfterValidatorFunctionSchema(_ValidatorFunctionSchema, total=False):
1786 type: Required[Literal['function-after']]
1789def no_info_after_validator_function(
1790 function: NoInfoValidatorFunction,
1791 schema: CoreSchema,
1792 *,
1793 ref: str | None = None,
1794 metadata: Any = None,
1795 serialization: SerSchema | None = None,
1796) -> AfterValidatorFunctionSchema:
1797 """
1798 Returns a schema that calls a validator function after validating, no info is provided, e.g.:
1800 ```py
1801 from pydantic_core import SchemaValidator, core_schema
1803 def fn(v: str) -> str:
1804 return v + 'world'
1806 func_schema = core_schema.no_info_after_validator_function(fn, core_schema.str_schema())
1807 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
1809 v = SchemaValidator(schema)
1810 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
1811 ```
1813 Args:
1814 function: The validator function to call after the schema is validated
1815 schema: The schema to validate before the validator function
1816 ref: optional unique identifier of the schema, used to reference the schema in other places
1817 metadata: Any other information you want to include with the schema, not used by pydantic-core
1818 serialization: Custom serialization schema
1819 """
1820 return dict_not_none(
1821 type='function-after',
1822 function={'type': 'no-info', 'function': function},
1823 schema=schema,
1824 ref=ref,
1825 metadata=metadata,
1826 serialization=serialization,
1827 )
1830def field_after_validator_function(
1831 function: FieldValidatorFunction,
1832 schema: CoreSchema,
1833 *,
1834 ref: str | None = None,
1835 metadata: Any = None,
1836 serialization: SerSchema | None = None,
1837) -> AfterValidatorFunctionSchema:
1838 """
1839 Returns a schema that calls a validator function after validating the function is called with information
1840 about the field being validated, e.g.:
1842 ```py
1843 from pydantic_core import SchemaValidator, core_schema
1845 def fn(v: str, info: core_schema.FieldValidationInfo) -> str:
1846 assert info.data is not None
1847 assert info.field_name is not None
1848 return v + 'world'
1850 func_schema = core_schema.field_after_validator_function(
1851 function=fn, schema=core_schema.str_schema()
1852 )
1853 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
1855 v = SchemaValidator(schema)
1856 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
1857 ```
1859 Args:
1860 function: The validator function to call after the schema is validated
1861 schema: The schema to validate before the validator function
1862 ref: optional unique identifier of the schema, used to reference the schema in other places
1863 metadata: Any other information you want to include with the schema, not used by pydantic-core
1864 serialization: Custom serialization schema
1865 """
1866 return dict_not_none(
1867 type='function-after',
1868 function={'type': 'field', 'function': function},
1869 schema=schema,
1870 ref=ref,
1871 metadata=metadata,
1872 serialization=serialization,
1873 )
1876def general_after_validator_function(
1877 function: GeneralValidatorFunction,
1878 schema: CoreSchema,
1879 *,
1880 ref: str | None = None,
1881 metadata: Any = None,
1882 serialization: SerSchema | None = None,
1883) -> AfterValidatorFunctionSchema:
1884 """
1885 Returns a schema that calls a validator function after validating the provided schema, e.g.:
1887 ```py
1888 from pydantic_core import SchemaValidator, core_schema
1890 def fn(v: str, info: core_schema.ValidationInfo) -> str:
1891 assert 'hello' in v
1892 return v + 'world'
1894 schema = core_schema.general_after_validator_function(
1895 schema=core_schema.str_schema(), function=fn
1896 )
1897 v = SchemaValidator(schema)
1898 assert v.validate_python('hello ') == 'hello world'
1899 ```
1901 Args:
1902 schema: The schema to validate before the validator function
1903 function: The validator function to call after the schema is validated
1904 ref: optional unique identifier of the schema, used to reference the schema in other places
1905 metadata: Any other information you want to include with the schema, not used by pydantic-core
1906 serialization: Custom serialization schema
1907 """
1908 return dict_not_none(
1909 type='function-after',
1910 function={'type': 'general', 'function': function},
1911 schema=schema,
1912 ref=ref,
1913 metadata=metadata,
1914 serialization=serialization,
1915 )
1918class ValidatorFunctionWrapHandler(Protocol):
1919 def __call__(self, input_value: Any, outer_location: str | int | None = None) -> Any: # pragma: no cover
1920 ...
1923# (__input_value: Any, __validator: ValidatorFunctionWrapHandler) -> Any
1924NoInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler], Any]
1927class NoInfoWrapValidatorFunctionSchema(TypedDict):
1928 type: Literal['no-info']
1929 function: NoInfoWrapValidatorFunction
1932# (__input_value: Any, __validator: ValidatorFunctionWrapHandler, __info: ValidationInfo) -> Any
1933GeneralWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler, ValidationInfo], Any]
1936class GeneralWrapValidatorFunctionSchema(TypedDict):
1937 type: Literal['general']
1938 function: GeneralWrapValidatorFunction
1941# (__input_value: Any, __validator: ValidatorFunctionWrapHandler, __info: FieldValidationInfo) -> Any
1942FieldWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler, FieldValidationInfo], Any]
1945class FieldWrapValidatorFunctionSchema(TypedDict):
1946 type: Literal['field']
1947 function: FieldWrapValidatorFunction
1950WrapValidatorFunction = Union[
1951 NoInfoWrapValidatorFunctionSchema, GeneralWrapValidatorFunctionSchema, FieldWrapValidatorFunctionSchema
1952]
1955class WrapValidatorFunctionSchema(TypedDict, total=False):
1956 type: Required[Literal['function-wrap']]
1957 function: Required[WrapValidatorFunction]
1958 schema: Required[CoreSchema]
1959 ref: str
1960 metadata: Any
1961 serialization: SerSchema
1964def no_info_wrap_validator_function(
1965 function: NoInfoWrapValidatorFunction,
1966 schema: CoreSchema,
1967 *,
1968 ref: str | None = None,
1969 metadata: Any = None,
1970 serialization: SerSchema | None = None,
1971) -> WrapValidatorFunctionSchema:
1972 """
1973 Returns a schema which calls a function with a `validator` callable argument which can
1974 optionally be used to call inner validation with the function logic, this is much like the
1975 "onion" implementation of middleware in many popular web frameworks, no info argument is passed, e.g.:
1977 ```py
1978 from pydantic_core import SchemaValidator, core_schema
1980 def fn(
1981 v: str,
1982 validator: core_schema.ValidatorFunctionWrapHandler,
1983 ) -> str:
1984 return validator(input_value=v) + 'world'
1986 schema = core_schema.no_info_wrap_validator_function(
1987 function=fn, schema=core_schema.str_schema()
1988 )
1989 v = SchemaValidator(schema)
1990 assert v.validate_python('hello ') == 'hello world'
1991 ```
1993 Args:
1994 function: The validator function to call
1995 schema: The schema to validate the output of the validator function
1996 ref: optional unique identifier of the schema, used to reference the schema in other places
1997 metadata: Any other information you want to include with the schema, not used by pydantic-core
1998 serialization: Custom serialization schema
1999 """
2000 return dict_not_none(
2001 type='function-wrap',
2002 function={'type': 'no-info', 'function': function},
2003 schema=schema,
2004 ref=ref,
2005 metadata=metadata,
2006 serialization=serialization,
2007 )
2010def general_wrap_validator_function(
2011 function: GeneralWrapValidatorFunction,
2012 schema: CoreSchema,
2013 *,
2014 ref: str | None = None,
2015 metadata: Any = None,
2016 serialization: SerSchema | None = None,
2017) -> WrapValidatorFunctionSchema:
2018 """
2019 Returns a schema which calls a function with a `validator` callable argument which can
2020 optionally be used to call inner validation with the function logic, this is much like the
2021 "onion" implementation of middleware in many popular web frameworks, general info is also passed, e.g.:
2023 ```py
2024 from pydantic_core import SchemaValidator, core_schema
2026 def fn(
2027 v: str,
2028 validator: core_schema.ValidatorFunctionWrapHandler,
2029 info: core_schema.ValidationInfo,
2030 ) -> str:
2031 return validator(input_value=v) + 'world'
2033 schema = core_schema.general_wrap_validator_function(
2034 function=fn, schema=core_schema.str_schema()
2035 )
2036 v = SchemaValidator(schema)
2037 assert v.validate_python('hello ') == 'hello world'
2038 ```
2040 Args:
2041 function: The validator function to call
2042 schema: The schema to validate the output of the validator function
2043 ref: optional unique identifier of the schema, used to reference the schema in other places
2044 metadata: Any other information you want to include with the schema, not used by pydantic-core
2045 serialization: Custom serialization schema
2046 """
2047 return dict_not_none(
2048 type='function-wrap',
2049 function={'type': 'general', 'function': function},
2050 schema=schema,
2051 ref=ref,
2052 metadata=metadata,
2053 serialization=serialization,
2054 )
2057def field_wrap_validator_function(
2058 function: FieldWrapValidatorFunction,
2059 schema: CoreSchema,
2060 *,
2061 ref: str | None = None,
2062 metadata: Any = None,
2063 serialization: SerSchema | None = None,
2064) -> WrapValidatorFunctionSchema:
2065 """
2066 Returns a schema applicable to **fields**
2067 which calls a function with a `validator` callable argument which can
2068 optionally be used to call inner validation with the function logic, this is much like the
2069 "onion" implementation of middleware in many popular web frameworks, field info is passed, e.g.:
2071 ```py
2072 from pydantic_core import SchemaValidator, core_schema
2074 def fn(
2075 v: bytes,
2076 validator: core_schema.ValidatorFunctionWrapHandler,
2077 info: core_schema.FieldValidationInfo,
2078 ) -> str:
2079 assert info.data is not None
2080 assert info.field_name is not None
2081 return validator(v) + 'world'
2083 func_schema = core_schema.field_wrap_validator_function(
2084 function=fn, schema=core_schema.str_schema()
2085 )
2086 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
2088 v = SchemaValidator(schema)
2089 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
2090 ```
2092 Args:
2093 function: The validator function to call
2094 schema: The schema to validate the output of the validator function
2095 ref: optional unique identifier of the schema, used to reference the schema in other places
2096 metadata: Any other information you want to include with the schema, not used by pydantic-core
2097 serialization: Custom serialization schema
2098 """
2099 return dict_not_none(
2100 type='function-wrap',
2101 function={'type': 'field', 'function': function},
2102 schema=schema,
2103 ref=ref,
2104 metadata=metadata,
2105 serialization=serialization,
2106 )
2109class PlainValidatorFunctionSchema(TypedDict, total=False):
2110 type: Required[Literal['function-plain']]
2111 function: Required[ValidationFunction]
2112 ref: str
2113 metadata: Any
2114 serialization: SerSchema
2117def no_info_plain_validator_function(
2118 function: NoInfoValidatorFunction,
2119 *,
2120 ref: str | None = None,
2121 metadata: Any = None,
2122 serialization: SerSchema | None = None,
2123) -> PlainValidatorFunctionSchema:
2124 """
2125 Returns a schema that uses the provided function for validation, no info is passed, e.g.:
2127 ```py
2128 from pydantic_core import SchemaValidator, core_schema
2130 def fn(v: str) -> str:
2131 assert 'hello' in v
2132 return v + 'world'
2134 schema = core_schema.no_info_plain_validator_function(function=fn)
2135 v = SchemaValidator(schema)
2136 assert v.validate_python('hello ') == 'hello world'
2137 ```
2139 Args:
2140 function: The validator function to call
2141 ref: optional unique identifier of the schema, used to reference the schema in other places
2142 metadata: Any other information you want to include with the schema, not used by pydantic-core
2143 serialization: Custom serialization schema
2144 """
2145 return dict_not_none(
2146 type='function-plain',
2147 function={'type': 'no-info', 'function': function},
2148 ref=ref,
2149 metadata=metadata,
2150 serialization=serialization,
2151 )
2154def general_plain_validator_function(
2155 function: GeneralValidatorFunction,
2156 *,
2157 ref: str | None = None,
2158 metadata: Any = None,
2159 serialization: SerSchema | None = None,
2160) -> PlainValidatorFunctionSchema:
2161 """
2162 Returns a schema that uses the provided function for validation, e.g.:
2164 ```py
2165 from pydantic_core import SchemaValidator, core_schema
2167 def fn(v: str, info: core_schema.ValidationInfo) -> str:
2168 assert 'hello' in v
2169 return v + 'world'
2171 schema = core_schema.general_plain_validator_function(function=fn)
2172 v = SchemaValidator(schema)
2173 assert v.validate_python('hello ') == 'hello world'
2174 ```
2176 Args:
2177 function: The validator function to call
2178 ref: optional unique identifier of the schema, used to reference the schema in other places
2179 metadata: Any other information you want to include with the schema, not used by pydantic-core
2180 serialization: Custom serialization schema
2181 """
2182 return dict_not_none(
2183 type='function-plain',
2184 function={'type': 'general', 'function': function},
2185 ref=ref,
2186 metadata=metadata,
2187 serialization=serialization,
2188 )
2191def field_plain_validator_function(
2192 function: FieldValidatorFunction,
2193 *,
2194 ref: str | None = None,
2195 metadata: Any = None,
2196 serialization: SerSchema | None = None,
2197) -> PlainValidatorFunctionSchema:
2198 """
2199 Returns a schema that uses the provided function for validation, e.g.:
2201 ```py
2202 from typing import Any
2203 from pydantic_core import SchemaValidator, core_schema
2205 def fn(v: Any, info: core_schema.FieldValidationInfo) -> str:
2206 assert info.data is not None
2207 assert info.field_name is not None
2208 return str(v) + 'world'
2210 func_schema = core_schema.field_plain_validator_function(function=fn)
2211 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
2213 v = SchemaValidator(schema)
2214 assert v.validate_python({'a': 'hello '}) == {'a': 'hello world'}
2215 ```
2217 Args:
2218 function: The validator function to call
2219 ref: optional unique identifier of the schema, used to reference the schema in other places
2220 metadata: Any other information you want to include with the schema, not used by pydantic-core
2221 serialization: Custom serialization schema
2222 """
2223 return dict_not_none(
2224 type='function-plain',
2225 function={'type': 'field', 'function': function},
2226 ref=ref,
2227 metadata=metadata,
2228 serialization=serialization,
2229 )
2232class WithDefaultSchema(TypedDict, total=False):
2233 type: Required[Literal['default']]
2234 schema: Required[CoreSchema]
2235 default: Any
2236 default_factory: Callable[[], Any]
2237 on_error: Literal['raise', 'omit', 'default'] # default: 'raise'
2238 validate_default: bool # default: False
2239 strict: bool
2240 ref: str
2241 metadata: Any
2242 serialization: SerSchema
2245Omitted = object()
2248def with_default_schema(
2249 schema: CoreSchema,
2250 *,
2251 default: Any = Omitted,
2252 default_factory: Callable[[], Any] | None = None,
2253 on_error: Literal['raise', 'omit', 'default'] | None = None,
2254 validate_default: bool | None = None,
2255 strict: bool | None = None,
2256 ref: str | None = None,
2257 metadata: Any = None,
2258 serialization: SerSchema | None = None,
2259) -> WithDefaultSchema:
2260 """
2261 Returns a schema that adds a default value to the given schema, e.g.:
2263 ```py
2264 from pydantic_core import SchemaValidator, core_schema
2266 schema = core_schema.with_default_schema(core_schema.str_schema(), default='hello')
2267 wrapper_schema = core_schema.typed_dict_schema(
2268 {'a': core_schema.typed_dict_field(schema)}
2269 )
2270 v = SchemaValidator(wrapper_schema)
2271 assert v.validate_python({}) == v.validate_python({'a': 'hello'})
2272 ```
2274 Args:
2275 schema: The schema to add a default value to
2276 default: The default value to use
2277 default_factory: A function that returns the default value to use
2278 on_error: What to do if the schema validation fails. One of 'raise', 'omit', 'default'
2279 validate_default: Whether the default value should be validated
2280 strict: Whether the underlying schema should be validated with strict mode
2281 ref: optional unique identifier of the schema, used to reference the schema in other places
2282 metadata: Any other information you want to include with the schema, not used by pydantic-core
2283 serialization: Custom serialization schema
2284 """
2285 s = dict_not_none(
2286 type='default',
2287 schema=schema,
2288 default_factory=default_factory,
2289 on_error=on_error,
2290 validate_default=validate_default,
2291 strict=strict,
2292 ref=ref,
2293 metadata=metadata,
2294 serialization=serialization,
2295 )
2296 if default is not Omitted:
2297 s['default'] = default
2298 return s
2301class NullableSchema(TypedDict, total=False):
2302 type: Required[Literal['nullable']]
2303 schema: Required[CoreSchema]
2304 strict: bool
2305 ref: str
2306 metadata: Any
2307 serialization: SerSchema
2310def nullable_schema(
2311 schema: CoreSchema,
2312 *,
2313 strict: bool | None = None,
2314 ref: str | None = None,
2315 metadata: Any = None,
2316 serialization: SerSchema | None = None,
2317) -> NullableSchema:
2318 """
2319 Returns a schema that matches a nullable value, e.g.:
2321 ```py
2322 from pydantic_core import SchemaValidator, core_schema
2324 schema = core_schema.nullable_schema(core_schema.str_schema())
2325 v = SchemaValidator(schema)
2326 assert v.validate_python(None) is None
2327 ```
2329 Args:
2330 schema: The schema to wrap
2331 strict: Whether the underlying schema should be validated with strict mode
2332 ref: optional unique identifier of the schema, used to reference the schema in other places
2333 metadata: Any other information you want to include with the schema, not used by pydantic-core
2334 serialization: Custom serialization schema
2335 """
2336 return dict_not_none(
2337 type='nullable', schema=schema, strict=strict, ref=ref, metadata=metadata, serialization=serialization
2338 )
2341class UnionSchema(TypedDict, total=False):
2342 type: Required[Literal['union']]
2343 choices: Required[List[CoreSchema]]
2344 # default true, whether to automatically collapse unions with one element to the inner validator
2345 auto_collapse: bool
2346 custom_error_type: str
2347 custom_error_message: str
2348 custom_error_context: Dict[str, Union[str, int, float]]
2349 strict: bool
2350 ref: str
2351 metadata: Any
2352 serialization: SerSchema
2355def union_schema(
2356 choices: list[CoreSchema],
2357 *,
2358 auto_collapse: bool | None = None,
2359 custom_error_type: str | None = None,
2360 custom_error_message: str | None = None,
2361 custom_error_context: dict[str, str | int] | None = None,
2362 strict: bool | None = None,
2363 ref: str | None = None,
2364 metadata: Any = None,
2365 serialization: SerSchema | None = None,
2366) -> UnionSchema:
2367 """
2368 Returns a schema that matches a union value, e.g.:
2370 ```py
2371 from pydantic_core import SchemaValidator, core_schema
2373 schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()])
2374 v = SchemaValidator(schema)
2375 assert v.validate_python('hello') == 'hello'
2376 assert v.validate_python(1) == 1
2377 ```
2379 Args:
2380 choices: The schemas to match
2381 auto_collapse: whether to automatically collapse unions with one element to the inner validator, default true
2382 custom_error_type: The custom error type to use if the validation fails
2383 custom_error_message: The custom error message to use if the validation fails
2384 custom_error_context: The custom error context to use if the validation fails
2385 strict: Whether the underlying schemas should be validated with strict mode
2386 ref: optional unique identifier of the schema, used to reference the schema in other places
2387 metadata: Any other information you want to include with the schema, not used by pydantic-core
2388 serialization: Custom serialization schema
2389 """
2390 return dict_not_none(
2391 type='union',
2392 choices=choices,
2393 auto_collapse=auto_collapse,
2394 custom_error_type=custom_error_type,
2395 custom_error_message=custom_error_message,
2396 custom_error_context=custom_error_context,
2397 strict=strict,
2398 ref=ref,
2399 metadata=metadata,
2400 serialization=serialization,
2401 )
2404class TaggedUnionSchema(TypedDict, total=False):
2405 type: Required[Literal['tagged-union']]
2406 choices: Required[Dict[Union[str, int], Union[str, int, CoreSchema]]]
2407 discriminator: Required[
2408 Union[str, List[Union[str, int]], List[List[Union[str, int]]], Callable[[Any], Optional[Union[str, int]]]]
2409 ]
2410 custom_error_type: str
2411 custom_error_message: str
2412 custom_error_context: Dict[str, Union[str, int, float]]
2413 strict: bool
2414 from_attributes: bool # default: True
2415 ref: str
2416 metadata: Any
2417 serialization: SerSchema
2420def tagged_union_schema(
2421 choices: Dict[Union[int, str], int | str | CoreSchema],
2422 discriminator: str | list[str | int] | list[list[str | int]] | Callable[[Any], str | int | None],
2423 *,
2424 custom_error_type: str | None = None,
2425 custom_error_message: str | None = None,
2426 custom_error_context: dict[str, int | str | float] | None = None,
2427 strict: bool | None = None,
2428 from_attributes: bool | None = None,
2429 ref: str | None = None,
2430 metadata: Any = None,
2431 serialization: SerSchema | None = None,
2432) -> TaggedUnionSchema:
2433 """
2434 Returns a schema that matches a tagged union value, e.g.:
2436 ```py
2437 from pydantic_core import SchemaValidator, core_schema
2439 apple_schema = core_schema.typed_dict_schema(
2440 {
2441 'foo': core_schema.typed_dict_field(core_schema.str_schema()),
2442 'bar': core_schema.typed_dict_field(core_schema.int_schema()),
2443 }
2444 )
2445 banana_schema = core_schema.typed_dict_schema(
2446 {
2447 'foo': core_schema.typed_dict_field(core_schema.str_schema()),
2448 'spam': core_schema.typed_dict_field(
2449 core_schema.list_schema(items_schema=core_schema.int_schema())
2450 ),
2451 }
2452 )
2453 schema = core_schema.tagged_union_schema(
2454 choices={
2455 'apple': apple_schema,
2456 'banana': banana_schema,
2457 },
2458 discriminator='foo',
2459 )
2460 v = SchemaValidator(schema)
2461 assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123}
2462 assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == {
2463 'foo': 'banana',
2464 'spam': [1, 2, 3],
2465 }
2466 ```
2468 Args:
2469 choices: The schemas to match
2470 When retrieving a schema from `choices` using the discriminator value, if the value is a str,
2471 it should be fed back into the `choices` map until a schema is obtained
2472 (This approach is to prevent multiple ownership of a single schema in Rust)
2473 discriminator: The discriminator to use to determine the schema to use
2474 * If `discriminator` is a str, it is the name of the attribute to use as the discriminator
2475 * If `discriminator` is a list of int/str, it should be used as a "path" to access the discriminator
2476 * If `discriminator` is a list of lists, each inner list is a path, and the first path that exists is used
2477 * If `discriminator` is a callable, it should return the discriminator when called on the value to validate;
2478 the callable can return `None` to indicate that there is no matching discriminator present on the input
2479 custom_error_type: The custom error type to use if the validation fails
2480 custom_error_message: The custom error message to use if the validation fails
2481 custom_error_context: The custom error context to use if the validation fails
2482 strict: Whether the underlying schemas should be validated with strict mode
2483 from_attributes: Whether to use the attributes of the object to retrieve the discriminator value
2484 ref: optional unique identifier of the schema, used to reference the schema in other places
2485 metadata: Any other information you want to include with the schema, not used by pydantic-core
2486 serialization: Custom serialization schema
2487 """
2488 return dict_not_none(
2489 type='tagged-union',
2490 choices=choices,
2491 discriminator=discriminator,
2492 custom_error_type=custom_error_type,
2493 custom_error_message=custom_error_message,
2494 custom_error_context=custom_error_context,
2495 strict=strict,
2496 from_attributes=from_attributes,
2497 ref=ref,
2498 metadata=metadata,
2499 serialization=serialization,
2500 )
2503class ChainSchema(TypedDict, total=False):
2504 type: Required[Literal['chain']]
2505 steps: Required[List[CoreSchema]]
2506 ref: str
2507 metadata: Any
2508 serialization: SerSchema
2511def chain_schema(
2512 steps: list[CoreSchema], *, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None
2513) -> ChainSchema:
2514 """
2515 Returns a schema that chains the provided validation schemas, e.g.:
2517 ```py
2518 from pydantic_core import SchemaValidator, core_schema
2520 def fn(v: str, info: core_schema.ValidationInfo) -> str:
2521 assert 'hello' in v
2522 return v + ' world'
2524 fn_schema = core_schema.general_plain_validator_function(function=fn)
2525 schema = core_schema.chain_schema(
2526 [fn_schema, fn_schema, fn_schema, core_schema.str_schema()]
2527 )
2528 v = SchemaValidator(schema)
2529 assert v.validate_python('hello') == 'hello world world world'
2530 ```
2532 Args:
2533 steps: The schemas to chain
2534 ref: optional unique identifier of the schema, used to reference the schema in other places
2535 metadata: Any other information you want to include with the schema, not used by pydantic-core
2536 serialization: Custom serialization schema
2537 """
2538 return dict_not_none(type='chain', steps=steps, ref=ref, metadata=metadata, serialization=serialization)
2541class LaxOrStrictSchema(TypedDict, total=False):
2542 type: Required[Literal['lax-or-strict']]
2543 lax_schema: Required[CoreSchema]
2544 strict_schema: Required[CoreSchema]
2545 strict: bool
2546 ref: str
2547 metadata: Any
2548 serialization: SerSchema
2551def lax_or_strict_schema(
2552 lax_schema: CoreSchema,
2553 strict_schema: CoreSchema,
2554 *,
2555 strict: bool | None = None,
2556 ref: str | None = None,
2557 metadata: Any = None,
2558 serialization: SerSchema | None = None,
2559) -> LaxOrStrictSchema:
2560 """
2561 Returns a schema that uses the lax or strict schema, e.g.:
2563 ```py
2564 from pydantic_core import SchemaValidator, core_schema
2566 def fn(v: str, info: core_schema.ValidationInfo) -> str:
2567 assert 'hello' in v
2568 return v + ' world'
2570 lax_schema = core_schema.int_schema(strict=False)
2571 strict_schema = core_schema.int_schema(strict=True)
2573 schema = core_schema.lax_or_strict_schema(
2574 lax_schema=lax_schema, strict_schema=strict_schema, strict=True
2575 )
2576 v = SchemaValidator(schema)
2577 assert v.validate_python(123) == 123
2579 schema = core_schema.lax_or_strict_schema(
2580 lax_schema=lax_schema, strict_schema=strict_schema, strict=False
2581 )
2582 v = SchemaValidator(schema)
2583 assert v.validate_python('123') == 123
2584 ```
2586 Args:
2587 lax_schema: The lax schema to use
2588 strict_schema: The strict schema to use
2589 strict: Whether the strict schema should be used
2590 ref: optional unique identifier of the schema, used to reference the schema in other places
2591 metadata: Any other information you want to include with the schema, not used by pydantic-core
2592 serialization: Custom serialization schema
2593 """
2594 return dict_not_none(
2595 type='lax-or-strict',
2596 lax_schema=lax_schema,
2597 strict_schema=strict_schema,
2598 strict=strict,
2599 ref=ref,
2600 metadata=metadata,
2601 serialization=serialization,
2602 )
2605class TypedDictField(TypedDict, total=False):
2606 type: Required[Literal['typed-dict-field']]
2607 schema: Required[CoreSchema]
2608 required: bool
2609 validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]]
2610 serialization_alias: str
2611 serialization_exclude: bool # default: False
2612 frozen: bool
2613 metadata: Any
2616def typed_dict_field(
2617 schema: CoreSchema,
2618 *,
2619 required: bool | None = None,
2620 validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
2621 serialization_alias: str | None = None,
2622 serialization_exclude: bool | None = None,
2623 frozen: bool | None = None,
2624 metadata: Any = None,
2625) -> TypedDictField:
2626 """
2627 Returns a schema that matches a typed dict field, e.g.:
2629 ```py
2630 from pydantic_core import core_schema
2632 field = core_schema.typed_dict_field(schema=core_schema.int_schema(), required=True)
2633 ```
2635 Args:
2636 schema: The schema to use for the field
2637 required: Whether the field is required
2638 validation_alias: The alias(es) to use to find the field in the validation data
2639 serialization_alias: The alias to use as a key when serializing
2640 serialization_exclude: Whether to exclude the field when serializing
2641 frozen: Whether the field is frozen
2642 metadata: Any other information you want to include with the schema, not used by pydantic-core
2643 """
2644 return dict_not_none(
2645 type='typed-dict-field',
2646 schema=schema,
2647 required=required,
2648 validation_alias=validation_alias,
2649 serialization_alias=serialization_alias,
2650 serialization_exclude=serialization_exclude,
2651 frozen=frozen,
2652 metadata=metadata,
2653 )
2656class TypedDictSchema(TypedDict, total=False):
2657 type: Required[Literal['typed-dict']]
2658 fields: Required[Dict[str, TypedDictField]]
2659 computed_fields: List[ComputedField]
2660 strict: bool
2661 extra_validator: CoreSchema
2662 return_fields_set: bool
2663 # all these values can be set via config, equivalent fields have `typed_dict_` prefix
2664 extra_behavior: ExtraBehavior
2665 total: bool # default: True
2666 populate_by_name: bool # replaces `allow_population_by_field_name` in pydantic v1
2667 from_attributes: bool
2668 ref: str
2669 metadata: Any
2670 serialization: SerSchema
2673def typed_dict_schema(
2674 fields: Dict[str, TypedDictField],
2675 *,
2676 computed_fields: list[ComputedField] | None = None,
2677 strict: bool | None = None,
2678 extra_validator: CoreSchema | None = None,
2679 return_fields_set: bool | None = None,
2680 extra_behavior: ExtraBehavior | None = None,
2681 total: bool | None = None,
2682 populate_by_name: bool | None = None,
2683 from_attributes: bool | None = None,
2684 ref: str | None = None,
2685 metadata: Any = None,
2686 serialization: SerSchema | None = None,
2687) -> TypedDictSchema:
2688 """
2689 Returns a schema that matches a typed dict, e.g.:
2691 ```py
2692 from pydantic_core import SchemaValidator, core_schema
2694 wrapper_schema = core_schema.typed_dict_schema(
2695 {'a': core_schema.typed_dict_field(core_schema.str_schema())}
2696 )
2697 v = SchemaValidator(wrapper_schema)
2698 assert v.validate_python({'a': 'hello'}) == {'a': 'hello'}
2699 ```
2701 Args:
2702 fields: The fields to use for the typed dict
2703 computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model
2704 strict: Whether the typed dict is strict
2705 extra_validator: The extra validator to use for the typed dict
2706 return_fields_set: Whether the typed dict should return a fields set
2707 ref: optional unique identifier of the schema, used to reference the schema in other places
2708 metadata: Any other information you want to include with the schema, not used by pydantic-core
2709 extra_behavior: The extra behavior to use for the typed dict
2710 total: Whether the typed dict is total
2711 populate_by_name: Whether the typed dict should populate by name
2712 from_attributes: Whether the typed dict should be populated from attributes
2713 serialization: Custom serialization schema
2714 """
2715 return dict_not_none(
2716 type='typed-dict',
2717 fields=fields,
2718 computed_fields=computed_fields,
2719 strict=strict,
2720 extra_validator=extra_validator,
2721 return_fields_set=return_fields_set,
2722 extra_behavior=extra_behavior,
2723 total=total,
2724 populate_by_name=populate_by_name,
2725 from_attributes=from_attributes,
2726 ref=ref,
2727 metadata=metadata,
2728 serialization=serialization,
2729 )
2732class ModelSchema(TypedDict, total=False):
2733 type: Required[Literal['model']]
2734 cls: Required[Type[Any]]
2735 schema: Required[CoreSchema]
2736 post_init: str
2737 revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never'
2738 strict: bool
2739 frozen: bool
2740 config: CoreConfig
2741 ref: str
2742 metadata: Any
2743 serialization: SerSchema
2746def model_schema(
2747 cls: Type[Any],
2748 schema: CoreSchema,
2749 *,
2750 post_init: str | None = None,
2751 revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
2752 strict: bool | None = None,
2753 frozen: bool | None = None,
2754 config: CoreConfig | None = None,
2755 ref: str | None = None,
2756 metadata: Any = None,
2757 serialization: SerSchema | None = None,
2758) -> ModelSchema:
2759 """
2760 A model schema generally contains a typed-dict schema.
2761 It will run the typed dict validator, then create a new class
2762 and set the dict and fields set returned from the typed dict validator
2763 to `__dict__` and `__pydantic_fields_set__` respectively.
2765 Example:
2767 ```py
2768 from pydantic_core import CoreConfig, SchemaValidator, core_schema
2770 class MyModel:
2771 __slots__ = '__dict__', '__pydantic_fields_set__'
2773 schema = core_schema.model_schema(
2774 cls=MyModel,
2775 config=CoreConfig(str_max_length=5),
2776 schema=core_schema.typed_dict_schema(
2777 fields={'a': core_schema.typed_dict_field(core_schema.str_schema())},
2778 ),
2779 )
2780 v = SchemaValidator(schema)
2781 assert v.isinstance_python({'a': 'hello'}) is True
2782 assert v.isinstance_python({'a': 'too long'}) is False
2783 ```
2785 Args:
2786 cls: The class to use for the model
2787 schema: The schema to use for the model
2788 post_init: The call after init to use for the model
2789 revalidate_instances: whether instances of models and dataclasses (including subclass instances)
2790 should re-validate defaults to config.revalidate_instances, else 'never'
2791 strict: Whether the model is strict
2792 frozen: Whether the model is frozen
2793 config: The config to use for the model
2794 ref: optional unique identifier of the schema, used to reference the schema in other places
2795 metadata: Any other information you want to include with the schema, not used by pydantic-core
2796 serialization: Custom serialization schema
2797 """
2798 return dict_not_none(
2799 type='model',
2800 cls=cls,
2801 schema=schema,
2802 post_init=post_init,
2803 revalidate_instances=revalidate_instances,
2804 strict=strict,
2805 frozen=frozen,
2806 config=config,
2807 ref=ref,
2808 metadata=metadata,
2809 serialization=serialization,
2810 )
2813class DataclassField(TypedDict, total=False):
2814 type: Required[Literal['dataclass-field']]
2815 name: Required[str]
2816 schema: Required[CoreSchema]
2817 kw_only: bool # default: True
2818 init_only: bool # default: False
2819 frozen: bool # default: False
2820 validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]]
2821 serialization_alias: str
2822 serialization_exclude: bool # default: False
2823 metadata: Any
2826def dataclass_field(
2827 name: str,
2828 schema: CoreSchema,
2829 *,
2830 kw_only: bool | None = None,
2831 init_only: bool | None = None,
2832 validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
2833 serialization_alias: str | None = None,
2834 serialization_exclude: bool | None = None,
2835 metadata: Any = None,
2836 frozen: bool | None = None,
2837) -> DataclassField:
2838 """
2839 Returns a schema for a dataclass field, e.g.:
2841 ```py
2842 from pydantic_core import SchemaValidator, core_schema
2844 field = core_schema.dataclass_field(
2845 name='a', schema=core_schema.str_schema(), kw_only=False
2846 )
2847 schema = core_schema.dataclass_args_schema('Foobar', [field])
2848 v = SchemaValidator(schema)
2849 assert v.validate_python({'a': 'hello'}) == ({'a': 'hello'}, None)
2850 ```
2852 Args:
2853 name: The name to use for the argument parameter
2854 schema: The schema to use for the argument parameter
2855 kw_only: Whether the field can be set with a positional argument as well as a keyword argument
2856 init_only: Whether the field should be omitted from `__dict__` and passed to `__post_init__`
2857 validation_alias: The alias(es) to use to find the field in the validation data
2858 serialization_alias: The alias to use as a key when serializing
2859 serialization_exclude: Whether to exclude the field when serializing
2860 metadata: Any other information you want to include with the schema, not used by pydantic-core
2861 frozen: Whether the field is frozen
2862 """
2863 return dict_not_none(
2864 type='dataclass-field',
2865 name=name,
2866 schema=schema,
2867 kw_only=kw_only,
2868 init_only=init_only,
2869 validation_alias=validation_alias,
2870 serialization_alias=serialization_alias,
2871 serialization_exclude=serialization_exclude,
2872 metadata=metadata,
2873 frozen=frozen,
2874 )
2877class DataclassArgsSchema(TypedDict, total=False):
2878 type: Required[Literal['dataclass-args']]
2879 dataclass_name: Required[str]
2880 fields: Required[List[DataclassField]]
2881 computed_fields: List[ComputedField]
2882 populate_by_name: bool # default: False
2883 collect_init_only: bool # default: False
2884 ref: str
2885 metadata: Any
2886 serialization: SerSchema
2887 extra_behavior: ExtraBehavior
2890def dataclass_args_schema(
2891 dataclass_name: str,
2892 fields: list[DataclassField],
2893 *,
2894 computed_fields: List[ComputedField] | None = None,
2895 populate_by_name: bool | None = None,
2896 collect_init_only: bool | None = None,
2897 ref: str | None = None,
2898 metadata: Any = None,
2899 serialization: SerSchema | None = None,
2900 extra_behavior: ExtraBehavior | None = None,
2901) -> DataclassArgsSchema:
2902 """
2903 Returns a schema for validating dataclass arguments, e.g.:
2905 ```py
2906 from pydantic_core import SchemaValidator, core_schema
2908 field_a = core_schema.dataclass_field(
2909 name='a', schema=core_schema.str_schema(), kw_only=False
2910 )
2911 field_b = core_schema.dataclass_field(
2912 name='b', schema=core_schema.bool_schema(), kw_only=False
2913 )
2914 schema = core_schema.dataclass_args_schema('Foobar', [field_a, field_b])
2915 v = SchemaValidator(schema)
2916 assert v.validate_python({'a': 'hello', 'b': True}) == ({'a': 'hello', 'b': True}, None)
2917 ```
2919 Args:
2920 dataclass_name: The name of the dataclass being validated
2921 fields: The fields to use for the dataclass
2922 computed_fields: Computed fields to use when serializing the dataclass
2923 populate_by_name: Whether to populate by name
2924 collect_init_only: Whether to collect init only fields into a dict to pass to `__post_init__`
2925 ref: optional unique identifier of the schema, used to reference the schema in other places
2926 metadata: Any other information you want to include with the schema, not used by pydantic-core
2927 serialization: Custom serialization schema
2928 extra_behavior: How to handle extra fields
2929 """
2930 return dict_not_none(
2931 type='dataclass-args',
2932 dataclass_name=dataclass_name,
2933 fields=fields,
2934 computed_fields=computed_fields,
2935 populate_by_name=populate_by_name,
2936 collect_init_only=collect_init_only,
2937 ref=ref,
2938 metadata=metadata,
2939 serialization=serialization,
2940 extra_behavior=extra_behavior,
2941 )
2944class DataclassSchema(TypedDict, total=False):
2945 type: Required[Literal['dataclass']]
2946 cls: Required[Type[Any]]
2947 schema: Required[CoreSchema]
2948 post_init: bool # default: False
2949 revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never'
2950 strict: bool # default: False
2951 frozen: bool # default False
2952 ref: str
2953 metadata: Any
2954 serialization: SerSchema
2957def dataclass_schema(
2958 cls: Type[Any],
2959 schema: CoreSchema,
2960 *,
2961 post_init: bool | None = None,
2962 revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
2963 strict: bool | None = None,
2964 ref: str | None = None,
2965 metadata: Any = None,
2966 serialization: SerSchema | None = None,
2967 frozen: bool | None = None,
2968) -> DataclassSchema:
2969 """
2970 Returns a schema for a dataclass. As with `ModelSchema`, this schema can only be used as a field within
2971 another schema, not as the root type.
2973 Args:
2974 cls: The dataclass type, used to to perform subclass checks
2975 schema: The schema to use for the dataclass fields
2976 post_init: Whether to call `__post_init__` after validation
2977 revalidate_instances: whether instances of models and dataclasses (including subclass instances)
2978 should re-validate defaults to config.revalidate_instances, else 'never'
2979 strict: Whether to require an exact instance of `cls`
2980 ref: optional unique identifier of the schema, used to reference the schema in other places
2981 metadata: Any other information you want to include with the schema, not used by pydantic-core
2982 serialization: Custom serialization schema
2983 frozen: Whether the dataclass is frozen
2984 """
2985 return dict_not_none(
2986 type='dataclass',
2987 cls=cls,
2988 schema=schema,
2989 post_init=post_init,
2990 revalidate_instances=revalidate_instances,
2991 strict=strict,
2992 ref=ref,
2993 metadata=metadata,
2994 serialization=serialization,
2995 frozen=frozen,
2996 )
2999class ArgumentsParameter(TypedDict, total=False):
3000 name: Required[str]
3001 schema: Required[CoreSchema]
3002 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] # default positional_or_keyword
3003 alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]]
3006def arguments_parameter(
3007 name: str,
3008 schema: CoreSchema,
3009 *,
3010 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None,
3011 alias: str | list[str | int] | list[list[str | int]] | None = None,
3012) -> ArgumentsParameter:
3013 """
3014 Returns a schema that matches an argument parameter, e.g.:
3016 ```py
3017 from pydantic_core import SchemaValidator, core_schema
3019 param = core_schema.arguments_parameter(
3020 name='a', schema=core_schema.str_schema(), mode='positional_only'
3021 )
3022 schema = core_schema.arguments_schema([param])
3023 v = SchemaValidator(schema)
3024 assert v.validate_python(('hello',)) == (('hello',), {})
3025 ```
3027 Args:
3028 name: The name to use for the argument parameter
3029 schema: The schema to use for the argument parameter
3030 mode: The mode to use for the argument parameter
3031 alias: The alias to use for the argument parameter
3032 """
3033 return dict_not_none(name=name, schema=schema, mode=mode, alias=alias)
3036class ArgumentsSchema(TypedDict, total=False):
3037 type: Required[Literal['arguments']]
3038 arguments_schema: Required[List[ArgumentsParameter]]
3039 populate_by_name: bool
3040 var_args_schema: CoreSchema
3041 var_kwargs_schema: CoreSchema
3042 ref: str
3043 metadata: Any
3044 serialization: SerSchema
3047def arguments_schema(
3048 arguments: list[ArgumentsParameter],
3049 *,
3050 populate_by_name: bool | None = None,
3051 var_args_schema: CoreSchema | None = None,
3052 var_kwargs_schema: CoreSchema | None = None,
3053 ref: str | None = None,
3054 metadata: Any = None,
3055 serialization: SerSchema | None = None,
3056) -> ArgumentsSchema:
3057 """
3058 Returns a schema that matches an arguments schema, e.g.:
3060 ```py
3061 from pydantic_core import SchemaValidator, core_schema
3063 param_a = core_schema.arguments_parameter(
3064 name='a', schema=core_schema.str_schema(), mode='positional_only'
3065 )
3066 param_b = core_schema.arguments_parameter(
3067 name='b', schema=core_schema.bool_schema(), mode='positional_only'
3068 )
3069 schema = core_schema.arguments_schema([param_a, param_b])
3070 v = SchemaValidator(schema)
3071 assert v.validate_python(('hello', True)) == (('hello', True), {})
3072 ```
3074 Args:
3075 arguments: The arguments to use for the arguments schema
3076 populate_by_name: Whether to populate by name
3077 var_args_schema: The variable args schema to use for the arguments schema
3078 var_kwargs_schema: The variable kwargs schema to use for the arguments schema
3079 ref: optional unique identifier of the schema, used to reference the schema in other places
3080 metadata: Any other information you want to include with the schema, not used by pydantic-core
3081 serialization: Custom serialization schema
3082 """
3083 return dict_not_none(
3084 type='arguments',
3085 arguments_schema=arguments,
3086 populate_by_name=populate_by_name,
3087 var_args_schema=var_args_schema,
3088 var_kwargs_schema=var_kwargs_schema,
3089 ref=ref,
3090 metadata=metadata,
3091 serialization=serialization,
3092 )
3095class CallSchema(TypedDict, total=False):
3096 type: Required[Literal['call']]
3097 arguments_schema: Required[CoreSchema]
3098 function: Required[Callable[..., Any]]
3099 function_name: str # default function.__name__
3100 return_schema: CoreSchema
3101 ref: str
3102 metadata: Any
3103 serialization: SerSchema
3106def call_schema(
3107 arguments: CoreSchema,
3108 function: Callable[..., Any],
3109 *,
3110 function_name: str | None = None,
3111 return_schema: CoreSchema | None = None,
3112 ref: str | None = None,
3113 metadata: Any = None,
3114 serialization: SerSchema | None = None,
3115) -> CallSchema:
3116 """
3117 Returns a schema that matches an arguments schema, then calls a function, e.g.:
3119 ```py
3120 from pydantic_core import SchemaValidator, core_schema
3122 param_a = core_schema.arguments_parameter(
3123 name='a', schema=core_schema.str_schema(), mode='positional_only'
3124 )
3125 param_b = core_schema.arguments_parameter(
3126 name='b', schema=core_schema.bool_schema(), mode='positional_only'
3127 )
3128 args_schema = core_schema.arguments_schema([param_a, param_b])
3130 schema = core_schema.call_schema(
3131 arguments=args_schema,
3132 function=lambda a, b: a + str(not b),
3133 return_schema=core_schema.str_schema(),
3134 )
3135 v = SchemaValidator(schema)
3136 assert v.validate_python((('hello', True))) == 'helloFalse'
3137 ```
3139 Args:
3140 arguments: The arguments to use for the arguments schema
3141 function: The function to use for the call schema
3142 function_name: The function name to use for the call schema, if not provided `function.__name__` is used
3143 return_schema: The return schema to use for the call schema
3144 ref: optional unique identifier of the schema, used to reference the schema in other places
3145 metadata: Any other information you want to include with the schema, not used by pydantic-core
3146 serialization: Custom serialization schema
3147 """
3148 return dict_not_none(
3149 type='call',
3150 arguments_schema=arguments,
3151 function=function,
3152 function_name=function_name,
3153 return_schema=return_schema,
3154 ref=ref,
3155 metadata=metadata,
3156 serialization=serialization,
3157 )
3160class CustomErrorSchema(TypedDict, total=False):
3161 type: Required[Literal['custom-error']]
3162 schema: Required[CoreSchema]
3163 custom_error_type: Required[str]
3164 custom_error_message: str
3165 custom_error_context: Dict[str, Union[str, int, float]]
3166 ref: str
3167 metadata: Any
3168 serialization: SerSchema
3171def custom_error_schema(
3172 schema: CoreSchema,
3173 custom_error_type: str,
3174 *,
3175 custom_error_message: str | None = None,
3176 custom_error_context: dict[str, str | int | float] | None = None,
3177 ref: str | None = None,
3178 metadata: Any = None,
3179 serialization: SerSchema | None = None,
3180) -> CustomErrorSchema:
3181 """
3182 Returns a schema that matches a custom error value, e.g.:
3184 ```py
3185 from pydantic_core import SchemaValidator, core_schema
3187 schema = core_schema.custom_error_schema(
3188 schema=core_schema.int_schema(),
3189 custom_error_type='MyError',
3190 custom_error_message='Error msg',
3191 )
3192 v = SchemaValidator(schema)
3193 v.validate_python(1)
3194 ```
3196 Args:
3197 schema: The schema to use for the custom error schema
3198 custom_error_type: The custom error type to use for the custom error schema
3199 custom_error_message: The custom error message to use for the custom error schema
3200 custom_error_context: The custom error context to use for the custom error schema
3201 ref: optional unique identifier of the schema, used to reference the schema in other places
3202 metadata: Any other information you want to include with the schema, not used by pydantic-core
3203 serialization: Custom serialization schema
3204 """
3205 return dict_not_none(
3206 type='custom-error',
3207 schema=schema,
3208 custom_error_type=custom_error_type,
3209 custom_error_message=custom_error_message,
3210 custom_error_context=custom_error_context,
3211 ref=ref,
3212 metadata=metadata,
3213 serialization=serialization,
3214 )
3217class JsonSchema(TypedDict, total=False):
3218 type: Required[Literal['json']]
3219 schema: CoreSchema
3220 ref: str
3221 metadata: Any
3222 serialization: SerSchema
3225def json_schema(
3226 schema: CoreSchema | None = None,
3227 *,
3228 ref: str | None = None,
3229 metadata: Any = None,
3230 serialization: SerSchema | None = None,
3231) -> JsonSchema:
3232 """
3233 Returns a schema that matches a JSON value, e.g.:
3235 ```py
3236 from pydantic_core import SchemaValidator, core_schema
3238 dict_schema = core_schema.typed_dict_schema(
3239 {
3240 'field_a': core_schema.typed_dict_field(core_schema.str_schema()),
3241 'field_b': core_schema.typed_dict_field(core_schema.bool_schema()),
3242 }
3243 )
3245 class MyModel:
3246 __slots__ = '__dict__', '__pydantic_fields_set__'
3247 field_a: str
3248 field_b: bool
3250 json_schema = core_schema.json_schema(schema=dict_schema)
3251 schema = core_schema.model_schema(cls=MyModel, schema=json_schema)
3252 v = SchemaValidator(schema)
3253 m = v.validate_python('{"field_a": "hello", "field_b": true}')
3254 assert isinstance(m, MyModel)
3255 ```
3257 Args:
3258 schema: The schema to use for the JSON schema
3259 ref: optional unique identifier of the schema, used to reference the schema in other places
3260 metadata: Any other information you want to include with the schema, not used by pydantic-core
3261 serialization: Custom serialization schema
3262 """
3263 return dict_not_none(type='json', schema=schema, ref=ref, metadata=metadata, serialization=serialization)
3266class UrlSchema(TypedDict, total=False):
3267 type: Required[Literal['url']]
3268 max_length: int
3269 allowed_schemes: List[str]
3270 host_required: bool # default False
3271 default_host: str
3272 default_port: int
3273 default_path: str
3274 strict: bool
3275 ref: str
3276 metadata: Any
3277 serialization: SerSchema
3280def url_schema(
3281 *,
3282 max_length: int | None = None,
3283 allowed_schemes: list[str] | None = None,
3284 host_required: bool | None = None,
3285 default_host: str | None = None,
3286 default_port: int | None = None,
3287 default_path: str | None = None,
3288 strict: bool | None = None,
3289 ref: str | None = None,
3290 metadata: Any = None,
3291 serialization: SerSchema | None = None,
3292) -> UrlSchema:
3293 """
3294 Returns a schema that matches a URL value, e.g.:
3296 ```py
3297 from pydantic_core import SchemaValidator, core_schema
3299 schema = core_schema.url_schema()
3300 v = SchemaValidator(schema)
3301 print(v.validate_python('https://example.com'))
3302 #> https://example.com/
3303 ```
3305 Args:
3306 max_length: The maximum length of the URL
3307 allowed_schemes: The allowed URL schemes
3308 host_required: Whether the URL must have a host
3309 default_host: The default host to use if the URL does not have a host
3310 default_port: The default port to use if the URL does not have a port
3311 default_path: The default path to use if the URL does not have a path
3312 strict: Whether to use strict URL parsing
3313 ref: optional unique identifier of the schema, used to reference the schema in other places
3314 metadata: Any other information you want to include with the schema, not used by pydantic-core
3315 serialization: Custom serialization schema
3316 """
3317 return dict_not_none(
3318 type='url',
3319 max_length=max_length,
3320 allowed_schemes=allowed_schemes,
3321 host_required=host_required,
3322 default_host=default_host,
3323 default_port=default_port,
3324 default_path=default_path,
3325 strict=strict,
3326 ref=ref,
3327 metadata=metadata,
3328 serialization=serialization,
3329 )
3332class MultiHostUrlSchema(TypedDict, total=False):
3333 type: Required[Literal['multi-host-url']]
3334 max_length: int
3335 allowed_schemes: List[str]
3336 host_required: bool # default False
3337 default_host: str
3338 default_port: int
3339 default_path: str
3340 strict: bool
3341 ref: str
3342 metadata: Any
3343 serialization: SerSchema
3346def multi_host_url_schema(
3347 *,
3348 max_length: int | None = None,
3349 allowed_schemes: list[str] | None = None,
3350 host_required: bool | None = None,
3351 default_host: str | None = None,
3352 default_port: int | None = None,
3353 default_path: str | None = None,
3354 strict: bool | None = None,
3355 ref: str | None = None,
3356 metadata: Any = None,
3357 serialization: SerSchema | None = None,
3358) -> MultiHostUrlSchema:
3359 """
3360 Returns a schema that matches a URL value with possibly multiple hosts, e.g.:
3362 ```py
3363 from pydantic_core import SchemaValidator, core_schema
3365 schema = core_schema.multi_host_url_schema()
3366 v = SchemaValidator(schema)
3367 print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1'))
3368 #> redis://localhost,0.0.0.0,127.0.0.1
3369 ```
3371 Args:
3372 max_length: The maximum length of the URL
3373 allowed_schemes: The allowed URL schemes
3374 host_required: Whether the URL must have a host
3375 default_host: The default host to use if the URL does not have a host
3376 default_port: The default port to use if the URL does not have a port
3377 default_path: The default path to use if the URL does not have a path
3378 strict: Whether to use strict URL parsing
3379 ref: optional unique identifier of the schema, used to reference the schema in other places
3380 metadata: Any other information you want to include with the schema, not used by pydantic-core
3381 serialization: Custom serialization schema
3382 """
3383 return dict_not_none(
3384 type='multi-host-url',
3385 max_length=max_length,
3386 allowed_schemes=allowed_schemes,
3387 host_required=host_required,
3388 default_host=default_host,
3389 default_port=default_port,
3390 default_path=default_path,
3391 strict=strict,
3392 ref=ref,
3393 metadata=metadata,
3394 serialization=serialization,
3395 )
3398class DefinitionsSchema(TypedDict, total=False):
3399 type: Required[Literal['definitions']]
3400 schema: Required[CoreSchema]
3401 definitions: Required[List[CoreSchema]]
3402 metadata: Any
3403 serialization: SerSchema
3406def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema:
3407 """
3408 Build a schema that contains both an inner schema and a list of definitions which can be used
3409 within the inner schema.
3411 ```py
3412 from pydantic_core import SchemaValidator, core_schema
3414 schema = core_schema.definitions_schema(
3415 core_schema.list_schema(core_schema.definition_reference_schema('foobar')),
3416 [core_schema.int_schema(ref='foobar')],
3417 )
3418 v = SchemaValidator(schema)
3419 assert v.validate_python([1, 2, '3']) == [1, 2, 3]
3420 ```
3422 Args:
3423 schema: The inner schema
3424 definitions: List of definitions which can be referenced within inner schema
3425 """
3426 return DefinitionsSchema(type='definitions', schema=schema, definitions=definitions)
3429class DefinitionReferenceSchema(TypedDict, total=False):
3430 type: Required[Literal['definition-ref']]
3431 schema_ref: Required[str]
3432 metadata: Any
3433 serialization: SerSchema
3436def definition_reference_schema(
3437 schema_ref: str, metadata: Any = None, serialization: SerSchema | None = None
3438) -> DefinitionReferenceSchema:
3439 """
3440 Returns a schema that points to a schema stored in "definitions", this is useful for nested recursive
3441 models and also when you want to define validators separately from the main schema, e.g.:
3443 ```py
3444 from pydantic_core import SchemaValidator, core_schema
3446 schema_definition = core_schema.definition_reference_schema('list-schema')
3447 schema = core_schema.list_schema(items_schema=schema_definition, ref='list-schema')
3448 v = SchemaValidator(schema)
3449 assert v.validate_python([[]]) == [[]]
3450 ```
3452 Args:
3453 schema_ref: The schema ref to use for the definition reference schema
3454 metadata: Any other information you want to include with the schema, not used by pydantic-core
3455 serialization: Custom serialization schema
3456 """
3457 return dict_not_none(type='definition-ref', schema_ref=schema_ref, metadata=metadata, serialization=serialization)
3460MYPY = False
3461# See https://github.com/python/mypy/issues/14034 for details, in summary mypy is extremely slow to process this
3462# union which kills performance not just for pydantic, but even for code using pydantic
3463if not MYPY:
3464 CoreSchema = Union[
3465 AnySchema,
3466 NoneSchema,
3467 BoolSchema,
3468 IntSchema,
3469 FloatSchema,
3470 StringSchema,
3471 BytesSchema,
3472 DateSchema,
3473 TimeSchema,
3474 DatetimeSchema,
3475 TimedeltaSchema,
3476 LiteralSchema,
3477 IsInstanceSchema,
3478 IsSubclassSchema,
3479 CallableSchema,
3480 ListSchema,
3481 TuplePositionalSchema,
3482 TupleVariableSchema,
3483 SetSchema,
3484 FrozenSetSchema,
3485 GeneratorSchema,
3486 DictSchema,
3487 AfterValidatorFunctionSchema,
3488 BeforeValidatorFunctionSchema,
3489 WrapValidatorFunctionSchema,
3490 PlainValidatorFunctionSchema,
3491 WithDefaultSchema,
3492 NullableSchema,
3493 UnionSchema,
3494 TaggedUnionSchema,
3495 ChainSchema,
3496 LaxOrStrictSchema,
3497 TypedDictSchema,
3498 ModelSchema,
3499 DataclassArgsSchema,
3500 DataclassSchema,
3501 ArgumentsSchema,
3502 CallSchema,
3503 CustomErrorSchema,
3504 JsonSchema,
3505 UrlSchema,
3506 MultiHostUrlSchema,
3507 DefinitionsSchema,
3508 DefinitionReferenceSchema,
3509 ]
3510elif False:
3511 CoreSchema: TypeAlias = Mapping[str, Any]
3514# to update this, call `pytest -k test_core_schema_type_literal` and copy the output
3515CoreSchemaType = Literal[
3516 'any',
3517 'none',
3518 'bool',
3519 'int',
3520 'float',
3521 'str',
3522 'bytes',
3523 'date',
3524 'time',
3525 'datetime',
3526 'timedelta',
3527 'literal',
3528 'is-instance',
3529 'is-subclass',
3530 'callable',
3531 'list',
3532 'tuple-positional',
3533 'tuple-variable',
3534 'set',
3535 'frozenset',
3536 'generator',
3537 'dict',
3538 'function-after',
3539 'function-before',
3540 'function-wrap',
3541 'function-plain',
3542 'default',
3543 'nullable',
3544 'union',
3545 'tagged-union',
3546 'chain',
3547 'lax-or-strict',
3548 'typed-dict',
3549 'model',
3550 'dataclass-args',
3551 'dataclass',
3552 'arguments',
3553 'call',
3554 'custom-error',
3555 'json',
3556 'url',
3557 'multi-host-url',
3558 'definitions',
3559 'definition-ref',
3560]
3563# used in _pydantic_core.pyi::PydanticKnownError
3564# to update this, call `pytest -k test_all_errors` and copy the output
3565ErrorType = Literal[
3566 'no_such_attribute',
3567 'json_invalid',
3568 'json_type',
3569 'recursion_loop',
3570 'dict_attributes_type',
3571 'missing',
3572 'frozen_field',
3573 'frozen_instance',
3574 'extra_forbidden',
3575 'invalid_key',
3576 'get_attribute_error',
3577 'model_class_type',
3578 'none_required',
3579 'bool',
3580 'greater_than',
3581 'greater_than_equal',
3582 'less_than',
3583 'less_than_equal',
3584 'multiple_of',
3585 'finite_number',
3586 'too_short',
3587 'too_long',
3588 'iterable_type',
3589 'iteration_error',
3590 'string_type',
3591 'string_sub_type',
3592 'string_unicode',
3593 'string_too_short',
3594 'string_too_long',
3595 'string_pattern_mismatch',
3596 'dict_type',
3597 'mapping_type',
3598 'list_type',
3599 'tuple_type',
3600 'set_type',
3601 'bool_type',
3602 'bool_parsing',
3603 'int_type',
3604 'int_parsing',
3605 'int_from_float',
3606 'float_type',
3607 'float_parsing',
3608 'bytes_type',
3609 'bytes_too_short',
3610 'bytes_too_long',
3611 'value_error',
3612 'assertion_error',
3613 'literal_error',
3614 'date_type',
3615 'date_parsing',
3616 'date_from_datetime_parsing',
3617 'date_from_datetime_inexact',
3618 'date_past',
3619 'date_future',
3620 'time_type',
3621 'time_parsing',
3622 'datetime_type',
3623 'datetime_parsing',
3624 'datetime_object_invalid',
3625 'datetime_past',
3626 'datetime_future',
3627 'datetime_aware',
3628 'datetime_naive',
3629 'time_delta_type',
3630 'time_delta_parsing',
3631 'frozen_set_type',
3632 'is_instance_of',
3633 'is_subclass_of',
3634 'callable_type',
3635 'union_tag_invalid',
3636 'union_tag_not_found',
3637 'arguments_type',
3638 'missing_argument',
3639 'unexpected_keyword_argument',
3640 'missing_keyword_only_argument',
3641 'unexpected_positional_argument',
3642 'missing_positional_only_argument',
3643 'multiple_argument_values',
3644 'dataclass_type',
3645 'url_type',
3646 'url_parsing',
3647 'url_syntax_violation',
3648 'url_too_long',
3649 'url_scheme',
3650]