forked from pydantic/pydantic-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core_schema.py
3926 lines (3363 loc) · 130 KB
/
core_schema.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module contains definitions to build schemas which `pydantic_core` can
validate and serialize.
"""
from __future__ import annotations as _annotations
import sys
import warnings
from collections.abc import Mapping
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Callable, Dict, Hashable, List, Set, Tuple, Type, Union
from typing_extensions import deprecated
if sys.version_info < (3, 12):
from typing_extensions import TypedDict
else:
from typing import TypedDict
if sys.version_info < (3, 11):
from typing_extensions import Protocol, Required, TypeAlias
else:
from typing import Protocol, Required, TypeAlias
if sys.version_info < (3, 9):
from typing_extensions import Literal
else:
from typing import Literal
if TYPE_CHECKING:
from pydantic_core import PydanticUndefined
else:
# The initial build of pydantic_core requires PydanticUndefined to generate
# the core schema; so we need to conditionally skip it. mypy doesn't like
# this at all, hence the TYPE_CHECKING branch above.
try:
from pydantic_core import PydanticUndefined
except ImportError:
PydanticUndefined = object()
ExtraBehavior = Literal['allow', 'forbid', 'ignore']
class CoreConfig(TypedDict, total=False):
"""
Base class for schema configuration options.
Attributes:
title: The name of the configuration.
strict: Whether the configuration should strictly adhere to specified rules.
extra_fields_behavior: The behavior for handling extra fields.
typed_dict_total: Whether the TypedDict should be considered total. Default is `True`.
from_attributes: Whether to use attributes for models, dataclasses, and tagged union keys.
loc_by_alias: Whether to use the used alias (or first alias for "field required" errors) instead of
`field_names` to construct error `loc`s. Default is `True`.
revalidate_instances: Whether instances of models and dataclasses should re-validate. Default is 'never'.
validate_default: Whether to validate default values during validation. Default is `False`.
populate_by_name: Whether an aliased field may be populated by its name as given by the model attribute,
as well as the alias. (Replaces 'allow_population_by_field_name' in Pydantic v1.) Default is `False`.
str_max_length: The maximum length for string fields.
str_min_length: The minimum length for string fields.
str_strip_whitespace: Whether to strip whitespace from string fields.
str_to_lower: Whether to convert string fields to lowercase.
str_to_upper: Whether to convert string fields to uppercase.
allow_inf_nan: Whether to allow infinity and NaN values for float fields. Default is `True`.
ser_json_timedelta: The serialization option for `timedelta` values. Default is 'iso8601'.
ser_json_bytes: The serialization option for `bytes` values. Default is 'utf8'.
hide_input_in_errors: Whether to hide input data from `ValidationError` representation.
validation_error_cause: Whether to add user-python excs to the __cause__ of a ValidationError.
Requires exceptiongroup backport pre Python 3.11.
coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
regex_engine: The regex engine to use for regex pattern validation. Default is 'rust-regex'. See `StringSchema`.
"""
title: str
strict: bool
# settings related to typed dicts, model fields, dataclass fields
extra_fields_behavior: ExtraBehavior
typed_dict_total: bool # default: True
# used for models, dataclasses, and tagged union keys
from_attributes: bool
# whether to use the used alias (or first alias for "field required" errors) instead of field_names
# to construct error `loc`s, default True
loc_by_alias: bool
# whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
revalidate_instances: Literal['always', 'never', 'subclass-instances']
# whether to validate default values during validation, default False
validate_default: bool
# used on typed-dicts and arguments
populate_by_name: bool # replaces `allow_population_by_field_name` in pydantic v1
# fields related to string fields only
str_max_length: int
str_min_length: int
str_strip_whitespace: bool
str_to_lower: bool
str_to_upper: bool
# fields related to float fields only
allow_inf_nan: bool # default: True
# the config options are used to customise serialization to JSON
ser_json_timedelta: Literal['iso8601', 'float'] # default: 'iso8601'
ser_json_bytes: Literal['utf8', 'base64', 'hex'] # default: 'utf8'
# used to hide input data from ValidationError repr
hide_input_in_errors: bool
validation_error_cause: bool # default: False
coerce_numbers_to_str: bool # default: False
regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex'
IncExCall: TypeAlias = 'set[int | str] | dict[int | str, IncExCall] | None'
class SerializationInfo(Protocol):
@property
def include(self) -> IncExCall:
...
@property
def exclude(self) -> IncExCall:
...
@property
def mode(self) -> str:
...
@property
def by_alias(self) -> bool:
...
@property
def exclude_unset(self) -> bool:
...
@property
def exclude_defaults(self) -> bool:
...
@property
def exclude_none(self) -> bool:
...
@property
def round_trip(self) -> bool:
...
def mode_is_json(self) -> bool:
...
def __str__(self) -> str:
...
def __repr__(self) -> str:
...
class FieldSerializationInfo(SerializationInfo, Protocol):
@property
def field_name(self) -> str:
...
class ValidationInfo(Protocol):
"""
Argument passed to validation functions.
"""
@property
def context(self) -> Any | None:
"""Current validation context."""
...
@property
def config(self) -> CoreConfig | None:
"""The CoreConfig that applies to this validation."""
...
@property
def mode(self) -> Literal['python', 'json']:
"""The type of input data we are currently validating"""
...
@property
def data(self) -> Dict[str, Any]:
"""The data being validated for this model."""
...
@property
def field_name(self) -> str | None:
"""
The name of the current field being validated if this validator is
attached to a model field.
"""
...
ExpectedSerializationTypes = Literal[
'none',
'int',
'bool',
'float',
'str',
'bytes',
'bytearray',
'list',
'tuple',
'set',
'frozenset',
'generator',
'dict',
'datetime',
'date',
'time',
'timedelta',
'url',
'multi-host-url',
'json',
'uuid',
]
class SimpleSerSchema(TypedDict, total=False):
type: Required[ExpectedSerializationTypes]
def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema:
"""
Returns a schema for serialization with a custom type.
Args:
type: The type to use for serialization
"""
return SimpleSerSchema(type=type)
# (__input_value: Any) -> Any
GeneralPlainNoInfoSerializerFunction = Callable[[Any], Any]
# (__input_value: Any, __info: FieldSerializationInfo) -> Any
GeneralPlainInfoSerializerFunction = Callable[[Any, SerializationInfo], Any]
# (__model: Any, __input_value: Any) -> Any
FieldPlainNoInfoSerializerFunction = Callable[[Any, Any], Any]
# (__model: Any, __input_value: Any, __info: FieldSerializationInfo) -> Any
FieldPlainInfoSerializerFunction = Callable[[Any, Any, FieldSerializationInfo], Any]
SerializerFunction = Union[
GeneralPlainNoInfoSerializerFunction,
GeneralPlainInfoSerializerFunction,
FieldPlainNoInfoSerializerFunction,
FieldPlainInfoSerializerFunction,
]
WhenUsed = Literal['always', 'unless-none', 'json', 'json-unless-none']
"""
Values have the following meanings:
* `'always'` means always use
* `'unless-none'` means use unless the value is `None`
* `'json'` means use when serializing to JSON
* `'json-unless-none'` means use when serializing to JSON and the value is not `None`
"""
class PlainSerializerFunctionSerSchema(TypedDict, total=False):
type: Required[Literal['function-plain']]
function: Required[SerializerFunction]
is_field_serializer: bool # default False
info_arg: bool # default False
return_schema: CoreSchema # if omitted, AnySchema is used
when_used: WhenUsed # default: 'always'
def plain_serializer_function_ser_schema(
function: SerializerFunction,
*,
is_field_serializer: bool | None = None,
info_arg: bool | None = None,
return_schema: CoreSchema | None = None,
when_used: WhenUsed = 'always',
) -> PlainSerializerFunctionSerSchema:
"""
Returns a schema for serialization with a function, can be either a "general" or "field" function.
Args:
function: The function to use for serialization
is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
and `info` includes `field_name`
info_arg: Whether the function takes an `__info` argument
return_schema: Schema to use for serializing return value
when_used: When the function should be called
"""
if when_used == 'always':
# just to avoid extra elements in schema, and to use the actual default defined in rust
when_used = None # type: ignore
return _dict_not_none(
type='function-plain',
function=function,
is_field_serializer=is_field_serializer,
info_arg=info_arg,
return_schema=return_schema,
when_used=when_used,
)
class SerializerFunctionWrapHandler(Protocol): # pragma: no cover
def __call__(self, __input_value: Any, __index_key: int | str | None = None) -> Any:
...
# (__input_value: Any, __serializer: SerializerFunctionWrapHandler) -> Any
GeneralWrapNoInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler], Any]
# (__input_value: Any, __serializer: SerializerFunctionWrapHandler, __info: SerializationInfo) -> Any
GeneralWrapInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo], Any]
# (__model: Any, __input_value: Any, __serializer: SerializerFunctionWrapHandler) -> Any
FieldWrapNoInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler], Any]
# (__model: Any, __input_value: Any, __serializer: SerializerFunctionWrapHandler, __info: FieldSerializationInfo) -> Any
FieldWrapInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo], Any]
WrapSerializerFunction = Union[
GeneralWrapNoInfoSerializerFunction,
GeneralWrapInfoSerializerFunction,
FieldWrapNoInfoSerializerFunction,
FieldWrapInfoSerializerFunction,
]
class WrapSerializerFunctionSerSchema(TypedDict, total=False):
type: Required[Literal['function-wrap']]
function: Required[WrapSerializerFunction]
is_field_serializer: bool # default False
info_arg: bool # default False
schema: CoreSchema # if omitted, the schema on which this serializer is defined is used
return_schema: CoreSchema # if omitted, AnySchema is used
when_used: WhenUsed # default: 'always'
def wrap_serializer_function_ser_schema(
function: WrapSerializerFunction,
*,
is_field_serializer: bool | None = None,
info_arg: bool | None = None,
schema: CoreSchema | None = None,
return_schema: CoreSchema | None = None,
when_used: WhenUsed = 'always',
) -> WrapSerializerFunctionSerSchema:
"""
Returns a schema for serialization with a wrap function, can be either a "general" or "field" function.
Args:
function: The function to use for serialization
is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
and `info` includes `field_name`
info_arg: Whether the function takes an `__info` argument
schema: The schema to use for the inner serialization
return_schema: Schema to use for serializing return value
when_used: When the function should be called
"""
if when_used == 'always':
# just to avoid extra elements in schema, and to use the actual default defined in rust
when_used = None # type: ignore
return _dict_not_none(
type='function-wrap',
function=function,
is_field_serializer=is_field_serializer,
info_arg=info_arg,
schema=schema,
return_schema=return_schema,
when_used=when_used,
)
class FormatSerSchema(TypedDict, total=False):
type: Required[Literal['format']]
formatting_string: Required[str]
when_used: WhenUsed # default: 'json-unless-none'
def format_ser_schema(formatting_string: str, *, when_used: WhenUsed = 'json-unless-none') -> FormatSerSchema:
"""
Returns a schema for serialization using python's `format` method.
Args:
formatting_string: String defining the format to use
when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
"""
if when_used == 'json-unless-none':
# just to avoid extra elements in schema, and to use the actual default defined in rust
when_used = None # type: ignore
return _dict_not_none(type='format', formatting_string=formatting_string, when_used=when_used)
class ToStringSerSchema(TypedDict, total=False):
type: Required[Literal['to-string']]
when_used: WhenUsed # default: 'json-unless-none'
def to_string_ser_schema(*, when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema:
"""
Returns a schema for serialization using python's `str()` / `__str__` method.
Args:
when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
"""
s = dict(type='to-string')
if when_used != 'json-unless-none':
# just to avoid extra elements in schema, and to use the actual default defined in rust
s['when_used'] = when_used
return s # type: ignore
class ModelSerSchema(TypedDict, total=False):
type: Required[Literal['model']]
cls: Required[Type[Any]]
schema: Required[CoreSchema]
def model_ser_schema(cls: Type[Any], schema: CoreSchema) -> ModelSerSchema:
"""
Returns a schema for serialization using a model.
Args:
cls: The expected class type, used to generate warnings if the wrong type is passed
schema: Internal schema to use to serialize the model dict
"""
return ModelSerSchema(type='model', cls=cls, schema=schema)
SerSchema = Union[
SimpleSerSchema,
PlainSerializerFunctionSerSchema,
WrapSerializerFunctionSerSchema,
FormatSerSchema,
ToStringSerSchema,
ModelSerSchema,
]
class ComputedField(TypedDict, total=False):
type: Required[Literal['computed-field']]
property_name: Required[str]
return_schema: Required[CoreSchema]
alias: str
metadata: Any
def computed_field(
property_name: str, return_schema: CoreSchema, *, alias: str | None = None, metadata: Any = None
) -> ComputedField:
"""
ComputedFields are properties of a model or dataclass that are included in serialization.
Args:
property_name: The name of the property on the model or dataclass
return_schema: The schema used for the type returned by the computed field
alias: The name to use in the serialized output
metadata: Any other information you want to include with the schema, not used by pydantic-core
"""
return _dict_not_none(
type='computed-field', property_name=property_name, return_schema=return_schema, alias=alias, metadata=metadata
)
class AnySchema(TypedDict, total=False):
type: Required[Literal['any']]
ref: str
metadata: Any
serialization: SerSchema
def any_schema(*, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None) -> AnySchema:
"""
Returns a schema that matches any value, e.g.:
```py
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.any_schema()
v = SchemaValidator(schema)
assert v.validate_python(1) == 1
```
Args:
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(type='any', ref=ref, metadata=metadata, serialization=serialization)
class NoneSchema(TypedDict, total=False):
type: Required[Literal['none']]
ref: str
metadata: Any
serialization: SerSchema
def none_schema(*, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None) -> NoneSchema:
"""
Returns a schema that matches a None value, e.g.:
```py
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.none_schema()
v = SchemaValidator(schema)
assert v.validate_python(None) is None
```
Args:
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(type='none', ref=ref, metadata=metadata, serialization=serialization)
class BoolSchema(TypedDict, total=False):
type: Required[Literal['bool']]
strict: bool
ref: str
metadata: Any
serialization: SerSchema
def bool_schema(
strict: bool | None = None, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None
) -> BoolSchema:
"""
Returns a schema that matches a bool value, e.g.:
```py
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.bool_schema()
v = SchemaValidator(schema)
assert v.validate_python('True') is True
```
Args:
strict: Whether the value should be a bool or a value that can be converted to a bool
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(type='bool', strict=strict, ref=ref, metadata=metadata, serialization=serialization)
class IntSchema(TypedDict, total=False):
type: Required[Literal['int']]
multiple_of: int
le: int
ge: int
lt: int
gt: int
strict: bool
ref: str
metadata: Any
serialization: SerSchema
def int_schema(
*,
multiple_of: int | None = None,
le: int | None = None,
ge: int | None = None,
lt: int | None = None,
gt: int | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: Any = None,
serialization: SerSchema | None = None,
) -> IntSchema:
"""
Returns a schema that matches a int value, e.g.:
```py
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.int_schema(multiple_of=2, le=6, ge=2)
v = SchemaValidator(schema)
assert v.validate_python('4') == 4
```
Args:
multiple_of: The value must be a multiple of this number
le: The value must be less than or equal to this number
ge: The value must be greater than or equal to this number
lt: The value must be strictly less than this number
gt: The value must be strictly greater than this number
strict: Whether the value should be a int or a value that can be converted to a int
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(
type='int',
multiple_of=multiple_of,
le=le,
ge=ge,
lt=lt,
gt=gt,
strict=strict,
ref=ref,
metadata=metadata,
serialization=serialization,
)
class FloatSchema(TypedDict, total=False):
type: Required[Literal['float']]
allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: True
multiple_of: float
le: float
ge: float
lt: float
gt: float
strict: bool
ref: str
metadata: Any
serialization: SerSchema
def float_schema(
*,
allow_inf_nan: bool | None = None,
multiple_of: float | None = None,
le: float | None = None,
ge: float | None = None,
lt: float | None = None,
gt: float | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: Any = None,
serialization: SerSchema | None = None,
) -> FloatSchema:
"""
Returns a schema that matches a float value, e.g.:
```py
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.float_schema(le=0.8, ge=0.2)
v = SchemaValidator(schema)
assert v.validate_python('0.5') == 0.5
```
Args:
allow_inf_nan: Whether to allow inf and nan values
multiple_of: The value must be a multiple of this number
le: The value must be less than or equal to this number
ge: The value must be greater than or equal to this number
lt: The value must be strictly less than this number
gt: The value must be strictly greater than this number
strict: Whether the value should be a float or a value that can be converted to a float
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(
type='float',
allow_inf_nan=allow_inf_nan,
multiple_of=multiple_of,
le=le,
ge=ge,
lt=lt,
gt=gt,
strict=strict,
ref=ref,
metadata=metadata,
serialization=serialization,
)
class DecimalSchema(TypedDict, total=False):
type: Required[Literal['decimal']]
allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: False
multiple_of: Decimal
le: Decimal
ge: Decimal
lt: Decimal
gt: Decimal
max_digits: int
decimal_places: int
strict: bool
ref: str
metadata: Any
serialization: SerSchema
def decimal_schema(
*,
allow_inf_nan: bool = None,
multiple_of: Decimal | None = None,
le: Decimal | None = None,
ge: Decimal | None = None,
lt: Decimal | None = None,
gt: Decimal | None = None,
max_digits: int | None = None,
decimal_places: int | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: Any = None,
serialization: SerSchema | None = None,
) -> DecimalSchema:
"""
Returns a schema that matches a decimal value, e.g.:
```py
from decimal import Decimal
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.decimal_schema(le=0.8, ge=0.2)
v = SchemaValidator(schema)
assert v.validate_python('0.5') == Decimal('0.5')
```
Args:
allow_inf_nan: Whether to allow inf and nan values
multiple_of: The value must be a multiple of this number
le: The value must be less than or equal to this number
ge: The value must be greater than or equal to this number
lt: The value must be strictly less than this number
gt: The value must be strictly greater than this number
max_digits: The maximum number of decimal digits allowed
decimal_places: The maximum number of decimal places allowed
strict: Whether the value should be a float or a value that can be converted to a float
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(
type='decimal',
gt=gt,
ge=ge,
lt=lt,
le=le,
max_digits=max_digits,
decimal_places=decimal_places,
multiple_of=multiple_of,
allow_inf_nan=allow_inf_nan,
strict=strict,
ref=ref,
metadata=metadata,
serialization=serialization,
)
class StringSchema(TypedDict, total=False):
type: Required[Literal['str']]
pattern: str
max_length: int
min_length: int
strip_whitespace: bool
to_lower: bool
to_upper: bool
regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex'
strict: bool
ref: str
metadata: Any
serialization: SerSchema
def str_schema(
*,
pattern: str | None = None,
max_length: int | None = None,
min_length: int | None = None,
strip_whitespace: bool | None = None,
to_lower: bool | None = None,
to_upper: bool | None = None,
regex_engine: Literal['rust-regex', 'python-re'] | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: Any = None,
serialization: SerSchema | None = None,
) -> StringSchema:
"""
Returns a schema that matches a string value, e.g.:
```py
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.str_schema(max_length=10, min_length=2)
v = SchemaValidator(schema)
assert v.validate_python('hello') == 'hello'
```
Args:
pattern: A regex pattern that the value must match
max_length: The value must be at most this length
min_length: The value must be at least this length
strip_whitespace: Whether to strip whitespace from the value
to_lower: Whether to convert the value to lowercase
to_upper: Whether to convert the value to uppercase
regex_engine: The regex engine to use for pattern validation. Default is 'rust-regex'.
- `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust
crate, which is non-backtracking and therefore more DDoS
resistant, but does not support all regex features.
- `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
which supports all regex features, but may be slower.
strict: Whether the value should be a string or a value that can be converted to a string
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(
type='str',
pattern=pattern,
max_length=max_length,
min_length=min_length,
strip_whitespace=strip_whitespace,
to_lower=to_lower,
to_upper=to_upper,
regex_engine=regex_engine,
strict=strict,
ref=ref,
metadata=metadata,
serialization=serialization,
)
class BytesSchema(TypedDict, total=False):
type: Required[Literal['bytes']]
max_length: int
min_length: int
strict: bool
ref: str
metadata: Any
serialization: SerSchema
def bytes_schema(
*,
max_length: int | None = None,
min_length: int | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: Any = None,
serialization: SerSchema | None = None,
) -> BytesSchema:
"""
Returns a schema that matches a bytes value, e.g.:
```py
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.bytes_schema(max_length=10, min_length=2)
v = SchemaValidator(schema)
assert v.validate_python(b'hello') == b'hello'
```
Args:
max_length: The value must be at most this length
min_length: The value must be at least this length
strict: Whether the value should be a bytes or a value that can be converted to a bytes
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(
type='bytes',
max_length=max_length,
min_length=min_length,
strict=strict,
ref=ref,
metadata=metadata,
serialization=serialization,
)
class DateSchema(TypedDict, total=False):
type: Required[Literal['date']]
strict: bool
le: date
ge: date
lt: date
gt: date
now_op: Literal['past', 'future']
# defaults to current local utc offset from `time.localtime().tm_gmtoff`
# value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py
now_utc_offset: int
ref: str
metadata: Any
serialization: SerSchema
def date_schema(
*,
strict: bool | None = None,
le: date | None = None,
ge: date | None = None,
lt: date | None = None,
gt: date | None = None,
now_op: Literal['past', 'future'] | None = None,
now_utc_offset: int | None = None,
ref: str | None = None,
metadata: Any = None,
serialization: SerSchema | None = None,
) -> DateSchema:
"""
Returns a schema that matches a date value, e.g.:
```py
from datetime import date
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1))
v = SchemaValidator(schema)
assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1)
```
Args:
strict: Whether the value should be a date or a value that can be converted to a date
le: The value must be less than or equal to this date
ge: The value must be greater than or equal to this date
lt: The value must be strictly less than this date
gt: The value must be strictly greater than this date
now_op: The value must be in the past or future relative to the current date
now_utc_offset: The value must be in the past or future relative to the current date with this utc offset
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(
type='date',
strict=strict,
le=le,
ge=ge,
lt=lt,
gt=gt,
now_op=now_op,
now_utc_offset=now_utc_offset,
ref=ref,
metadata=metadata,
serialization=serialization,
)
class TimeSchema(TypedDict, total=False):
type: Required[Literal['time']]
strict: bool
le: time
ge: time
lt: time
gt: time
tz_constraint: Union[Literal['aware', 'naive'], int]
microseconds_precision: Literal['truncate', 'error']
ref: str
metadata: Any
serialization: SerSchema
def time_schema(
*,
strict: bool | None = None,
le: time | None = None,
ge: time | None = None,
lt: time | None = None,
gt: time | None = None,
tz_constraint: Literal['aware', 'naive'] | int | None = None,
microseconds_precision: Literal['truncate', 'error'] = 'truncate',
ref: str | None = None,
metadata: Any = None,
serialization: SerSchema | None = None,
) -> TimeSchema:
"""
Returns a schema that matches a time value, e.g.:
```py
from datetime import time
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0))
v = SchemaValidator(schema)
assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0)
```
Args:
strict: Whether the value should be a time or a value that can be converted to a time
le: The value must be less than or equal to this time
ge: The value must be greater than or equal to this time
lt: The value must be strictly less than this time
gt: The value must be strictly greater than this time
tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset
microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
ref: optional unique identifier of the schema, used to reference the schema in other places
metadata: Any other information you want to include with the schema, not used by pydantic-core
serialization: Custom serialization schema
"""
return _dict_not_none(
type='time',
strict=strict,
le=le,
ge=ge,
lt=lt,
gt=gt,
tz_constraint=tz_constraint,
microseconds_precision=microseconds_precision,
ref=ref,
metadata=metadata,
serialization=serialization,
)