Coverage for pydantic / types.py: 96.40%
614 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
1"""The types module contains custom types used by pydantic."""
3from __future__ import annotations as _annotations 1hijcabmnokdespqrlfg
5import base64 1hijcabmnokdespqrlfg
6import dataclasses as _dataclasses 1hijcabmnokdespqrlfg
7import re 1hijcabmnokdespqrlfg
8import secrets 1hijcabmnokdespqrlfg
9import sys 1hijcabmnokdespqrlfg
10from collections.abc import Callable, Hashable, Iterator 1hijcabmnokdespqrlfg
11from datetime import date, datetime 1hijcabmnokdespqrlfg
12from decimal import Decimal 1hijcabmnokdespqrlfg
13from fractions import Fraction 1hijcabmnokdespqrlfg
14from pathlib import Path 1hijcabmnokdespqrlfg
15from re import Pattern 1hijcabmnokdespqrlfg
16from types import ModuleType 1hijcabmnokdespqrlfg
17from typing import ( 1hijcabmnokdespqrlfg
18 TYPE_CHECKING,
19 Annotated,
20 Any,
21 ClassVar,
22 Generic,
23 Literal,
24 Protocol,
25 TypeAlias,
26 TypeVar,
27 cast,
28)
29from uuid import UUID 1hijcabmnokdespqrlfg
31import annotated_types 1hijcabmnokdespqrlfg
32from annotated_types import BaseMetadata, MaxLen, MinLen 1hijcabmnokdespqrlfg
33from pydantic_core import CoreSchema, PydanticCustomError, SchemaSerializer, core_schema 1hijcabmnokdespqrlfg
34from typing_extensions import ( # noqa: UP035 (for `get_args` and `get_origin`) 1hijcabmnokdespqrlfg
35 TypeAliasType,
36 get_args,
37 get_origin,
38)
40from ._internal import _fields, _utils, _validators 1hijcabmnokdespqrlfg
41from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler 1hijcabmnokdespqrlfg
42from .errors import PydanticUserError 1hijcabmnokdespqrlfg
43from .json_schema import JsonSchemaValue 1hijcabmnokdespqrlfg
45if TYPE_CHECKING: 1hijcabmnokdespqrlfg
46 from ._internal._core_metadata import CoreMetadata
48__all__ = ( 1hijcabmnokdespqrlfg
49 'Strict',
50 'StrictStr',
51 'SocketPath',
52 'conbytes',
53 'conlist',
54 'conset',
55 'confrozenset',
56 'constr',
57 'ImportString',
58 'conint',
59 'PositiveInt',
60 'NegativeInt',
61 'NonNegativeInt',
62 'NonPositiveInt',
63 'confloat',
64 'PositiveFloat',
65 'NegativeFloat',
66 'NonNegativeFloat',
67 'NonPositiveFloat',
68 'FiniteFloat',
69 'condecimal',
70 'UUID1',
71 'UUID3',
72 'UUID4',
73 'UUID5',
74 'UUID6',
75 'UUID7',
76 'UUID8',
77 'FilePath',
78 'DirectoryPath',
79 'NewPath',
80 'Json',
81 'Secret',
82 'SecretStr',
83 'SecretBytes',
84 'StrictBool',
85 'StrictBytes',
86 'StrictInt',
87 'StrictFloat',
88 'ByteSize',
89 'PastDate',
90 'FutureDate',
91 'PastDatetime',
92 'FutureDatetime',
93 'condate',
94 'AwareDatetime',
95 'NaiveDatetime',
96 'AllowInfNan',
97 'EncoderProtocol',
98 'EncodedBytes',
99 'EncodedStr',
100 'Base64Encoder',
101 'Base64Bytes',
102 'Base64Str',
103 'Base64UrlBytes',
104 'Base64UrlStr',
105 'GetPydanticSchema',
106 'StringConstraints',
107 'Tag',
108 'Discriminator',
109 'JsonValue',
110 'OnErrorOmit',
111 'FailFast',
112)
115T = TypeVar('T') 1hijcabmnokdespqrlfg
118@_dataclasses.dataclass 1hijcabmnokdespqrlfg
119class Strict(_fields.PydanticMetadata, BaseMetadata): 1hijcabmnokdespqrlfg
120 """!!! abstract "Usage Documentation"
121 [Strict Mode with `Annotated` `Strict`](../concepts/strict_mode.md#strict-mode-with-annotated-strict)
123 A field metadata class to indicate that a field should be validated in strict mode.
124 Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
126 Attributes:
127 strict: Whether to validate the field in strict mode.
129 Example:
130 ```python
131 from typing import Annotated
133 from pydantic.types import Strict
135 StrictBool = Annotated[bool, Strict()]
136 ```
137 """
139 strict: bool = True 1hijcabmnokdespqrlfg
141 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
142 return hash(self.strict) 1hijcabmnokdespqrlfg
145# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BOOLEAN TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
147StrictBool = Annotated[bool, Strict()] 1hijcabmnokdespqrlfg
148"""A boolean that must be either ``True`` or ``False``.""" 1hijcabmnokdespqrlfg
150# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INTEGER TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
153def conint( 1hijcabmnokdespqrlfg
154 *,
155 strict: bool | None = None,
156 gt: int | None = None,
157 ge: int | None = None,
158 lt: int | None = None,
159 le: int | None = None,
160 multiple_of: int | None = None,
161) -> type[int]:
162 """
163 !!! warning "Discouraged"
164 This function is **discouraged** in favor of using
165 [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
166 [`Field`][pydantic.fields.Field] instead.
168 This function will be **deprecated** in Pydantic 3.0.
170 The reason is that `conint` returns a type, which doesn't play well with static analysis tools.
172 === ":x: Don't do this"
173 ```python
174 from pydantic import BaseModel, conint
176 class Foo(BaseModel):
177 bar: conint(strict=True, gt=0)
178 ```
180 === ":white_check_mark: Do this"
181 ```python
182 from typing import Annotated
184 from pydantic import BaseModel, Field
186 class Foo(BaseModel):
187 bar: Annotated[int, Field(strict=True, gt=0)]
188 ```
190 A wrapper around `int` that allows for additional constraints.
192 Args:
193 strict: Whether to validate the integer in strict mode. Defaults to `None`.
194 gt: The value must be greater than this.
195 ge: The value must be greater than or equal to this.
196 lt: The value must be less than this.
197 le: The value must be less than or equal to this.
198 multiple_of: The value must be a multiple of this.
200 Returns:
201 The wrapped integer type.
203 ```python
204 from pydantic import BaseModel, ValidationError, conint
206 class ConstrainedExample(BaseModel):
207 constrained_int: conint(gt=1)
209 m = ConstrainedExample(constrained_int=2)
210 print(repr(m))
211 #> ConstrainedExample(constrained_int=2)
213 try:
214 ConstrainedExample(constrained_int=0)
215 except ValidationError as e:
216 print(e.errors())
217 '''
218 [
219 {
220 'type': 'greater_than',
221 'loc': ('constrained_int',),
222 'msg': 'Input should be greater than 1',
223 'input': 0,
224 'ctx': {'gt': 1},
225 'url': 'https://errors.pydantic.dev/2/v/greater_than',
226 }
227 ]
228 '''
229 ```
231 """ # noqa: D212
232 return Annotated[ # pyright: ignore[reportReturnType] 1hijcabmnokdepqrlfg
233 int,
234 Strict(strict) if strict is not None else None,
235 annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
236 annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
237 ]
240PositiveInt = Annotated[int, annotated_types.Gt(0)] 1hijcabmnokdespqrlfg
241"""An integer that must be greater than zero. 1hijcabmnokdespqrlfg
243```python
244from pydantic import BaseModel, PositiveInt, ValidationError
246class Model(BaseModel):
247 positive_int: PositiveInt
249m = Model(positive_int=1)
250print(repr(m))
251#> Model(positive_int=1)
253try:
254 Model(positive_int=-1)
255except ValidationError as e:
256 print(e.errors())
257 '''
258 [
259 {
260 'type': 'greater_than',
261 'loc': ('positive_int',),
262 'msg': 'Input should be greater than 0',
263 'input': -1,
264 'ctx': {'gt': 0},
265 'url': 'https://errors.pydantic.dev/2/v/greater_than',
266 }
267 ]
268 '''
269```
270"""
271NegativeInt = Annotated[int, annotated_types.Lt(0)] 1hijcabmnokdespqrlfg
272"""An integer that must be less than zero. 1hijcabmnokdespqrlfg
274```python
275from pydantic import BaseModel, NegativeInt, ValidationError
277class Model(BaseModel):
278 negative_int: NegativeInt
280m = Model(negative_int=-1)
281print(repr(m))
282#> Model(negative_int=-1)
284try:
285 Model(negative_int=1)
286except ValidationError as e:
287 print(e.errors())
288 '''
289 [
290 {
291 'type': 'less_than',
292 'loc': ('negative_int',),
293 'msg': 'Input should be less than 0',
294 'input': 1,
295 'ctx': {'lt': 0},
296 'url': 'https://errors.pydantic.dev/2/v/less_than',
297 }
298 ]
299 '''
300```
301"""
302NonPositiveInt = Annotated[int, annotated_types.Le(0)] 1hijcabmnokdespqrlfg
303"""An integer that must be less than or equal to zero. 1hijcabmnokdespqrlfg
305```python
306from pydantic import BaseModel, NonPositiveInt, ValidationError
308class Model(BaseModel):
309 non_positive_int: NonPositiveInt
311m = Model(non_positive_int=0)
312print(repr(m))
313#> Model(non_positive_int=0)
315try:
316 Model(non_positive_int=1)
317except ValidationError as e:
318 print(e.errors())
319 '''
320 [
321 {
322 'type': 'less_than_equal',
323 'loc': ('non_positive_int',),
324 'msg': 'Input should be less than or equal to 0',
325 'input': 1,
326 'ctx': {'le': 0},
327 'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
328 }
329 ]
330 '''
331```
332"""
333NonNegativeInt = Annotated[int, annotated_types.Ge(0)] 1hijcabmnokdespqrlfg
334"""An integer that must be greater than or equal to zero. 1hijcabmnokdespqrlfg
336```python
337from pydantic import BaseModel, NonNegativeInt, ValidationError
339class Model(BaseModel):
340 non_negative_int: NonNegativeInt
342m = Model(non_negative_int=0)
343print(repr(m))
344#> Model(non_negative_int=0)
346try:
347 Model(non_negative_int=-1)
348except ValidationError as e:
349 print(e.errors())
350 '''
351 [
352 {
353 'type': 'greater_than_equal',
354 'loc': ('non_negative_int',),
355 'msg': 'Input should be greater than or equal to 0',
356 'input': -1,
357 'ctx': {'ge': 0},
358 'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
359 }
360 ]
361 '''
362```
363"""
364StrictInt = Annotated[int, Strict()] 1hijcabmnokdespqrlfg
365"""An integer that must be validated in strict mode. 1hijcabmnokdespqrlfg
367```python
368from pydantic import BaseModel, StrictInt, ValidationError
370class StrictIntModel(BaseModel):
371 strict_int: StrictInt
373try:
374 StrictIntModel(strict_int=3.14159)
375except ValidationError as e:
376 print(e)
377 '''
378 1 validation error for StrictIntModel
379 strict_int
380 Input should be a valid integer [type=int_type, input_value=3.14159, input_type=float]
381 '''
382```
383"""
385# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FLOAT TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
388@_dataclasses.dataclass 1hijcabmnokdespqrlfg
389class AllowInfNan(_fields.PydanticMetadata): 1hijcabmnokdespqrlfg
390 """A field metadata class to indicate that a field should allow `-inf`, `inf`, and `nan`.
392 Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
394 Attributes:
395 allow_inf_nan: Whether to allow `-inf`, `inf`, and `nan`. Defaults to `True`.
397 Example:
398 ```python
399 from typing import Annotated
401 from pydantic.types import AllowInfNan
403 LaxFloat = Annotated[float, AllowInfNan()]
404 ```
405 """
407 allow_inf_nan: bool = True 1hijcabmnokdespqrlfg
409 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
410 return hash(self.allow_inf_nan) 1hijcabmnokdespqrlfg
413def confloat( 1hijcabmnokdespqrlfg
414 *,
415 strict: bool | None = None,
416 gt: float | None = None,
417 ge: float | None = None,
418 lt: float | None = None,
419 le: float | None = None,
420 multiple_of: float | None = None,
421 allow_inf_nan: bool | None = None,
422) -> type[float]:
423 """
424 !!! warning "Discouraged"
425 This function is **discouraged** in favor of using
426 [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
427 [`Field`][pydantic.fields.Field] instead.
429 This function will be **deprecated** in Pydantic 3.0.
431 The reason is that `confloat` returns a type, which doesn't play well with static analysis tools.
433 === ":x: Don't do this"
434 ```python
435 from pydantic import BaseModel, confloat
437 class Foo(BaseModel):
438 bar: confloat(strict=True, gt=0)
439 ```
441 === ":white_check_mark: Do this"
442 ```python
443 from typing import Annotated
445 from pydantic import BaseModel, Field
447 class Foo(BaseModel):
448 bar: Annotated[float, Field(strict=True, gt=0)]
449 ```
451 A wrapper around `float` that allows for additional constraints.
453 Args:
454 strict: Whether to validate the float in strict mode.
455 gt: The value must be greater than this.
456 ge: The value must be greater than or equal to this.
457 lt: The value must be less than this.
458 le: The value must be less than or equal to this.
459 multiple_of: The value must be a multiple of this.
460 allow_inf_nan: Whether to allow `-inf`, `inf`, and `nan`.
462 Returns:
463 The wrapped float type.
465 ```python
466 from pydantic import BaseModel, ValidationError, confloat
468 class ConstrainedExample(BaseModel):
469 constrained_float: confloat(gt=1.0)
471 m = ConstrainedExample(constrained_float=1.1)
472 print(repr(m))
473 #> ConstrainedExample(constrained_float=1.1)
475 try:
476 ConstrainedExample(constrained_float=0.9)
477 except ValidationError as e:
478 print(e.errors())
479 '''
480 [
481 {
482 'type': 'greater_than',
483 'loc': ('constrained_float',),
484 'msg': 'Input should be greater than 1',
485 'input': 0.9,
486 'ctx': {'gt': 1.0},
487 'url': 'https://errors.pydantic.dev/2/v/greater_than',
488 }
489 ]
490 '''
491 ```
492 """ # noqa: D212
493 return Annotated[ # pyright: ignore[reportReturnType] 1hijcabmnokdepqrlfg
494 float,
495 Strict(strict) if strict is not None else None,
496 annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
497 annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
498 AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None,
499 ]
502PositiveFloat = Annotated[float, annotated_types.Gt(0)] 1hijcabmnokdespqrlfg
503"""A float that must be greater than zero. 1hijcabmnokdespqrlfg
505```python
506from pydantic import BaseModel, PositiveFloat, ValidationError
508class Model(BaseModel):
509 positive_float: PositiveFloat
511m = Model(positive_float=1.0)
512print(repr(m))
513#> Model(positive_float=1.0)
515try:
516 Model(positive_float=-1.0)
517except ValidationError as e:
518 print(e.errors())
519 '''
520 [
521 {
522 'type': 'greater_than',
523 'loc': ('positive_float',),
524 'msg': 'Input should be greater than 0',
525 'input': -1.0,
526 'ctx': {'gt': 0.0},
527 'url': 'https://errors.pydantic.dev/2/v/greater_than',
528 }
529 ]
530 '''
531```
532"""
533NegativeFloat = Annotated[float, annotated_types.Lt(0)] 1hijcabmnokdespqrlfg
534"""A float that must be less than zero. 1hijcabmnokdespqrlfg
536```python
537from pydantic import BaseModel, NegativeFloat, ValidationError
539class Model(BaseModel):
540 negative_float: NegativeFloat
542m = Model(negative_float=-1.0)
543print(repr(m))
544#> Model(negative_float=-1.0)
546try:
547 Model(negative_float=1.0)
548except ValidationError as e:
549 print(e.errors())
550 '''
551 [
552 {
553 'type': 'less_than',
554 'loc': ('negative_float',),
555 'msg': 'Input should be less than 0',
556 'input': 1.0,
557 'ctx': {'lt': 0.0},
558 'url': 'https://errors.pydantic.dev/2/v/less_than',
559 }
560 ]
561 '''
562```
563"""
564NonPositiveFloat = Annotated[float, annotated_types.Le(0)] 1hijcabmnokdespqrlfg
565"""A float that must be less than or equal to zero. 1hijcabmnokdespqrlfg
567```python
568from pydantic import BaseModel, NonPositiveFloat, ValidationError
570class Model(BaseModel):
571 non_positive_float: NonPositiveFloat
573m = Model(non_positive_float=0.0)
574print(repr(m))
575#> Model(non_positive_float=0.0)
577try:
578 Model(non_positive_float=1.0)
579except ValidationError as e:
580 print(e.errors())
581 '''
582 [
583 {
584 'type': 'less_than_equal',
585 'loc': ('non_positive_float',),
586 'msg': 'Input should be less than or equal to 0',
587 'input': 1.0,
588 'ctx': {'le': 0.0},
589 'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
590 }
591 ]
592 '''
593```
594"""
595NonNegativeFloat = Annotated[float, annotated_types.Ge(0)] 1hijcabmnokdespqrlfg
596"""A float that must be greater than or equal to zero. 1hijcabmnokdespqrlfg
598```python
599from pydantic import BaseModel, NonNegativeFloat, ValidationError
601class Model(BaseModel):
602 non_negative_float: NonNegativeFloat
604m = Model(non_negative_float=0.0)
605print(repr(m))
606#> Model(non_negative_float=0.0)
608try:
609 Model(non_negative_float=-1.0)
610except ValidationError as e:
611 print(e.errors())
612 '''
613 [
614 {
615 'type': 'greater_than_equal',
616 'loc': ('non_negative_float',),
617 'msg': 'Input should be greater than or equal to 0',
618 'input': -1.0,
619 'ctx': {'ge': 0.0},
620 'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
621 }
622 ]
623 '''
624```
625"""
626StrictFloat = Annotated[float, Strict(True)] 1hijcabmnokdespqrlfg
627"""A float that must be validated in strict mode. 1hijcabmnokdespqrlfg
629```python
630from pydantic import BaseModel, StrictFloat, ValidationError
632class StrictFloatModel(BaseModel):
633 strict_float: StrictFloat
635try:
636 StrictFloatModel(strict_float='1.0')
637except ValidationError as e:
638 print(e)
639 '''
640 1 validation error for StrictFloatModel
641 strict_float
642 Input should be a valid number [type=float_type, input_value='1.0', input_type=str]
643 '''
644```
645"""
646FiniteFloat = Annotated[float, AllowInfNan(False)] 1hijcabmnokdespqrlfg
647"""A float that must be finite (not ``-inf``, ``inf``, or ``nan``). 1hijcabmnokdespqrlfg
649```python
650from pydantic import BaseModel, FiniteFloat
652class Model(BaseModel):
653 finite: FiniteFloat
655m = Model(finite=1.0)
656print(m)
657#> finite=1.0
658```
659"""
662# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTES TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
665def conbytes( 1hijcabmnokdespqrlfg
666 *,
667 min_length: int | None = None,
668 max_length: int | None = None,
669 strict: bool | None = None,
670) -> type[bytes]:
671 """A wrapper around `bytes` that allows for additional constraints.
673 Args:
674 min_length: The minimum length of the bytes.
675 max_length: The maximum length of the bytes.
676 strict: Whether to validate the bytes in strict mode.
678 Returns:
679 The wrapped bytes type.
680 """
681 return Annotated[ # pyright: ignore[reportReturnType] 1hijcabmnokdepqrlfg
682 bytes,
683 Strict(strict) if strict is not None else None,
684 annotated_types.Len(min_length or 0, max_length),
685 ]
688StrictBytes = Annotated[bytes, Strict()] 1hijcabmnokdespqrlfg
689"""A bytes that must be validated in strict mode.""" 1hijcabmnokdespqrlfg
692# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STRING TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695@_dataclasses.dataclass(frozen=True) 1hijcabmnokdespqrlfg
696class StringConstraints(annotated_types.GroupedMetadata): 1hijcabmnokdespqrlfg
697 """!!! abstract "Usage Documentation"
698 [String types](./standard_library_types.md#strings)
700 A field metadata class to apply constraints to `str` types.
701 Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
703 Attributes:
704 strip_whitespace: Whether to remove leading and trailing whitespace.
705 to_upper: Whether to convert the string to uppercase.
706 to_lower: Whether to convert the string to lowercase.
707 strict: Whether to validate the string in strict mode.
708 min_length: The minimum length of the string.
709 max_length: The maximum length of the string.
710 pattern: A regex pattern that the string must match.
711 ascii_only: Whether the string should contain only ASCII characters.
713 Example:
714 ```python
715 from typing import Annotated
717 from pydantic.types import StringConstraints
719 ConstrainedStr = Annotated[str, StringConstraints(min_length=1, max_length=10)]
720 ```
721 """
723 strip_whitespace: bool | None = None 1hijcabmnokdespqrlfg
724 to_upper: bool | None = None 1hijcabmnokdespqrlfg
725 to_lower: bool | None = None 1hijcabmnokdespqrlfg
726 strict: bool | None = None 1hijcabmnokdespqrlfg
727 min_length: int | None = None 1hijcabmnokdespqrlfg
728 max_length: int | None = None 1hijcabmnokdespqrlfg
729 pattern: str | Pattern[str] | None = None 1hijcabmnokdespqrlfg
730 ascii_only: bool | None = None 1hijcabmnokdespqrlfg
732 def __iter__(self) -> Iterator[BaseMetadata]: 1hijcabmnokdespqrlfg
733 if self.min_length is not None: 1hijcabmnokdepqrlfg
734 yield MinLen(self.min_length) 1hijcabmnokdepqrlfg
735 if self.max_length is not None: 1hijcabmnokdepqrlfg
736 yield MaxLen(self.max_length) 1hijcabmnokdepqrlfg
737 if self.strict is not None: 1hijcabmnokdepqrlfg
738 yield Strict(self.strict) 1hijcabmnokdepqrlfg
739 if ( 1cabkdelfg
740 self.strip_whitespace is not None
741 or self.pattern is not None
742 or self.to_lower is not None
743 or self.to_upper is not None
744 or self.ascii_only is not None
745 ):
746 yield _fields.pydantic_general_metadata( 1hijcabmnokdepqrlfg
747 strip_whitespace=self.strip_whitespace,
748 to_upper=self.to_upper,
749 to_lower=self.to_lower,
750 pattern=self.pattern,
751 ascii_only=self.ascii_only,
752 )
755def constr( 1hijcabmnokdespqrlfg
756 *,
757 strip_whitespace: bool | None = None,
758 to_upper: bool | None = None,
759 to_lower: bool | None = None,
760 strict: bool | None = None,
761 min_length: int | None = None,
762 max_length: int | None = None,
763 pattern: str | Pattern[str] | None = None,
764 ascii_only: bool | None = None,
765) -> type[str]:
766 """
767 !!! warning "Discouraged"
768 This function is **discouraged** in favor of using
769 [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
770 [`StringConstraints`][pydantic.types.StringConstraints] instead.
772 This function will be **deprecated** in Pydantic 3.0.
774 The reason is that `constr` returns a type, which doesn't play well with static analysis tools.
776 === ":x: Don't do this"
777 ```python
778 from pydantic import BaseModel, constr
780 class Foo(BaseModel):
781 bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')
782 ```
784 === ":white_check_mark: Do this"
785 ```python
786 from typing import Annotated
788 from pydantic import BaseModel, StringConstraints
790 class Foo(BaseModel):
791 bar: Annotated[
792 str,
793 StringConstraints(
794 strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$'
795 ),
796 ]
797 ```
799 A wrapper around `str` that allows for additional constraints.
801 ```python
802 from pydantic import BaseModel, constr
804 class Foo(BaseModel):
805 bar: constr(strip_whitespace=True, to_upper=True)
807 foo = Foo(bar=' hello ')
808 print(foo)
809 #> bar='HELLO'
810 ```
812 Args:
813 strip_whitespace: Whether to remove leading and trailing whitespace.
814 to_upper: Whether to turn all characters to uppercase.
815 to_lower: Whether to turn all characters to lowercase.
816 strict: Whether to validate the string in strict mode.
817 min_length: The minimum length of the string.
818 max_length: The maximum length of the string.
819 pattern: A regex pattern to validate the string against.
820 ascii_only: Whether the string should contain only ASCII characters.
822 Returns:
823 The wrapped string type.
824 """ # noqa: D212
825 return Annotated[ # pyright: ignore[reportReturnType] 1hijcabmnokdepqrlfg
826 str,
827 StringConstraints(
828 strip_whitespace=strip_whitespace,
829 to_upper=to_upper,
830 to_lower=to_lower,
831 strict=strict,
832 min_length=min_length,
833 max_length=max_length,
834 pattern=pattern,
835 ascii_only=ascii_only,
836 ),
837 ]
840StrictStr = Annotated[str, Strict()] 1hijcabmnokdespqrlfg
841"""A string that must be validated in strict mode.""" 1hijcabmnokdespqrlfg
844# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ COLLECTION TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
845HashableItemType = TypeVar('HashableItemType', bound=Hashable) 1hijcabmnokdespqrlfg
848def conset( 1hijcabmnokdespqrlfg
849 item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None
850) -> type[set[HashableItemType]]:
851 """A wrapper around `typing.Set` that allows for additional constraints.
853 Args:
854 item_type: The type of the items in the set.
855 min_length: The minimum length of the set.
856 max_length: The maximum length of the set.
858 Returns:
859 The wrapped set type.
860 """
861 return Annotated[set[item_type], annotated_types.Len(min_length or 0, max_length)] # pyright: ignore[reportReturnType]
864def confrozenset( 1hijcabmnokdespqrlfg
865 item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None
866) -> type[frozenset[HashableItemType]]:
867 """A wrapper around `typing.FrozenSet` that allows for additional constraints.
869 Args:
870 item_type: The type of the items in the frozenset.
871 min_length: The minimum length of the frozenset.
872 max_length: The maximum length of the frozenset.
874 Returns:
875 The wrapped frozenset type.
876 """
877 return Annotated[frozenset[item_type], annotated_types.Len(min_length or 0, max_length)] # pyright: ignore[reportReturnType]
880AnyItemType = TypeVar('AnyItemType') 1hijcabmnokdespqrlfg
883def conlist( 1hijcabmnokdespqrlfg
884 item_type: type[AnyItemType],
885 *,
886 min_length: int | None = None,
887 max_length: int | None = None,
888) -> type[list[AnyItemType]]:
889 """A wrapper around [`list`][] that adds validation.
891 Args:
892 item_type: The type of the items in the list.
893 min_length: The minimum length of the list. Defaults to None.
894 max_length: The maximum length of the list. Defaults to None.
896 Returns:
897 The wrapped list type.
898 """
899 return Annotated[list[item_type], annotated_types.Len(min_length or 0, max_length)] # pyright: ignore[reportReturnType]
902# ~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPORT STRING TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
904AnyType = TypeVar('AnyType') 1hijcabmnokdespqrlfg
905if TYPE_CHECKING: 1hijcabmnokdespqrlfg
906 ImportString = Annotated[AnyType, ...]
907else:
909 class ImportString: 1hijcabmnokdespqrlfg
910 """A type that can be used to import a Python object from a string.
912 `ImportString` expects a string and loads the Python object importable at that dotted path.
913 Attributes of modules may be separated from the module by `:` or `.`, e.g. if `'math:cos'` is provided,
914 the resulting field value would be the function `cos`. If a `.` is used and both an attribute and submodule
915 are present at the same path, the module will be preferred.
917 On model instantiation, pointers will be evaluated and imported. There is
918 some nuance to this behavior, demonstrated in the examples below.
920 ```python
921 import math
923 from pydantic import BaseModel, Field, ImportString, ValidationError
925 class ImportThings(BaseModel):
926 obj: ImportString
928 # A string value will cause an automatic import
929 my_cos = ImportThings(obj='math.cos')
931 # You can use the imported function as you would expect
932 cos_of_0 = my_cos.obj(0)
933 assert cos_of_0 == 1
935 # A string whose value cannot be imported will raise an error
936 try:
937 ImportThings(obj='foo.bar')
938 except ValidationError as e:
939 print(e)
940 '''
941 1 validation error for ImportThings
942 obj
943 Invalid python path: No module named 'foo' [type=import_error, input_value='foo.bar', input_type=str]
944 '''
946 # Actual python objects can be assigned as well
947 my_cos = ImportThings(obj=math.cos)
948 my_cos_2 = ImportThings(obj='math.cos')
949 my_cos_3 = ImportThings(obj='math:cos')
950 assert my_cos == my_cos_2 == my_cos_3
952 # You can set default field value either as Python object:
953 class ImportThingsDefaultPyObj(BaseModel):
954 obj: ImportString = math.cos
956 # or as a string value (but only if used with `validate_default=True`)
957 class ImportThingsDefaultString(BaseModel):
958 obj: ImportString = Field(default='math.cos', validate_default=True)
960 my_cos_default1 = ImportThingsDefaultPyObj()
961 my_cos_default2 = ImportThingsDefaultString()
962 assert my_cos_default1.obj == my_cos_default2.obj == math.cos
964 # note: this will not work!
965 class ImportThingsMissingValidateDefault(BaseModel):
966 obj: ImportString = 'math.cos'
968 my_cos_default3 = ImportThingsMissingValidateDefault()
969 assert my_cos_default3.obj == 'math.cos' # just string, not evaluated
970 ```
972 Serializing an `ImportString` type to json is also possible.
974 ```python
975 from pydantic import BaseModel, ImportString
977 class ImportThings(BaseModel):
978 obj: ImportString
980 # Create an instance
981 m = ImportThings(obj='math.cos')
982 print(m)
983 #> obj=<built-in function cos>
984 print(m.model_dump_json())
985 #> {"obj":"math.cos"}
986 ```
987 """
989 @classmethod 1hijcabmnokdespqrlfg
990 def __class_getitem__(cls, item: AnyType) -> AnyType: 1hijcabmnokdespqrlfg
991 return Annotated[item, cls()] 1hijcabmnokdepqrlfg
993 @classmethod 1hijcabmnokdespqrlfg
994 def __get_pydantic_core_schema__( 1hijcabmnokdespqrlfg
995 cls, source: type[Any], handler: GetCoreSchemaHandler
996 ) -> core_schema.CoreSchema:
997 serializer = core_schema.plain_serializer_function_ser_schema(cls._serialize, when_used='json') 1hijcabmnokdepqrlfg
998 if cls is source: 1hijcabmnokdepqrlfg
999 # Treat bare usage of ImportString (`schema is None`) as the same as ImportString[Any]
1000 return core_schema.no_info_plain_validator_function( 1hijcabmnokdepqrlfg
1001 function=_validators.import_string, serialization=serializer
1002 )
1003 else:
1004 return core_schema.no_info_before_validator_function( 1hijcabmnokdepqrlfg
1005 function=_validators.import_string, schema=handler(source), serialization=serializer
1006 )
1008 @classmethod 1hijcabmnokdespqrlfg
1009 def __get_pydantic_json_schema__(cls, cs: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: 1hijcabmnokdespqrlfg
1010 return handler(core_schema.str_schema()) 1hijcabmnokdepqrlfg
1012 @staticmethod 1hijcabmnokdespqrlfg
1013 def _serialize(v: Any) -> str: 1hijcabmnokdespqrlfg
1014 if isinstance(v, ModuleType): 1hijcabmnokdepqrlfg
1015 return v.__name__ 1hijcabmnokdepqrlfg
1016 elif hasattr(v, '__module__') and hasattr(v, '__name__'): 1hijcabmnokdepqrlfg
1017 return f'{v.__module__}.{v.__name__}' 1hijcabmnokdepqrlfg
1018 # Handle special cases for sys.XXX streams
1019 # if we see more of these, we should consider a more general solution
1020 elif hasattr(v, 'name'): 1hijcabmnokdepqrlfg
1021 if v.name == '<stdout>': 1021 ↛ 1022line 1021 didn't jump to line 1022 because the condition on line 1021 was never true1hijcabmnokdepqrlfg
1022 return 'sys.stdout'
1023 elif v.name == '<stdin>': 1023 ↛ 1024line 1023 didn't jump to line 1024 because the condition on line 1023 was never true1hijcabmnokdepqrlfg
1024 return 'sys.stdin'
1025 elif v.name == '<stderr>': 1025 ↛ 1026line 1025 didn't jump to line 1026 because the condition on line 1025 was never true1hijcabmnokdepqrlfg
1026 return 'sys.stderr'
1027 return v 1hijcabmnokdepqrlfg
1029 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
1030 return 'ImportString' 1hijcabmnokdepqrlfg
1033# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DECIMAL TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1036def condecimal( 1hijcabmnokdespqrlfg
1037 *,
1038 strict: bool | None = None,
1039 gt: int | Decimal | None = None,
1040 ge: int | Decimal | None = None,
1041 lt: int | Decimal | None = None,
1042 le: int | Decimal | None = None,
1043 multiple_of: int | Decimal | None = None,
1044 max_digits: int | None = None,
1045 decimal_places: int | None = None,
1046 allow_inf_nan: bool | None = None,
1047) -> type[Decimal]:
1048 """
1049 !!! warning "Discouraged"
1050 This function is **discouraged** in favor of using
1051 [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
1052 [`Field`][pydantic.fields.Field] instead.
1054 This function will be **deprecated** in Pydantic 3.0.
1056 The reason is that `condecimal` returns a type, which doesn't play well with static analysis tools.
1058 === ":x: Don't do this"
1059 ```python
1060 from pydantic import BaseModel, condecimal
1062 class Foo(BaseModel):
1063 bar: condecimal(strict=True, allow_inf_nan=True)
1064 ```
1066 === ":white_check_mark: Do this"
1067 ```python
1068 from decimal import Decimal
1069 from typing import Annotated
1071 from pydantic import BaseModel, Field
1073 class Foo(BaseModel):
1074 bar: Annotated[Decimal, Field(strict=True, allow_inf_nan=True)]
1075 ```
1077 A wrapper around Decimal that adds validation.
1079 Args:
1080 strict: Whether to validate the value in strict mode. Defaults to `None`.
1081 gt: The value must be greater than this. Defaults to `None`.
1082 ge: The value must be greater than or equal to this. Defaults to `None`.
1083 lt: The value must be less than this. Defaults to `None`.
1084 le: The value must be less than or equal to this. Defaults to `None`.
1085 multiple_of: The value must be a multiple of this. Defaults to `None`.
1086 max_digits: The maximum number of digits. Defaults to `None`.
1087 decimal_places: The number of decimal places. Defaults to `None`.
1088 allow_inf_nan: Whether to allow infinity and NaN. Defaults to `None`.
1090 ```python
1091 from decimal import Decimal
1093 from pydantic import BaseModel, ValidationError, condecimal
1095 class ConstrainedExample(BaseModel):
1096 constrained_decimal: condecimal(gt=Decimal('1.0'))
1098 m = ConstrainedExample(constrained_decimal=Decimal('1.1'))
1099 print(repr(m))
1100 #> ConstrainedExample(constrained_decimal=Decimal('1.1'))
1102 try:
1103 ConstrainedExample(constrained_decimal=Decimal('0.9'))
1104 except ValidationError as e:
1105 print(e.errors())
1106 '''
1107 [
1108 {
1109 'type': 'greater_than',
1110 'loc': ('constrained_decimal',),
1111 'msg': 'Input should be greater than 1.0',
1112 'input': Decimal('0.9'),
1113 'ctx': {'gt': Decimal('1.0')},
1114 'url': 'https://errors.pydantic.dev/2/v/greater_than',
1115 }
1116 ]
1117 '''
1118 ```
1119 """ # noqa: D212
1120 return Annotated[ # pyright: ignore[reportReturnType] 1hijcabmnokdepqrlfg
1121 Decimal,
1122 Strict(strict) if strict is not None else None,
1123 annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
1124 annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
1125 _fields.pydantic_general_metadata(max_digits=max_digits, decimal_places=decimal_places),
1126 AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None,
1127 ]
1130# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UUID TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1133@_dataclasses.dataclass(slots=True) 1hijcabmnokdespqrlfg
1134class UuidVersion: 1hijcabmnokdespqrlfg
1135 """A field metadata class to indicate a [UUID](https://docs.python.org/3/library/uuid.html) version.
1137 Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
1139 Attributes:
1140 uuid_version: The version of the UUID. Must be one of 1, 3, 4, 5, 6, 7 or 8.
1142 Example:
1143 ```python
1144 from typing import Annotated
1145 from uuid import UUID
1147 from pydantic.types import UuidVersion
1149 UUID1 = Annotated[UUID, UuidVersion(1)]
1150 ```
1151 """
1153 uuid_version: Literal[1, 3, 4, 5, 6, 7, 8] 1hijcabmnokdespqrlfg
1155 def __get_pydantic_json_schema__( 1hijcabmnokdespqrlfg
1156 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
1157 ) -> JsonSchemaValue:
1158 field_schema = handler(core_schema) 1hijcabmnokdepqrlfg
1159 field_schema.pop('anyOf', None) # remove the bytes/str union 1hijcabmnokdepqrlfg
1160 field_schema.update(type='string', format=f'uuid{self.uuid_version}') 1hijcabmnokdepqrlfg
1161 return field_schema 1hijcabmnokdepqrlfg
1163 def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
1164 schema = handler(source) 1hijcabmnokdepqrlfg
1165 _check_annotated_type(schema['type'], 'uuid', self.__class__.__name__) 1hijcabmnokdepqrlfg
1166 schema['version'] = self.uuid_version # type: ignore 1hijcabmnokdepqrlfg
1167 return schema 1hijcabmnokdepqrlfg
1169 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
1170 return hash(self.uuid_version) 1hijcabmnokdespqrlfg
1173UUID1 = Annotated[UUID, UuidVersion(1)] 1hijcabmnokdespqrlfg
1174"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 1. 1hijcabmnokdespqrlfg
1176```python
1177import uuid
1179from pydantic import UUID1, BaseModel
1181class Model(BaseModel):
1182 uuid1: UUID1
1184Model(uuid1=uuid.uuid1())
1185```
1186"""
1187UUID3 = Annotated[UUID, UuidVersion(3)] 1hijcabmnokdespqrlfg
1188"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 3. 1hijcabmnokdespqrlfg
1190```python
1191import uuid
1193from pydantic import UUID3, BaseModel
1195class Model(BaseModel):
1196 uuid3: UUID3
1198Model(uuid3=uuid.uuid3(uuid.NAMESPACE_DNS, 'pydantic.org'))
1199```
1200"""
1201UUID4 = Annotated[UUID, UuidVersion(4)] 1hijcabmnokdespqrlfg
1202"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 4. 1hijcabmnokdespqrlfg
1204```python
1205import uuid
1207from pydantic import UUID4, BaseModel
1209class Model(BaseModel):
1210 uuid4: UUID4
1212Model(uuid4=uuid.uuid4())
1213```
1214"""
1215UUID5 = Annotated[UUID, UuidVersion(5)] 1hijcabmnokdespqrlfg
1216"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 5. 1hijcabmnokdespqrlfg
1218```python
1219import uuid
1221from pydantic import UUID5, BaseModel
1223class Model(BaseModel):
1224 uuid5: UUID5
1226Model(uuid5=uuid.uuid5(uuid.NAMESPACE_DNS, 'pydantic.org'))
1227```
1228"""
1229UUID6 = Annotated[UUID, UuidVersion(6)] 1hijcabmnokdespqrlfg
1230"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 6. 1hijcabmnokdespqrlfg
1232```python
1233import uuid
1235from pydantic import UUID6, BaseModel
1237class Model(BaseModel):
1238 uuid6: UUID6
1240Model(uuid6=uuid.UUID('1efea953-c2d6-6790-aa0a-69db8c87df97'))
1241```
1242"""
1243UUID7 = Annotated[UUID, UuidVersion(7)] 1hijcabmnokdespqrlfg
1244"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 7. 1hijcabmnokdespqrlfg
1246```python
1247import uuid
1249from pydantic import UUID7, BaseModel
1251class Model(BaseModel):
1252 uuid7: UUID7
1254Model(uuid7=uuid.UUID('0194fdcb-1c47-7a09-b52c-561154de0b4a'))
1255```
1256"""
1257UUID8 = Annotated[UUID, UuidVersion(8)] 1hijcabmnokdespqrlfg
1258"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 8. 1hijcabmnokdespqrlfg
1260```python
1261import uuid
1263from pydantic import UUID8, BaseModel
1265class Model(BaseModel):
1266 uuid8: UUID8
1268Model(uuid8=uuid.UUID('81a0b92e-6078-8551-9c81-8ccb666bdab8'))
1269```
1270"""
1272# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PATH TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1275@_dataclasses.dataclass 1hijcabmnokdespqrlfg
1276class PathType: 1hijcabmnokdespqrlfg
1277 path_type: Literal['file', 'dir', 'new', 'socket'] 1hijcabmnokdespqrlfg
1279 def __get_pydantic_json_schema__( 1hijcabmnokdespqrlfg
1280 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
1281 ) -> JsonSchemaValue:
1282 field_schema = handler(core_schema) 1hijcabmnokdepqrlfg
1283 format_conversion = {'file': 'file-path', 'dir': 'directory-path'} 1hijcabmnokdepqrlfg
1284 field_schema.update(format=format_conversion.get(self.path_type, 'path'), type='string') 1hijcabmnokdepqrlfg
1285 return field_schema 1hijcabmnokdepqrlfg
1287 def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
1288 function_lookup = { 1hijcabmnokdepqrlfg
1289 'file': cast(core_schema.WithInfoValidatorFunction, self.validate_file),
1290 'dir': cast(core_schema.WithInfoValidatorFunction, self.validate_directory),
1291 'new': cast(core_schema.WithInfoValidatorFunction, self.validate_new),
1292 'socket': cast(core_schema.WithInfoValidatorFunction, self.validate_socket),
1293 }
1295 return core_schema.with_info_after_validator_function( 1hijcabmnokdepqrlfg
1296 function_lookup[self.path_type],
1297 handler(source),
1298 )
1300 @staticmethod 1hijcabmnokdespqrlfg
1301 def validate_file(path: Path, _: core_schema.ValidationInfo) -> Path: 1hijcabmnokdespqrlfg
1302 if path.is_file(): 1hijcabmnokdepqrlfg
1303 return path 1hijcabmnokdepqrlfg
1304 else:
1305 raise PydanticCustomError('path_not_file', 'Path does not point to a file') 1hijcabmnokdepqrlfg
1307 @staticmethod 1hijcabmnokdespqrlfg
1308 def validate_socket(path: Path, _: core_schema.ValidationInfo) -> Path: 1hijcabmnokdespqrlfg
1309 if path.is_socket(): 1hijcabmnokdepqrlfg
1310 return path 1hijcab
1311 else:
1312 raise PydanticCustomError('path_not_socket', 'Path does not point to a socket') 1hijcabmnokdepqrlfg
1314 @staticmethod 1hijcabmnokdespqrlfg
1315 def validate_directory(path: Path, _: core_schema.ValidationInfo) -> Path: 1hijcabmnokdespqrlfg
1316 if path.is_dir(): 1hijcabmnokdepqrlfg
1317 return path 1hijcabmnokdepqrlfg
1318 else:
1319 raise PydanticCustomError('path_not_directory', 'Path does not point to a directory') 1hijcabmnokdepqrlfg
1321 @staticmethod 1hijcabmnokdespqrlfg
1322 def validate_new(path: Path, _: core_schema.ValidationInfo) -> Path: 1hijcabmnokdespqrlfg
1323 if path.exists(): 1hijcabmnokdepqrlfg
1324 raise PydanticCustomError('path_exists', 'Path already exists') 1hijcabmnokdepqrlfg
1325 elif not path.parent.exists(): 1hijcabmnokdepqrlfg
1326 raise PydanticCustomError('parent_does_not_exist', 'Parent directory does not exist') 1hijcabmnokdepqrlfg
1327 else:
1328 return path 1hijcabmnokdepqrlfg
1330 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
1331 return hash(self.path_type) 1hijcabmnokdespqrlfg
1334FilePath = Annotated[Path, PathType('file')] 1hijcabmnokdespqrlfg
1335"""A path that must point to a file. 1hijcabmnokdespqrlfg
1337```python
1338from pathlib import Path
1340from pydantic import BaseModel, FilePath, ValidationError
1342class Model(BaseModel):
1343 f: FilePath
1345path = Path('text.txt')
1346path.touch()
1347m = Model(f='text.txt')
1348print(m.model_dump())
1349#> {'f': PosixPath('text.txt')}
1350path.unlink()
1352path = Path('directory')
1353path.mkdir(exist_ok=True)
1354try:
1355 Model(f='directory') # directory
1356except ValidationError as e:
1357 print(e)
1358 '''
1359 1 validation error for Model
1360 f
1361 Path does not point to a file [type=path_not_file, input_value='directory', input_type=str]
1362 '''
1363path.rmdir()
1365try:
1366 Model(f='not-exists-file')
1367except ValidationError as e:
1368 print(e)
1369 '''
1370 1 validation error for Model
1371 f
1372 Path does not point to a file [type=path_not_file, input_value='not-exists-file', input_type=str]
1373 '''
1374```
1375"""
1376DirectoryPath = Annotated[Path, PathType('dir')] 1hijcabmnokdespqrlfg
1377"""A path that must point to a directory. 1hijcabmnokdespqrlfg
1379```python
1380from pathlib import Path
1382from pydantic import BaseModel, DirectoryPath, ValidationError
1384class Model(BaseModel):
1385 f: DirectoryPath
1387path = Path('directory/')
1388path.mkdir()
1389m = Model(f='directory/')
1390print(m.model_dump())
1391#> {'f': PosixPath('directory')}
1392path.rmdir()
1394path = Path('file.txt')
1395path.touch()
1396try:
1397 Model(f='file.txt') # file
1398except ValidationError as e:
1399 print(e)
1400 '''
1401 1 validation error for Model
1402 f
1403 Path does not point to a directory [type=path_not_directory, input_value='file.txt', input_type=str]
1404 '''
1405path.unlink()
1407try:
1408 Model(f='not-exists-directory')
1409except ValidationError as e:
1410 print(e)
1411 '''
1412 1 validation error for Model
1413 f
1414 Path does not point to a directory [type=path_not_directory, input_value='not-exists-directory', input_type=str]
1415 '''
1416```
1417"""
1418NewPath = Annotated[Path, PathType('new')] 1hijcabmnokdespqrlfg
1419"""A path for a new file or directory that must not already exist. The parent directory must already exist.""" 1hijcabmnokdespqrlfg
1421SocketPath = Annotated[Path, PathType('socket')] 1hijcabmnokdespqrlfg
1422"""A path to an existing socket file""" 1hijcabmnokdespqrlfg
1424# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1426if TYPE_CHECKING: 1hijcabmnokdespqrlfg
1427 # Json[list[str]] will be recognized by type checkers as list[str]
1428 Json = Annotated[AnyType, ...]
1430else:
1432 class Json: 1hijcabmnokdespqrlfg
1433 """A special type wrapper which loads JSON before parsing.
1435 You can use the `Json` data type to make Pydantic first load a raw JSON string before
1436 validating the loaded data into the parametrized type:
1438 ```python
1439 from typing import Any
1441 from pydantic import BaseModel, Json, ValidationError
1443 class AnyJsonModel(BaseModel):
1444 json_obj: Json[Any]
1446 class ConstrainedJsonModel(BaseModel):
1447 json_obj: Json[list[int]]
1449 print(AnyJsonModel(json_obj='{"b": 1}'))
1450 #> json_obj={'b': 1}
1451 print(ConstrainedJsonModel(json_obj='[1, 2, 3]'))
1452 #> json_obj=[1, 2, 3]
1454 try:
1455 ConstrainedJsonModel(json_obj=12)
1456 except ValidationError as e:
1457 print(e)
1458 '''
1459 1 validation error for ConstrainedJsonModel
1460 json_obj
1461 JSON input should be string, bytes or bytearray [type=json_type, input_value=12, input_type=int]
1462 '''
1464 try:
1465 ConstrainedJsonModel(json_obj='[a, b]')
1466 except ValidationError as e:
1467 print(e)
1468 '''
1469 1 validation error for ConstrainedJsonModel
1470 json_obj
1471 Invalid JSON: expected value at line 1 column 2 [type=json_invalid, input_value='[a, b]', input_type=str]
1472 '''
1474 try:
1475 ConstrainedJsonModel(json_obj='["a", "b"]')
1476 except ValidationError as e:
1477 print(e)
1478 '''
1479 2 validation errors for ConstrainedJsonModel
1480 json_obj.0
1481 Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
1482 json_obj.1
1483 Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]
1484 '''
1485 ```
1487 When you dump the model using `model_dump` or `model_dump_json`, the dumped value will be the result of validation,
1488 not the original JSON string. However, you can use the argument `round_trip=True` to get the original JSON string back:
1490 ```python
1491 from pydantic import BaseModel, Json
1493 class ConstrainedJsonModel(BaseModel):
1494 json_obj: Json[list[int]]
1496 print(ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json())
1497 #> {"json_obj":[1,2,3]}
1498 print(
1499 ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json(round_trip=True)
1500 )
1501 #> {"json_obj":"[1,2,3]"}
1502 ```
1503 """
1505 @classmethod 1hijcabmnokdespqrlfg
1506 def __class_getitem__(cls, item: AnyType) -> AnyType: 1hijcabmnokdespqrlfg
1507 return Annotated[item, cls()] 1hijcabmnokdepqrlfg
1509 @classmethod 1hijcabmnokdespqrlfg
1510 def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
1511 if cls is source: 1hijcabmnokdepqrlfg
1512 return core_schema.json_schema(None) 1hijcabmnokdepqrlfg
1513 else:
1514 return core_schema.json_schema(handler(source)) 1hijcabmnokdepqrlfg
1516 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
1517 return 'Json' 1hijcabmnokdepqrlfg
1519 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
1520 return hash(type(self)) 1hijcabmnokdepqrlfg
1522 def __eq__(self, other: Any) -> bool: 1hijcabmnokdespqrlfg
1523 return type(other) is type(self) 1hijcabmnokdepqrlfg
1526# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SECRET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1528# The `Secret` class being conceptually immutable, make the type variable covariant:
1529SecretType = TypeVar('SecretType', covariant=True) 1hijcabmnokdespqrlfg
1532class _SecretBase(Generic[SecretType]): 1hijcabmnokdespqrlfg
1533 def __init__(self, secret_value: SecretType) -> None: 1hijcabmnokdespqrlfg
1534 self._secret_value: SecretType = secret_value 1hijcabmnokdepqrlfg
1536 def get_secret_value(self) -> SecretType: 1hijcabmnokdespqrlfg
1537 """Get the secret value.
1539 Returns:
1540 The secret value.
1541 """
1542 return self._secret_value 1hijcabmnokdepqrlfg
1544 def __eq__(self, other: Any) -> bool: 1hijcabmnokdespqrlfg
1545 return isinstance(other, self.__class__) and self.get_secret_value() == other.get_secret_value() 1hijcabmnokdepqrlfg
1547 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
1548 return hash(self.get_secret_value())
1550 def __str__(self) -> str: 1hijcabmnokdespqrlfg
1551 return str(self._display()) 1hijcabmnokdepqrlfg
1553 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
1554 return f'{self.__class__.__name__}({self._display()!r})' 1hijcabmnokdepqrlfg
1556 def _display(self) -> str | bytes: 1hijcabmnokdespqrlfg
1557 raise NotImplementedError
1560def _serialize_secret(value: Secret[SecretType], info: core_schema.SerializationInfo) -> str | Secret[SecretType]: 1hijcabmnokdespqrlfg
1561 if info.mode == 'json': 1hijcabmnokdepqrlfg
1562 return str(value) 1hijcabmnokdepqrlfg
1563 else:
1564 return value 1hijcabmnokdepqrlfg
1567class Secret(_SecretBase[SecretType]): 1hijcabmnokdespqrlfg
1568 """A generic base class used for defining a field with sensitive information that you do not want to be visible in logging or tracebacks.
1570 You may either directly parametrize `Secret` with a type, or subclass from `Secret` with a parametrized type. The benefit of subclassing
1571 is that you can define a custom `_display()` method, which will be used for [`repr()`][repr] and [`str()`][str] methods. The examples below demonstrate both
1572 ways of using `Secret` to create a new secret type.
1574 1. Directly parametrizing `Secret` with a type:
1576 ```python
1577 from pydantic import BaseModel, Secret
1579 SecretBool = Secret[bool]
1581 class Model(BaseModel):
1582 secret_bool: SecretBool
1584 m = Model(secret_bool=True)
1585 print(m.model_dump())
1586 #> {'secret_bool': Secret('**********')}
1588 print(m.model_dump_json())
1589 #> {"secret_bool":"**********"}
1591 print(m.secret_bool.get_secret_value())
1592 #> True
1593 ```
1595 2. Subclassing from parametrized `Secret`:
1597 ```python
1598 from datetime import date
1600 from pydantic import BaseModel, Secret
1602 class SecretDate(Secret[date]):
1603 def _display(self) -> str:
1604 return '****/**/**'
1606 class Model(BaseModel):
1607 secret_date: SecretDate
1609 m = Model(secret_date=date(2022, 1, 1))
1610 print(m.model_dump())
1611 #> {'secret_date': SecretDate('****/**/**')}
1613 print(m.model_dump_json())
1614 #> {"secret_date":"****/**/**"}
1616 print(m.secret_date.get_secret_value())
1617 #> 2022-01-01
1618 ```
1620 The value returned by the `_display()` method will be used for [`repr()`][repr] and [`str()`][str].
1622 You can enforce constraints on the underlying type through annotations:
1623 For example:
1625 ```python
1626 from typing import Annotated
1628 from pydantic import BaseModel, Field, Secret, ValidationError
1630 SecretPosInt = Secret[Annotated[int, Field(gt=0, strict=True)]]
1632 class Model(BaseModel):
1633 sensitive_int: SecretPosInt
1635 m = Model(sensitive_int=42)
1636 print(m.model_dump())
1637 #> {'sensitive_int': Secret('**********')}
1639 try:
1640 m = Model(sensitive_int=-42) # (1)!
1641 except ValidationError as exc_info:
1642 print(exc_info.errors(include_url=False, include_input=False))
1643 '''
1644 [
1645 {
1646 'type': 'greater_than',
1647 'loc': ('sensitive_int',),
1648 'msg': 'Input should be greater than 0',
1649 'ctx': {'gt': 0},
1650 }
1651 ]
1652 '''
1654 try:
1655 m = Model(sensitive_int='42') # (2)!
1656 except ValidationError as exc_info:
1657 print(exc_info.errors(include_url=False, include_input=False))
1658 '''
1659 [
1660 {
1661 'type': 'int_type',
1662 'loc': ('sensitive_int',),
1663 'msg': 'Input should be a valid integer',
1664 }
1665 ]
1666 '''
1667 ```
1669 1. The input value is not greater than 0, so it raises a validation error.
1670 2. The input value is not an integer, so it raises a validation error because the `SecretPosInt` type has strict mode enabled.
1672 Two `Secret` types compare equal if the secret values are equal. For the [`SecretStr`][pydantic.types.SecretStr] and
1673 [`SecretBytes`][pydantic.types.SecretBytes] implementations, constant-time comparison is achieved
1674 (using [`secrets.compare_digest()`][secrets.compare_digest]). If you need constant-time comparison on your `Secret`
1675 subclass, you can do so by overriding [`__eq__()`][object.__eq__].
1676 """
1678 def _display(self) -> str | bytes: 1hijcabmnokdespqrlfg
1679 return '**********' if self.get_secret_value() else '' 1hijcabmnokdepqrlfg
1681 @classmethod 1hijcabmnokdespqrlfg
1682 def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
1683 inner_type = None 1hijcabmnokdepqrlfg
1684 # if origin_type is Secret, then cls is a GenericAlias, and we can extract the inner type directly
1685 origin_type = get_origin(source) 1hijcabmnokdepqrlfg
1686 if origin_type is not None: 1hijcabmnokdepqrlfg
1687 inner_type = get_args(source)[0] 1hijcabmnokdepqrlfg
1688 # otherwise, we need to get the inner type from the base class
1689 else:
1690 bases = getattr(cls, '__orig_bases__', getattr(cls, '__bases__', [])) 1hijcabmnokdepqrlfg
1691 for base in bases: 1hijcabmnokdepqrlfg
1692 if get_origin(base) is Secret: 1692 ↛ 1691line 1692 didn't jump to line 1691 because the condition on line 1692 was always true1hijcabmnokdepqrlfg
1693 inner_type = get_args(base)[0] 1hijcabmnokdepqrlfg
1694 if bases == [] or inner_type is None: 1694 ↛ 1695line 1694 didn't jump to line 1695 because the condition on line 1694 was never true1hijcabmnokdepqrlfg
1695 raise TypeError(
1696 f"Can't get secret type from {cls.__name__}. "
1697 'Please use Secret[<type>], or subclass from Secret[<type>] instead.'
1698 )
1700 inner_schema = handler.generate_schema(inner_type) # type: ignore 1hijcabmnokdepqrlfg
1702 def validate_secret_value(value, handler) -> Secret[SecretType]: 1hijcabmnokdepqrlfg
1703 if isinstance(value, Secret): 1hijcabmnokdepqrlfg
1704 value = value.get_secret_value() 1hijcabmnokdepqrlfg
1705 validated_inner = handler(value) 1hijcabmnokdepqrlfg
1706 return cls(validated_inner) 1hijcabmnokdepqrlfg
1708 return core_schema.json_or_python_schema( 1hijcabmnokdepqrlfg
1709 python_schema=core_schema.no_info_wrap_validator_function(
1710 validate_secret_value,
1711 inner_schema,
1712 ),
1713 json_schema=core_schema.no_info_after_validator_function(lambda x: cls(x), inner_schema),
1714 serialization=core_schema.plain_serializer_function_ser_schema(
1715 _serialize_secret,
1716 info_arg=True,
1717 when_used='always',
1718 ),
1719 )
1721 __pydantic_serializer__ = SchemaSerializer( 1hijcabmnokdespqrlfg
1722 core_schema.any_schema(
1723 serialization=core_schema.plain_serializer_function_ser_schema(
1724 _serialize_secret,
1725 info_arg=True,
1726 when_used='always',
1727 )
1728 )
1729 )
1732def _secret_display(value: SecretType) -> str: # type: ignore 1hijcabmnokdespqrlfg
1733 return '**********' if value else '' 1hijcabmnokdepqrlfg
1736def _serialize_secret_field( 1hijcabmnokdespqrlfg
1737 value: _SecretField[SecretType], info: core_schema.SerializationInfo
1738) -> str | _SecretField[SecretType]:
1739 if info.mode == 'json': 1hijcabmnokdepqrlfg
1740 # we want the output to always be string without the `b'` prefix for bytes,
1741 # hence we just use `secret_display`
1742 return _secret_display(value.get_secret_value()) 1hijcabmnokdepqrlfg
1743 else:
1744 return value 1hijcabmnokdepqrlfg
1747class _SecretField(_SecretBase[SecretType]): 1hijcabmnokdespqrlfg
1748 _inner_schema: ClassVar[CoreSchema] 1hijcabmnokdespqrlfg
1749 _error_kind: ClassVar[str] 1hijcabmnokdespqrlfg
1751 @classmethod 1hijcabmnokdespqrlfg
1752 def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
1753 def get_json_schema(_core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: 1hijcabmnokdepqrlfg
1754 json_schema = handler(cls._inner_schema) 1hijcabmnokdepqrlfg
1755 _utils.update_not_none( 1hijcabmnokdepqrlfg
1756 json_schema,
1757 type='string',
1758 writeOnly=True,
1759 format='password',
1760 )
1761 return json_schema 1hijcabmnokdepqrlfg
1763 def get_secret_schema(strict: bool) -> CoreSchema: 1hijcabmnokdepqrlfg
1764 inner_schema = {**cls._inner_schema, 'strict': strict} 1hijcabmnokdepqrlfg
1765 json_schema = core_schema.no_info_after_validator_function( 1hijcabmnokdepqrlfg
1766 source, # construct the type
1767 inner_schema, # pyright: ignore[reportArgumentType]
1768 )
1769 return core_schema.json_or_python_schema( 1hijcabmnokdepqrlfg
1770 python_schema=core_schema.union_schema(
1771 [
1772 core_schema.is_instance_schema(source),
1773 json_schema,
1774 ],
1775 custom_error_type=cls._error_kind,
1776 ),
1777 json_schema=json_schema,
1778 serialization=core_schema.plain_serializer_function_ser_schema(
1779 _serialize_secret_field,
1780 info_arg=True,
1781 when_used='unless-none',
1782 ),
1783 )
1785 return core_schema.lax_or_strict_schema( 1hijcabmnokdepqrlfg
1786 lax_schema=get_secret_schema(strict=False),
1787 strict_schema=get_secret_schema(strict=True),
1788 metadata={'pydantic_js_functions': [get_json_schema]},
1789 )
1791 __pydantic_serializer__ = SchemaSerializer( 1hijcabmnokdespqrlfg
1792 core_schema.any_schema(
1793 serialization=core_schema.plain_serializer_function_ser_schema(
1794 _serialize_secret_field,
1795 info_arg=True,
1796 when_used='always',
1797 )
1798 )
1799 )
1802class SecretStr(_SecretField[str]): 1hijcabmnokdespqrlfg
1803 """A string used for storing sensitive information that you do not want to be visible in logging or tracebacks.
1805 When the secret value is nonempty, it is displayed as `'**********'` instead of the underlying value in
1806 calls to [`repr()`][repr] and [`str()`][str]. If the value _is_ empty, it is displayed as `''`.
1808 Two `SecretStr` types compare equal if the secret values are equal. Constant-time comparison is achieved
1809 (using [`secrets.compare_digest()`][secrets.compare_digest]).
1811 ```python
1812 from pydantic import BaseModel, SecretStr
1814 class User(BaseModel):
1815 username: str
1816 password: SecretStr
1818 user = User(username='scolvin', password='password1')
1820 print(user)
1821 #> username='scolvin' password=SecretStr('**********')
1822 print(user.password.get_secret_value())
1823 #> password1
1824 print((SecretStr('password'), SecretStr('')))
1825 #> (SecretStr('**********'), SecretStr(''))
1826 ```
1828 As seen above, by default, [`SecretStr`][pydantic.types.SecretStr] (and [`SecretBytes`][pydantic.types.SecretBytes])
1829 will be serialized as `**********` when serializing to json.
1831 You can use a [field serializer](../concepts/serialization.md#field-serializers) to dump the
1832 secret as plain-text when serializing to json.
1834 ```python
1835 from pydantic import BaseModel, SecretBytes, SecretStr, field_serializer
1837 class Model(BaseModel):
1838 password: SecretStr
1839 password_bytes: SecretBytes
1841 @field_serializer('password', 'password_bytes', when_used='json')
1842 def dump_secret(self, v):
1843 return v.get_secret_value()
1845 model = Model(password='IAmSensitive', password_bytes=b'IAmSensitiveBytes')
1846 print(model)
1847 #> password=SecretStr('**********') password_bytes=SecretBytes(b'**********')
1848 print(model.password)
1849 #> **********
1850 print(model.model_dump())
1851 '''
1852 {
1853 'password': SecretStr('**********'),
1854 'password_bytes': SecretBytes(b'**********'),
1855 }
1856 '''
1857 print(model.model_dump_json())
1858 #> {"password":"IAmSensitive","password_bytes":"IAmSensitiveBytes"}
1859 ```
1860 """
1862 _inner_schema: ClassVar[CoreSchema] = core_schema.str_schema() 1hijcabmnokdespqrlfg
1863 _error_kind: ClassVar[str] = 'string_type' 1hijcabmnokdespqrlfg
1865 def __len__(self) -> int: 1hijcabmnokdespqrlfg
1866 return len(self._secret_value) 1hijcabmnokdepqrlfg
1868 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
1869 return hash(self.get_secret_value()) 1hijcabmnokdepqrlfg
1871 def __eq__(self, other: Any) -> bool: 1hijcabmnokdespqrlfg
1872 if not isinstance(other, self.__class__): 1hijcabmnokdepqrlfg
1873 return False 1hijcabmnokdepqrlfg
1875 # `secrets.compare_digest()` only supports ASCII strings, so encode to bytes first:
1876 return secrets.compare_digest( 1hijcabmnokdepqrlfg
1877 self.get_secret_value().encode('utf-8', errors='surrogatepass'),
1878 other.get_secret_value().encode('utf-8', errors='surrogatepass'),
1879 )
1881 def _display(self) -> str: 1hijcabmnokdespqrlfg
1882 return _secret_display(self._secret_value) 1hijcabmnokdepqrlfg
1885class SecretBytes(_SecretField[bytes]): 1hijcabmnokdespqrlfg
1886 """A bytes used for storing sensitive information that you do not want to be visible in logging or tracebacks.
1888 When the secret value is nonempty, it is displayed as `b'**********'` instead of the underlying value in
1889 calls to [`repr()`][repr] and [`str()`][str]. If the value _is_ empty, it is displayed as `b''`.
1891 Two `SecretBytes` types compare equal if the secret values are equal. Constant-time comparison is achieved
1892 (using [`secrets.compare_digest()`][secrets.compare_digest]).
1894 ```python
1895 from pydantic import BaseModel, SecretBytes
1897 class User(BaseModel):
1898 username: str
1899 password: SecretBytes
1901 user = User(username='scolvin', password=b'password1')
1902 #> username='scolvin' password=SecretBytes(b'**********')
1903 print(user.password.get_secret_value())
1904 #> b'password1'
1905 print((SecretBytes(b'password'), SecretBytes(b'')))
1906 #> (SecretBytes(b'**********'), SecretBytes(b''))
1907 ```
1908 """
1910 _inner_schema: ClassVar[CoreSchema] = core_schema.bytes_schema() 1hijcabmnokdespqrlfg
1911 _error_kind: ClassVar[str] = 'bytes_type' 1hijcabmnokdespqrlfg
1913 def __len__(self) -> int: 1hijcabmnokdespqrlfg
1914 return len(self._secret_value) 1hijcabmnokdepqrlfg
1916 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
1917 return hash(self.get_secret_value()) 1hijcabmnokdepqrlfg
1919 def __eq__(self, other: Any) -> bool: 1hijcabmnokdespqrlfg
1920 if not isinstance(other, self.__class__): 1hijcabmnokdepqrlfg
1921 return False 1hijcabmnokdepqrlfg
1923 return secrets.compare_digest(self.get_secret_value(), other.get_secret_value()) 1hijcabmnokdepqrlfg
1925 def _display(self) -> bytes: 1hijcabmnokdespqrlfg
1926 return _secret_display(self._secret_value).encode() 1hijcabmnokdepqrlfg
1929# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTE SIZE TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1932class ByteSize(int): 1hijcabmnokdespqrlfg
1933 """Converts a string representing a number of bytes with units (such as `'1KB'` or `'11.5MiB'`) into an integer.
1935 You can use the `ByteSize` data type to (case-insensitively) convert a string representation of a number of bytes into
1936 an integer, and also to print out human-readable strings representing a number of bytes.
1938 In conformance with [IEC 80000-13 Standard](https://en.wikipedia.org/wiki/ISO/IEC_80000) we interpret `'1KB'` to mean 1000 bytes,
1939 and `'1KiB'` to mean 1024 bytes. In general, including a middle `'i'` will cause the unit to be interpreted as a power of 2,
1940 rather than a power of 10 (so, for example, `'1 MB'` is treated as `1_000_000` bytes, whereas `'1 MiB'` is treated as `1_048_576` bytes).
1942 !!! info
1943 Note that `1b` will be parsed as "1 byte" and not "1 bit".
1945 ```python
1946 from pydantic import BaseModel, ByteSize
1948 class MyModel(BaseModel):
1949 size: ByteSize
1951 print(MyModel(size=52000).size)
1952 #> 52000
1953 print(MyModel(size='3000 KiB').size)
1954 #> 3072000
1956 m = MyModel(size='50 PB')
1957 print(m.size.human_readable())
1958 #> 44.4PiB
1959 print(m.size.human_readable(decimal=True))
1960 #> 50.0PB
1961 print(m.size.human_readable(separator=' '))
1962 #> 44.4 PiB
1964 print(m.size.to('TiB'))
1965 #> 45474.73508864641
1966 ```
1967 """
1969 byte_sizes: ClassVar[dict[str, float]] = { 1hijcabmnokdespqrlfg
1970 'b': 1,
1971 'kb': 10**3,
1972 'mb': 10**6,
1973 'gb': 10**9,
1974 'tb': 10**12,
1975 'pb': 10**15,
1976 'eb': 10**18,
1977 'kib': 2**10,
1978 'mib': 2**20,
1979 'gib': 2**30,
1980 'tib': 2**40,
1981 'pib': 2**50,
1982 'eib': 2**60,
1983 'bit': 1 / 8,
1984 'kbit': 10**3 / 8,
1985 'mbit': 10**6 / 8,
1986 'gbit': 10**9 / 8,
1987 'tbit': 10**12 / 8,
1988 'pbit': 10**15 / 8,
1989 'ebit': 10**18 / 8,
1990 'kibit': 2**10 / 8,
1991 'mibit': 2**20 / 8,
1992 'gibit': 2**30 / 8,
1993 'tibit': 2**40 / 8,
1994 'pibit': 2**50 / 8,
1995 'eibit': 2**60 / 8,
1996 }
1997 byte_sizes.update({k.lower()[0]: v for k, v in byte_sizes.items() if 'i' not in k}) 1hijcabmnokdespqrlfg
1999 byte_string_pattern: ClassVar[str] = r'^\s*(\d*\.?\d+)\s*(\w+)?' 1hijcabmnokdespqrlfg
2000 byte_string_re: ClassVar[Pattern[str]] = re.compile(byte_string_pattern, re.IGNORECASE) 1hijcabmnokdespqrlfg
2002 @classmethod 1hijcabmnokdespqrlfg
2003 def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
2004 return core_schema.with_info_after_validator_function( 1hijcabmnokdepqrlfg
2005 function=cls._validate,
2006 schema=core_schema.union_schema(
2007 [
2008 core_schema.str_schema(pattern=cls.byte_string_pattern),
2009 core_schema.int_schema(ge=0),
2010 ],
2011 custom_error_type='byte_size',
2012 custom_error_message='could not parse value and unit from byte string',
2013 ),
2014 serialization=core_schema.plain_serializer_function_ser_schema(
2015 int, return_schema=core_schema.int_schema(ge=0)
2016 ),
2017 )
2019 @classmethod 1hijcabmnokdespqrlfg
2020 def _validate(cls, input_value: Any, /, _: core_schema.ValidationInfo) -> ByteSize: 1hijcabmnokdespqrlfg
2021 try: 1hijcabmnokdepqrlfg
2022 return cls(int(input_value)) 1hijcabmnokdepqrlfg
2023 except ValueError: 1hijcabmnokdepqrlfg
2024 pass 1hijcabmnokdepqrlfg
2026 str_match = cls.byte_string_re.match(str(input_value)) 1hijcabmnokdepqrlfg
2027 if str_match is None: 2027 ↛ 2028line 2027 didn't jump to line 2028 because the condition on line 2027 was never true1hijcabmnokdepqrlfg
2028 raise PydanticCustomError('byte_size', 'could not parse value and unit from byte string')
2030 scalar, unit = str_match.groups() 1hijcabmnokdepqrlfg
2031 if unit is None: 1hijcabmnokdepqrlfg
2032 unit = 'b' 1hijcabmnokdepqrlfg
2034 try: 1hijcabmnokdepqrlfg
2035 unit_mult = cls.byte_sizes[unit.lower()] 1hijcabmnokdepqrlfg
2036 except KeyError: 1hijcabmnokdepqrlfg
2037 raise PydanticCustomError('byte_size_unit', 'could not interpret byte unit: {unit}', {'unit': unit}) 1hijcabmnokdepqrlfg
2039 # Matches the default `default_max_str_digits` value (https://docs.python.org/3/library/sys.html#sys.int_info.default_max_str_digits)
2040 # to avoid potential DoS issues from the `Fraction()` constructor:
2041 if len(scalar) > 4300: 1hijcabmnokdepqrlfg
2042 raise PydanticCustomError('byte_size', 'could not parse value and unit from byte string') 1hijcabmnokdepqrlfg
2044 # `Fraction` keeps the computation exact (using `float(scalar)` would turn `'1.005 KB'` into 1004 bytes).
2045 # All the `unit_mult` are exactly representable as floats, so `Fraction(unit_mult)` is exact as well
2046 # (see https://docs.python.org/3/tutorial/floatingpoint.html#representation-error).
2047 return cls(int(Fraction(scalar) * Fraction(unit_mult))) 1hijcabmnokdepqrlfg
2049 def human_readable(self, decimal: bool = False, separator: str = '') -> str: 1hijcabmnokdespqrlfg
2050 """Converts a byte size to a human readable string.
2052 Args:
2053 decimal: If True, use decimal units (e.g. 1000 bytes per KB). If False, use binary units
2054 (e.g. 1024 bytes per KiB).
2055 separator: A string used to split the value and unit. Defaults to an empty string ('').
2057 Returns:
2058 A human readable string representation of the byte size.
2059 """
2060 if decimal: 1hijcabmnokdepqrlfg
2061 divisor = 1000 1hijcabmnokdepqrlfg
2062 units = 'B', 'KB', 'MB', 'GB', 'TB', 'PB' 1hijcabmnokdepqrlfg
2063 final_unit = 'EB' 1hijcabmnokdepqrlfg
2064 else:
2065 divisor = 1024 1hijcabmnokdepqrlfg
2066 units = 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB' 1hijcabmnokdepqrlfg
2067 final_unit = 'EiB' 1hijcabmnokdepqrlfg
2069 num = float(self) 1hijcabmnokdepqrlfg
2070 for unit in units: 1hijcabmnokdepqrlfg
2071 # Check the rounded value, so that e.g. 1023.99KiB is shown as 1.0MiB and not 1024.0KiB:
2072 if round(abs(num), 1) < divisor: 1hijcabmnokdepqrlfg
2073 if unit == 'B': 1hijcabmnokdepqrlfg
2074 return f'{num:0.0f}{separator}{unit}' 1hijcabmnokdepqrlfg
2075 else:
2076 return f'{num:0.1f}{separator}{unit}' 1hijcabmnokdepqrlfg
2077 num /= divisor 1hijcabmnokdepqrlfg
2079 return f'{num:0.1f}{separator}{final_unit}' 1hijcabmnokdepqrlfg
2081 def to(self, unit: str) -> float: 1hijcabmnokdespqrlfg
2082 """Converts a byte size to another unit, including both byte and bit units.
2084 Args:
2085 unit: The unit to convert to. Must be one of the following: B, KB, MB, GB, TB, PB, EB,
2086 KiB, MiB, GiB, TiB, PiB, EiB (byte units) and
2087 bit, kbit, mbit, gbit, tbit, pbit, ebit,
2088 kibit, mibit, gibit, tibit, pibit, eibit (bit units).
2090 Returns:
2091 The byte size in the new unit.
2092 """
2093 try: 1hijcabmnokdepqrlfg
2094 unit_div = self.byte_sizes[unit.lower()] 1hijcabmnokdepqrlfg
2095 except KeyError: 1hijcabmnokdepqrlfg
2096 raise PydanticCustomError('byte_size_unit', 'Could not interpret byte unit: {unit}', {'unit': unit}) 1hijcabmnokdepqrlfg
2098 return self / unit_div 1hijcabmnokdepqrlfg
2101# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATE TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2104def _check_annotated_type(annotated_type: str, expected_type: str, annotation: str) -> None: 1hijcabmnokdespqrlfg
2105 if annotated_type != expected_type: 1hijcabmnokdepqrlfg
2106 raise PydanticUserError(f"'{annotation}' cannot annotate '{annotated_type}'.", code='invalid-annotated-type') 1hijcabmnokdepqrlfg
2109if TYPE_CHECKING: 1hijcabmnokdespqrlfg
2110 PastDate = Annotated[date, ...]
2111 FutureDate = Annotated[date, ...]
2112else:
2114 class PastDate: 1hijcabmnokdespqrlfg
2115 """A date in the past."""
2117 @classmethod 1hijcabmnokdespqrlfg
2118 def __get_pydantic_core_schema__( 1hijcabmnokdespqrlfg
2119 cls, source: type[Any], handler: GetCoreSchemaHandler
2120 ) -> core_schema.CoreSchema:
2121 if cls is source: 1hijcabmnokdepqrlfg
2122 # used directly as a type
2123 return core_schema.date_schema(now_op='past') 1hijcabmnokdepqrlfg
2124 else:
2125 schema = handler(source) 1hijcabmnokdepqrlfg
2126 _check_annotated_type(schema['type'], 'date', cls.__name__) 1hijcabmnokdepqrlfg
2127 schema['now_op'] = 'past' 1hijcabmnokdepqrlfg
2128 return schema 1hijcabmnokdepqrlfg
2130 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
2131 return 'PastDate' 1hijcabmnokdepqrlfg
2133 class FutureDate: 1hijcabmnokdespqrlfg
2134 """A date in the future."""
2136 @classmethod 1hijcabmnokdespqrlfg
2137 def __get_pydantic_core_schema__( 1hijcabmnokdespqrlfg
2138 cls, source: type[Any], handler: GetCoreSchemaHandler
2139 ) -> core_schema.CoreSchema:
2140 if cls is source: 1hijcabmnokdepqrlfg
2141 # used directly as a type
2142 return core_schema.date_schema(now_op='future') 1hijcabmnokdepqrlfg
2143 else:
2144 schema = handler(source) 1hijcabmnokdepqrlfg
2145 _check_annotated_type(schema['type'], 'date', cls.__name__) 1hijcabmnokdepqrlfg
2146 schema['now_op'] = 'future' 1hijcabmnokdepqrlfg
2147 return schema 1hijcabmnokdepqrlfg
2149 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
2150 return 'FutureDate' 1hijcabmnokdepqrlfg
2153def condate( 1hijcabmnokdespqrlfg
2154 *,
2155 strict: bool | None = None,
2156 gt: date | None = None,
2157 ge: date | None = None,
2158 lt: date | None = None,
2159 le: date | None = None,
2160) -> type[date]:
2161 """A wrapper for date that adds constraints.
2163 Args:
2164 strict: Whether to validate the date value in strict mode. Defaults to `None`.
2165 gt: The value must be greater than this. Defaults to `None`.
2166 ge: The value must be greater than or equal to this. Defaults to `None`.
2167 lt: The value must be less than this. Defaults to `None`.
2168 le: The value must be less than or equal to this. Defaults to `None`.
2170 Returns:
2171 A date type with the specified constraints.
2172 """
2173 return Annotated[ # pyright: ignore[reportReturnType] 1hijcabmnokdepqrlfg
2174 date,
2175 Strict(strict) if strict is not None else None,
2176 annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
2177 ]
2180# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATETIME TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2182if TYPE_CHECKING: 1hijcabmnokdespqrlfg
2183 AwareDatetime = Annotated[datetime, ...]
2184 NaiveDatetime = Annotated[datetime, ...]
2185 PastDatetime = Annotated[datetime, ...]
2186 FutureDatetime = Annotated[datetime, ...]
2188else:
2190 class AwareDatetime: 1hijcabmnokdespqrlfg
2191 """A datetime that requires timezone info."""
2193 @classmethod 1hijcabmnokdespqrlfg
2194 def __get_pydantic_core_schema__( 1hijcabmnokdespqrlfg
2195 cls, source: type[Any], handler: GetCoreSchemaHandler
2196 ) -> core_schema.CoreSchema:
2197 if cls is source: 1hijcabmnokdepqrlfg
2198 # used directly as a type
2199 return core_schema.datetime_schema(tz_constraint='aware') 1hijcabmnokdepqrlfg
2200 else:
2201 schema = handler(source) 1hijcabmnokdepqrlfg
2202 _check_annotated_type(schema['type'], 'datetime', cls.__name__) 1hijcabmnokdepqrlfg
2203 schema['tz_constraint'] = 'aware' 1hijcabmnokdepqrlfg
2204 return schema 1hijcabmnokdepqrlfg
2206 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
2207 return 'AwareDatetime' 1hijcabmnokdepqrlfg
2209 class NaiveDatetime: 1hijcabmnokdespqrlfg
2210 """A datetime that doesn't require timezone info."""
2212 @classmethod 1hijcabmnokdespqrlfg
2213 def __get_pydantic_core_schema__( 1hijcabmnokdespqrlfg
2214 cls, source: type[Any], handler: GetCoreSchemaHandler
2215 ) -> core_schema.CoreSchema:
2216 if cls is source: 1hijcabmnokdepqrlfg
2217 # used directly as a type
2218 return core_schema.datetime_schema(tz_constraint='naive') 1hijcabmnokdepqrlfg
2219 else:
2220 schema = handler(source) 1hijcabmnokdepqrlfg
2221 _check_annotated_type(schema['type'], 'datetime', cls.__name__) 1hijcabmnokdepqrlfg
2222 schema['tz_constraint'] = 'naive' 1hijcabmnokdepqrlfg
2223 return schema 1hijcabmnokdepqrlfg
2225 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
2226 return 'NaiveDatetime' 1hijcabmnokdepqrlfg
2228 class PastDatetime: 1hijcabmnokdespqrlfg
2229 """A datetime that must be in the past."""
2231 @classmethod 1hijcabmnokdespqrlfg
2232 def __get_pydantic_core_schema__( 1hijcabmnokdespqrlfg
2233 cls, source: type[Any], handler: GetCoreSchemaHandler
2234 ) -> core_schema.CoreSchema:
2235 if cls is source: 1hijcabmnokdepqrlfg
2236 # used directly as a type
2237 return core_schema.datetime_schema(now_op='past') 1hijcabmnokdepqrlfg
2238 else:
2239 schema = handler(source) 1hijcabmnokdepqrlfg
2240 _check_annotated_type(schema['type'], 'datetime', cls.__name__) 1hijcabmnokdepqrlfg
2241 schema['now_op'] = 'past' 1hijcabmnokdepqrlfg
2242 return schema 1hijcabmnokdepqrlfg
2244 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
2245 return 'PastDatetime' 1hijcabmnokdepqrlfg
2247 class FutureDatetime: 1hijcabmnokdespqrlfg
2248 """A datetime that must be in the future."""
2250 @classmethod 1hijcabmnokdespqrlfg
2251 def __get_pydantic_core_schema__( 1hijcabmnokdespqrlfg
2252 cls, source: type[Any], handler: GetCoreSchemaHandler
2253 ) -> core_schema.CoreSchema:
2254 if cls is source: 1hijcabmnokdepqrlfg
2255 # used directly as a type
2256 return core_schema.datetime_schema(now_op='future') 1hijcabmnokdepqrlfg
2257 else:
2258 schema = handler(source) 1hijcabmnokdepqrlfg
2259 _check_annotated_type(schema['type'], 'datetime', cls.__name__) 1hijcabmnokdepqrlfg
2260 schema['now_op'] = 'future' 1hijcabmnokdepqrlfg
2261 return schema 1hijcabmnokdepqrlfg
2263 def __repr__(self) -> str: 1hijcabmnokdespqrlfg
2264 return 'FutureDatetime' 1hijcabmnokdepqrlfg
2267# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Encoded TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2270class EncoderProtocol(Protocol): 1hijcabmnokdespqrlfg
2271 """Protocol for encoding and decoding data to and from bytes.""" 1hijcabmnokdespqrlfg
2273 @classmethod 1hijcabmnokdespqrlfg
2274 def decode(cls, data: bytes) -> bytes: 1hijcabmnokdespqrlfg
2275 """Decode the data using the encoder.
2277 Args:
2278 data: The data to decode.
2280 Returns:
2281 The decoded data.
2282 """
2283 ...
2285 @classmethod 1hijcabmnokdespqrlfg
2286 def encode(cls, value: bytes) -> bytes: 1hijcabmnokdespqrlfg
2287 """Encode the data using the encoder.
2289 Args:
2290 value: The data to encode.
2292 Returns:
2293 The encoded data.
2294 """
2295 ...
2297 @classmethod 1hijcabmnokdespqrlfg
2298 def get_json_format(cls) -> str: 1hijcabmnokdespqrlfg
2299 """Get the JSON format for the encoded data.
2301 Returns:
2302 The JSON format for the encoded data.
2303 """
2304 ...
2307class Base64Encoder(EncoderProtocol): 1hijcabmnokdespqrlfg
2308 """Standard (non-URL-safe) Base64 encoder."""
2310 @classmethod 1hijcabmnokdespqrlfg
2311 def decode(cls, data: bytes) -> bytes: 1hijcabmnokdespqrlfg
2312 """Decode the data from base64 encoded bytes to original bytes data.
2314 Args:
2315 data: The data to decode.
2317 Returns:
2318 The decoded data.
2319 """
2320 try: 1hijcabmnokdepqrlfg
2321 return base64.b64decode(data) 1hijcabmnokdepqrlfg
2322 except ValueError as e: 1hijcabmnokdepqrlfg
2323 raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)}) 1hijcabmnokdepqrlfg
2325 @classmethod 1hijcabmnokdespqrlfg
2326 def encode(cls, value: bytes) -> bytes: 1hijcabmnokdespqrlfg
2327 """Encode the data from bytes to a base64 encoded bytes.
2329 Args:
2330 value: The data to encode.
2332 Returns:
2333 The encoded data.
2334 """
2335 return base64.b64encode(value) 1hijcabmnokdepqrlfg
2337 @classmethod 1hijcabmnokdespqrlfg
2338 def get_json_format(cls) -> Literal['base64']: 1hijcabmnokdespqrlfg
2339 """Get the JSON format for the encoded data.
2341 Returns:
2342 The JSON format for the encoded data.
2343 """
2344 return 'base64' 1hijcabmnokdepqrlfg
2347_urlsafe_translation = bytes.maketrans(b'+/', b'-_') 1hijcabmnokdespqrlfg
2350class Base64UrlEncoder(EncoderProtocol): 1hijcabmnokdespqrlfg
2351 """URL-safe Base64 encoder."""
2353 @classmethod 1hijcabmnokdespqrlfg
2354 def decode(cls, data: bytes) -> bytes: 1hijcabmnokdespqrlfg
2355 """Decode the data from base64 encoded bytes to original bytes data.
2357 Args:
2358 data: The data to decode.
2360 Returns:
2361 The decoded data.
2362 """
2363 try: 1hijcabmnokdepqrlfg
2364 if sys.version_info >= (3, 15): 1hijcabmnokdepqrlfg
2365 # In Python >= 3.15, `urlsafe_b64decode()` doesn't require padded input anymore.
2366 # It also raises a `FutureWarning` if '+' or '/' is found in input (and translates it
2367 # to '-' and '_'). We can't have this warning raised while validating, so we do the translation
2368 # ourselves.
2369 data = data.translate(_urlsafe_translation) 1abdefg
2370 return base64.urlsafe_b64decode(data, padded=True) 1abdefg
2371 else:
2372 return base64.urlsafe_b64decode(data) 1hijcmnokpqrl
2373 except ValueError as e: 1hijcabmnokdepqrlfg
2374 raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)}) 1hijcabmnokdepqrlfg
2376 @classmethod 1hijcabmnokdespqrlfg
2377 def encode(cls, value: bytes) -> bytes: 1hijcabmnokdespqrlfg
2378 """Encode the data from bytes to a base64 encoded bytes.
2380 Args:
2381 value: The data to encode.
2383 Returns:
2384 The encoded data.
2385 """
2386 return base64.urlsafe_b64encode(value) 1hijcabmnokdepqrlfg
2388 @classmethod 1hijcabmnokdespqrlfg
2389 def get_json_format(cls) -> Literal['base64url']: 1hijcabmnokdespqrlfg
2390 """Get the JSON format for the encoded data.
2392 Returns:
2393 The JSON format for the encoded data.
2394 """
2395 return 'base64url' 1hijcabmnokdepqrlfg
2398@_dataclasses.dataclass(slots=True) 1hijcabmnokdespqrlfg
2399class EncodedBytes: 1hijcabmnokdespqrlfg
2400 """A bytes type that is encoded and decoded using the specified encoder.
2402 `EncodedBytes` needs an encoder that implements `EncoderProtocol` to operate.
2404 ```python
2405 from typing import Annotated
2407 from pydantic import BaseModel, EncodedBytes, EncoderProtocol, ValidationError
2409 class MyEncoder(EncoderProtocol):
2410 @classmethod
2411 def decode(cls, data: bytes) -> bytes:
2412 if data == b'**undecodable**':
2413 raise ValueError('Cannot decode data')
2414 return data[13:]
2416 @classmethod
2417 def encode(cls, value: bytes) -> bytes:
2418 return b'**encoded**: ' + value
2420 @classmethod
2421 def get_json_format(cls) -> str:
2422 return 'my-encoder'
2424 MyEncodedBytes = Annotated[bytes, EncodedBytes(encoder=MyEncoder)]
2426 class Model(BaseModel):
2427 my_encoded_bytes: MyEncodedBytes
2429 # Initialize the model with encoded data
2430 m = Model(my_encoded_bytes=b'**encoded**: some bytes')
2432 # Access decoded value
2433 print(m.my_encoded_bytes)
2434 #> b'some bytes'
2436 # Serialize into the encoded form
2437 print(m.model_dump())
2438 #> {'my_encoded_bytes': b'**encoded**: some bytes'}
2440 # Validate encoded data
2441 try:
2442 Model(my_encoded_bytes=b'**undecodable**')
2443 except ValidationError as e:
2444 print(e)
2445 '''
2446 1 validation error for Model
2447 my_encoded_bytes
2448 Value error, Cannot decode data [type=value_error, input_value=b'**undecodable**', input_type=bytes]
2449 '''
2450 ```
2451 """
2453 encoder: type[EncoderProtocol] 1hijcabmnokdespqrlfg
2455 def __get_pydantic_json_schema__( 1hijcabmnokdespqrlfg
2456 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
2457 ) -> JsonSchemaValue:
2458 field_schema = handler(core_schema) 1hijcabmnokdepqrlfg
2459 field_schema.update(type='string', format=self.encoder.get_json_format()) 1hijcabmnokdepqrlfg
2460 return field_schema 1hijcabmnokdepqrlfg
2462 def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
2463 schema = handler(source) 1hijcabmnokdepqrlfg
2464 _check_annotated_type(schema['type'], 'bytes', self.__class__.__name__) 1hijcabmnokdepqrlfg
2465 return core_schema.with_info_after_validator_function( 1hijcabmnokdepqrlfg
2466 function=self.decode,
2467 schema=schema,
2468 serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode),
2469 )
2471 def decode(self, data: bytes, _: core_schema.ValidationInfo) -> bytes: 1hijcabmnokdespqrlfg
2472 """Decode the data using the specified encoder.
2474 Args:
2475 data: The data to decode.
2477 Returns:
2478 The decoded data.
2479 """
2480 return self.encoder.decode(data) 1hijcabmnokdepqrlfg
2482 def encode(self, value: bytes) -> bytes: 1hijcabmnokdespqrlfg
2483 """Encode the data using the specified encoder.
2485 Args:
2486 value: The data to encode.
2488 Returns:
2489 The encoded data.
2490 """
2491 return self.encoder.encode(value) 1hijcabmnokdepqrlfg
2493 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
2494 return hash(self.encoder) 1hijcabmnokdespqrlfg
2497@_dataclasses.dataclass(slots=True) 1hijcabmnokdespqrlfg
2498class EncodedStr: 1hijcabmnokdespqrlfg
2499 """A str type that is encoded and decoded using the specified encoder.
2501 `EncodedStr` needs an encoder that implements `EncoderProtocol` to operate.
2503 ```python
2504 from typing import Annotated
2506 from pydantic import BaseModel, EncodedStr, EncoderProtocol, ValidationError
2508 class MyEncoder(EncoderProtocol):
2509 @classmethod
2510 def decode(cls, data: bytes) -> bytes:
2511 if data == b'**undecodable**':
2512 raise ValueError('Cannot decode data')
2513 return data[13:]
2515 @classmethod
2516 def encode(cls, value: bytes) -> bytes:
2517 return b'**encoded**: ' + value
2519 @classmethod
2520 def get_json_format(cls) -> str:
2521 return 'my-encoder'
2523 MyEncodedStr = Annotated[str, EncodedStr(encoder=MyEncoder)]
2525 class Model(BaseModel):
2526 my_encoded_str: MyEncodedStr
2528 # Initialize the model with encoded data
2529 m = Model(my_encoded_str='**encoded**: some str')
2531 # Access decoded value
2532 print(m.my_encoded_str)
2533 #> some str
2535 # Serialize into the encoded form
2536 print(m.model_dump())
2537 #> {'my_encoded_str': '**encoded**: some str'}
2539 # Validate encoded data
2540 try:
2541 Model(my_encoded_str='**undecodable**')
2542 except ValidationError as e:
2543 print(e)
2544 '''
2545 1 validation error for Model
2546 my_encoded_str
2547 Value error, Cannot decode data [type=value_error, input_value='**undecodable**', input_type=str]
2548 '''
2549 ```
2550 """
2552 encoder: type[EncoderProtocol] 1hijcabmnokdespqrlfg
2554 def __get_pydantic_json_schema__( 1hijcabmnokdespqrlfg
2555 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
2556 ) -> JsonSchemaValue:
2557 field_schema = handler(core_schema) 1hijcabmnokdepqrlfg
2558 field_schema.update(type='string', format=self.encoder.get_json_format()) 1hijcabmnokdepqrlfg
2559 return field_schema 1hijcabmnokdepqrlfg
2561 def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1hijcabmnokdespqrlfg
2562 schema = handler(source) 1hijcabmnokdepqrlfg
2563 _check_annotated_type(schema['type'], 'str', self.__class__.__name__) 1hijcabmnokdepqrlfg
2564 return core_schema.with_info_after_validator_function( 1hijcabmnokdepqrlfg
2565 function=self.decode_str,
2566 schema=schema,
2567 serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode_str),
2568 )
2570 def decode_str(self, data: str, _: core_schema.ValidationInfo) -> str: 1hijcabmnokdespqrlfg
2571 """Decode the data using the specified encoder.
2573 Args:
2574 data: The data to decode.
2576 Returns:
2577 The decoded data.
2578 """
2579 return self.encoder.decode(data.encode()).decode() 1hijcabmnokdepqrlfg
2581 def encode_str(self, value: str) -> str: 1hijcabmnokdespqrlfg
2582 """Encode the data using the specified encoder.
2584 Args:
2585 value: The data to encode.
2587 Returns:
2588 The encoded data.
2589 """
2590 return self.encoder.encode(value.encode()).decode() # noqa: UP008 1hijcabmnokdepqrlfg
2592 def __hash__(self) -> int: 1hijcabmnokdespqrlfg
2593 return hash(self.encoder) 1hijcabmnokdespqrlfg
2596Base64Bytes = Annotated[bytes, EncodedBytes(encoder=Base64Encoder)] 1hijcabmnokdespqrlfg
2597"""A bytes type that is encoded and decoded using the standard (non-URL-safe) base64 encoder. 1hijcabmnokdespqrlfg
2599Note:
2600 Under the hood, `Base64Bytes` uses the standard library [`base64.b64encode()`][base64.b64encode] and [`base64.b64decode()`][base64.b64decode] functions.
2602 As a result, attempting to decode url-safe base64 data using the `Base64Bytes` type may fail or produce an incorrect
2603 decoding.
2605/// version-changed | v2.10
2606`Base64Bytes` now uses [`base64.b64encode()`][base64.b64encode] and [`base64.b64decode()`][base64.b64decode]
2607instead of [`base64.encodebytes()`][base64.encodebytes] and [`base64.decodebytes()`][base64.decodebytes].
2609These methods are considered legacy implementation. If you'd still like to use these legacy encoders/decoders,
2610you can achieve this by creating a custom annotated type, like follows:
2611```python
2612import base64
2613from typing import Annotated, Literal
2615from pydantic_core import PydanticCustomError
2617from pydantic import EncodedBytes, EncoderProtocol
2619class LegacyBase64Encoder(EncoderProtocol):
2620 @classmethod
2621 def decode(cls, data: bytes) -> bytes:
2622 try:
2623 return base64.decodebytes(data)
2624 except ValueError as e:
2625 raise PydanticCustomError(
2626 'base64_decode',
2627 "Base64 decoding error: '{error}'",
2628 {'error': str(e)},
2629 )
2631 @classmethod
2632 def encode(cls, value: bytes) -> bytes:
2633 return base64.encodebytes(value)
2635 @classmethod
2636 def get_json_format(cls) -> Literal['base64']:
2637 return 'base64'
2639LegacyBase64Bytes = Annotated[bytes, EncodedBytes(encoder=LegacyBase64Encoder)]
2640```
2641///
2643```python
2644from pydantic import Base64Bytes, BaseModel, ValidationError
2646class Model(BaseModel):
2647 base64_bytes: Base64Bytes
2649# Initialize the model with base64 data
2650m = Model(base64_bytes=b'VGhpcyBpcyB0aGUgd2F5')
2652# Access decoded value
2653print(m.base64_bytes)
2654#> b'This is the way'
2656# Serialize into the base64 form
2657print(m.model_dump())
2658#> {'base64_bytes': b'VGhpcyBpcyB0aGUgd2F5'}
2660# Validate base64 data
2661try:
2662 print(Model(base64_bytes=b'undecodable').base64_bytes)
2663except ValidationError as e:
2664 print(e)
2665 '''
2666 1 validation error for Model
2667 base64_bytes
2668 Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value=b'undecodable', input_type=bytes]
2669 '''
2670```
2671"""
2672Base64Str = Annotated[str, EncodedStr(encoder=Base64Encoder)] 1hijcabmnokdespqrlfg
2673"""A string type that is encoded and decoded using the standard (non-URL-safe) base64 encoder. 1hijcabmnokdespqrlfg
2675Note:
2676 Under the hood, `Base64Str` uses the standard library [`base64.b64encode()`][base64.b64encode] and [`base64.b64decode()`][base64.b64decode] functions.
2678 As a result, attempting to decode url-safe base64 data using the `Base64Str` type may fail or produce an incorrect
2679 decoding.
2681/// version-changed | v2.10
2682`Base64Str` now uses [`base64.b64encode()`][base64.b64encode] and [`base64.b64decode()`][base64.b64decode]
2683instead of [`base64.encodebytes()`][base64.encodebytes] and [`base64.decodebytes()`][base64.decodebytes].
2685These methods are considered legacy implementation. See the documentation about the [`Base64Bytes`][pydantic.types.Base64Bytes] type
2686for more information on how to replicate the old behavior with the legacy encoders/decoders.
2687///
2690```python
2691from pydantic import Base64Str, BaseModel, ValidationError
2693class Model(BaseModel):
2694 base64_str: Base64Str
2696# Initialize the model with base64 data
2697m = Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y')
2699# Access decoded value
2700print(m.base64_str)
2701#> These aren't the droids you're looking for
2703# Serialize into the base64 form
2704print(m.model_dump())
2705#> {'base64_str': 'VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y'}
2707# Validate base64 data
2708try:
2709 print(Model(base64_str='undecodable').base64_str)
2710except ValidationError as e:
2711 print(e)
2712 '''
2713 1 validation error for Model
2714 base64_str
2715 Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value='undecodable', input_type=str]
2716 '''
2717```
2718"""
2719Base64UrlBytes = Annotated[bytes, EncodedBytes(encoder=Base64UrlEncoder)] 1hijcabmnokdespqrlfg
2720"""A bytes type that is encoded and decoded using the URL-safe base64 encoder. 1hijcabmnokdespqrlfg
2722Note:
2723 Under the hood, `Base64UrlBytes` uses the standard library [`base64.urlsafe_b64encode()`][base64.urlsafe_b64encode]
2724 and [`base64.urlsafe_b64decode()`][base64.urlsafe_b64decode] functions.
2726```python
2727from pydantic import Base64UrlBytes, BaseModel
2729class Model(BaseModel):
2730 base64url_bytes: Base64UrlBytes
2732# Initialize the model with base64 data
2733m = Model(base64url_bytes=b'SHc_dHc-TXc==')
2734print(m)
2735#> base64url_bytes=b'Hw?tw>Mw'
2736```
2737"""
2738Base64UrlStr = Annotated[str, EncodedStr(encoder=Base64UrlEncoder)] 1hijcabmnokdespqrlfg
2739"""A str type that is encoded and decoded using the URL-safe base64 encoder. 1hijcabmnokdespqrlfg
2741Note:
2742 Under the hood, `Base64UrlStr` uses the standard library [`base64.urlsafe_b64encode()`][base64.urlsafe_b64encode]
2743 and [`base64.urlsafe_b64decode()`][base64.urlsafe_b64decode] functions.
2745```python
2746from pydantic import Base64UrlStr, BaseModel
2748class Model(BaseModel):
2749 base64url_str: Base64UrlStr
2751# Initialize the model with base64 data
2752m = Model(base64url_str='SHc_dHc-TXc==')
2753print(m)
2754#> base64url_str='Hw?tw>Mw'
2755```
2756"""
2759@_dataclasses.dataclass(slots=True) 1hijcabmnokdespqrlfg
2760class GetPydanticSchema: 1hijcabmnokdespqrlfg
2761 """!!! abstract "Usage Documentation"
2762 [Using `GetPydanticSchema` to Reduce Boilerplate](../concepts/types.md#using-getpydanticschema-to-reduce-boilerplate)
2764 A convenience class for creating an annotation that provides pydantic custom type hooks.
2766 This class is intended to eliminate the need to create a custom "marker" which defines the
2767 `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__` custom hook methods.
2769 For example, to have a field treated by type checkers as `int`, but by pydantic as `Any`, you can do:
2770 ```python
2771 from typing import Annotated, Any
2773 from pydantic import BaseModel, GetPydanticSchema
2775 HandleAsAny = GetPydanticSchema(lambda _s, h: h(Any))
2777 class Model(BaseModel):
2778 x: Annotated[int, HandleAsAny] # pydantic sees `x: Any`
2780 print(repr(Model(x='abc').x))
2781 #> 'abc'
2782 ```
2783 """
2785 get_pydantic_core_schema: Callable[[Any, GetCoreSchemaHandler], CoreSchema] | None = None 1hijcabmnokdespqrlfg
2786 get_pydantic_json_schema: Callable[[Any, GetJsonSchemaHandler], JsonSchemaValue] | None = None 1hijcabmnokdespqrlfg
2788 # Note: we may want to consider adding a convenience staticmethod `def for_type(type_: Any) -> GetPydanticSchema:`
2789 # which returns `GetPydanticSchema(lambda _s, h: h(type_))`
2791 if not TYPE_CHECKING: 2791 ↛ 2803line 2791 didn't jump to line 2803 because the condition on line 2791 was always true1hijcabmnokdespqrlfg
2792 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
2794 def __getattr__(self, item: str) -> Any: 1hijcabmnokdespqrlfg
2795 """Use this rather than defining `__get_pydantic_core_schema__` etc. to reduce the number of nested calls."""
2796 if item == '__get_pydantic_core_schema__' and self.get_pydantic_core_schema: 1hijcabmnokdepqrlfg
2797 return self.get_pydantic_core_schema 1hijcabmnokdepqrlfg
2798 elif item == '__get_pydantic_json_schema__' and self.get_pydantic_json_schema: 2798 ↛ 2799line 2798 didn't jump to line 2799 because the condition on line 2798 was never true1hijcabmnokdepqrlfg
2799 return self.get_pydantic_json_schema
2800 else:
2801 return object.__getattribute__(self, item) 1hijcabmnokdepqrlfg
2803 __hash__ = object.__hash__ 1hijcabmnokdespqrlfg
2806@_dataclasses.dataclass(slots=True, frozen=True) 1hijcabmnokdespqrlfg
2807class Tag: 1hijcabmnokdespqrlfg
2808 """Provides a way to specify the expected tag to use for a case of a (callable) discriminated union.
2810 Also provides a way to label a union case in error messages.
2812 When using a callable `Discriminator`, attach a `Tag` to each case in the union to specify the tag that
2813 should be used to identify that case. For example, in the below example, the `Tag` is used to specify that
2814 if `get_discriminator_value` returns `'apple'`, the input should be validated as an `ApplePie`, and if it
2815 returns `'pumpkin'`, the input should be validated as a `PumpkinPie`.
2817 The primary role of the `Tag` here is to map the return value from the callable `Discriminator` function to
2818 the appropriate member of the union in question.
2820 ```python {lint="skip"}
2821 from typing import Annotated, Any, Literal
2823 from pydantic import BaseModel, Discriminator, Tag
2825 class Pie(BaseModel):
2826 time_to_cook: int
2827 num_ingredients: int
2829 class ApplePie(Pie):
2830 fruit: Literal['apple'] = 'apple'
2832 class PumpkinPie(Pie):
2833 filling: Literal['pumpkin'] = 'pumpkin'
2835 def get_discriminator_value(v: Any) -> str:
2836 if isinstance(v, dict):
2837 return v.get('fruit', v.get('filling'))
2838 return getattr(v, 'fruit', getattr(v, 'filling', None))
2840 class ThanksgivingDinner(BaseModel):
2841 dessert: Annotated[
2842 Annotated[ApplePie, Tag('apple')] | Annotated[PumpkinPie, Tag('pumpkin')],
2843 Discriminator(get_discriminator_value),
2844 ]
2846 apple_variation = ThanksgivingDinner.model_validate(
2847 {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
2848 )
2849 print(repr(apple_variation))
2850 '''
2851 ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
2852 '''
2854 pumpkin_variation = ThanksgivingDinner.model_validate(
2855 {
2856 'dessert': {
2857 'filling': 'pumpkin',
2858 'time_to_cook': 40,
2859 'num_ingredients': 6,
2860 }
2861 }
2862 )
2863 print(repr(pumpkin_variation))
2864 '''
2865 ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
2866 '''
2867 ```
2869 !!! note
2870 You must specify a `Tag` for every case in a `Tag` that is associated with a
2871 callable `Discriminator`. Failing to do so will result in a `PydanticUserError` with code
2872 [`callable-discriminator-no-tag`](../errors/usage_errors.md#callable-discriminator-no-tag).
2874 See the [Discriminated Unions] concepts docs for more details on how to use `Tag`s.
2876 [Discriminated Unions]: ../concepts/unions.md#discriminated-unions
2877 """
2879 tag: str 1hijcabmnokdespqrlfg
2881 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: 1hijcabmnokdespqrlfg
2882 schema = handler(source_type) 1hijcabmnokdepqrlfg
2883 metadata = cast('CoreMetadata', schema.setdefault('metadata', {})) 1hijcabmnokdepqrlfg
2884 metadata['pydantic_internal_union_tag_key'] = self.tag 1hijcabmnokdepqrlfg
2885 return schema 1hijcabmnokdepqrlfg
2888@_dataclasses.dataclass(slots=True, frozen=True) 1hijcabmnokdespqrlfg
2889class Discriminator: 1hijcabmnokdespqrlfg
2890 """!!! abstract "Usage Documentation"
2891 [Discriminated Unions with `Callable` `Discriminator`](../concepts/unions.md#discriminated-unions-with-callable-discriminator)
2893 Provides a way to use a custom callable as the way to extract the value of a union discriminator.
2895 This allows you to get validation behavior like you'd get from `Field(discriminator=<field_name>)`,
2896 but without needing to have a single shared field across all the union choices. This also makes it
2897 possible to handle unions of models and primitive types with discriminated-union-style validation errors.
2898 Finally, this allows you to use a custom callable as the way to identify which member of a union a value
2899 belongs to, while still seeing all the performance benefits of a discriminated union.
2901 Consider this example, which is much more performant with the use of `Discriminator` and thus a `TaggedUnion`
2902 than it would be as a normal union.
2904 ```python {lint="skip"}
2905 from typing import Annotated, Any, Literal
2907 from pydantic import BaseModel, Discriminator, Tag
2909 class Pie(BaseModel):
2910 time_to_cook: int
2911 num_ingredients: int
2913 class ApplePie(Pie):
2914 fruit: Literal['apple'] = 'apple'
2916 class PumpkinPie(Pie):
2917 filling: Literal['pumpkin'] = 'pumpkin'
2919 def get_discriminator_value(v: Any) -> str:
2920 if isinstance(v, dict):
2921 return v.get('fruit', v.get('filling'))
2922 return getattr(v, 'fruit', getattr(v, 'filling', None))
2924 class ThanksgivingDinner(BaseModel):
2925 dessert: Annotated[
2926 Annotated[ApplePie, Tag('apple')] | Annotated[PumpkinPie, Tag('pumpkin')],
2927 Discriminator(get_discriminator_value),
2928 ]
2930 apple_variation = ThanksgivingDinner.model_validate(
2931 {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
2932 )
2933 print(repr(apple_variation))
2934 '''
2935 ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
2936 '''
2938 pumpkin_variation = ThanksgivingDinner.model_validate(
2939 {
2940 'dessert': {
2941 'filling': 'pumpkin',
2942 'time_to_cook': 40,
2943 'num_ingredients': 6,
2944 }
2945 }
2946 )
2947 print(repr(pumpkin_variation))
2948 '''
2949 ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
2950 '''
2951 ```
2953 See the [Discriminated Unions] concepts docs for more details on how to use `Discriminator`s.
2955 [Discriminated Unions]: ../concepts/unions.md#discriminated-unions
2956 """
2958 discriminator: str | Callable[[Any], Hashable] 1hijcabmnokdespqrlfg
2959 """The callable or field name for discriminating the type in a tagged union. 1hijcabmnokdespqrlfg
2961 A `Callable` discriminator must extract the value of the discriminator from the input.
2962 A `str` discriminator must be the name of a field to discriminate against.
2963 """
2964 custom_error_type: str | None = None 1hijcabmnokdespqrlfg
2965 """Type to use in [custom errors](../errors/errors.md) replacing the standard discriminated union 1hijcabmnokdespqrlfg
2966 validation errors.
2967 """
2968 custom_error_message: str | None = None 1hijcabmnokdespqrlfg
2969 """Message to use in custom errors.""" 1hijcabmnokdespqrlfg
2970 custom_error_context: dict[str, int | str | float] | None = None 1hijcabmnokdespqrlfg
2971 """Context to use in custom errors.""" 1hijcabmnokdespqrlfg
2973 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: 1hijcabmnokdespqrlfg
2974 if isinstance(self.discriminator, str): 1hijcabmnokdepqrlfg
2975 from pydantic import Field 1hijcabmnokdepqrlfg
2977 return handler(Annotated[source_type, Field(discriminator=self.discriminator)]) 1hijcabmnokdepqrlfg
2978 else:
2979 original_schema = handler(source_type) 1hijcabmnokdepqrlfg
2980 return self._convert_schema(original_schema, handler) 1hijcabmnokdepqrlfg
2982 def _convert_schema( 1hijcabmnokdespqrlfg
2983 self,
2984 original_schema: core_schema.CoreSchema,
2985 handler: GetCoreSchemaHandler | None = None,
2986 definitions: dict[str, core_schema.CoreSchema] | None = None,
2987 ) -> core_schema.TaggedUnionSchema:
2988 def _resolve_ref(schema: core_schema.CoreSchema) -> core_schema.CoreSchema | None: 1hijcabmnokdepqrlfg
2989 # `handler` is set when this method is called while generating the schema for the field
2990 # (e.g. via `Annotated[<type>, Discriminator(...)]`). `definitions` is set instead when
2991 # this method is called from `apply_discriminator()` (deferred/callable discriminators).
2992 if handler is not None: 1hijcabmnokdepqrlfg
2993 try: 1hijcabmnokdepqrlfg
2994 return handler.resolve_ref_schema(schema) 1hijcabmnokdepqrlfg
2995 except LookupError: # pragma: no cover 1hijcabmnokdepqrlfg
2996 return None 1hijcabmnokdepqrlfg
2997 elif definitions is not None: 2997 ↛ 3000line 2997 didn't jump to line 3000 because the condition on line 2997 was always true1hijcabmnokdepqrlfg
2998 schema_ref = cast(core_schema.DefinitionReferenceSchema, schema)['schema_ref'] 1hijcabmnokdepqrlfg
2999 return definitions.get(schema_ref) 1hijcabmnokdepqrlfg
3000 return None
3002 if original_schema['type'] == 'definition-ref': 1hijcabmnokdepqrlfg
3003 # Same logic as `_ApplyInferredDiscriminator._apply_to_root()`
3004 def_schema = _resolve_ref(original_schema) 1hijcabmnokdepqrlfg
3005 if def_schema is None: 3005 ↛ 3006line 3005 didn't jump to line 3006 because the condition on line 3005 was never true1hijcabmnokdepqrlfg
3006 from pydantic._internal._discriminated_union import MissingDefinitionForUnionRef
3008 raise MissingDefinitionForUnionRef(original_schema['schema_ref'])
3010 # If using a referenceable union as discriminated (e.g. `type Pet = Cat | Dog; field: Pet = Field(discriminator=...)`):
3011 if def_schema['type'] == 'union': 3011 ↛ 3015line 3011 didn't jump to line 3015 because the condition on line 3011 was always true1hijcabmnokdepqrlfg
3012 original_schema = def_schema.copy() 1hijcabmnokdepqrlfg
3013 original_schema.pop('ref') 1hijcabmnokdepqrlfg
3015 if original_schema['type'] != 'union': 3015 ↛ 3020line 3015 didn't jump to line 3020 because the condition on line 3015 was never true1hijcabmnokdepqrlfg
3016 # This likely indicates that the schema was a single-item union that was simplified.
3017 # In this case, we do the same thing we do in
3018 # `pydantic._internal._discriminated_union._ApplyInferredDiscriminator._apply_to_root`, namely,
3019 # package the generated schema back into a single-item union.
3020 original_schema = core_schema.union_schema([original_schema])
3022 tagged_union_choices = {} 1hijcabmnokdepqrlfg
3023 for choice in original_schema['choices']: 1hijcabmnokdepqrlfg
3024 tag = None 1hijcabmnokdepqrlfg
3025 if isinstance(choice, tuple): 1hijcabmnokdepqrlfg
3026 choice, tag = choice 1hijcabmnokdepqrlfg
3027 metadata = cast('CoreMetadata | None', choice.get('metadata')) 1hijcabmnokdepqrlfg
3028 if metadata is not None: 1hijcabmnokdepqrlfg
3029 tag = metadata.get('pydantic_internal_union_tag_key') or tag 1hijcabmnokdepqrlfg
3030 if tag is None: 1hijcabmnokdepqrlfg
3031 if choice['type'] == 'definition-ref': 1hijcabmnokdepqrlfg
3032 # If choice was built from a PEP 695 type alias, try to resolve the def:
3033 resolved_choice = _resolve_ref(choice) 1hijcabmnokdepqrlfg
3034 if resolved_choice is not None: 1hijcabmnokdepqrlfg
3035 choice = resolved_choice 1hijcabmnokdepqrlfg
3036 metadata = cast('CoreMetadata | None', choice.get('metadata')) 1hijcabmnokdepqrlfg
3037 if metadata is not None: 3037 ↛ 3040line 3037 didn't jump to line 3040 because the condition on line 3037 was always true1hijcabmnokdepqrlfg
3038 tag = metadata.get('pydantic_internal_union_tag_key') 1hijcabmnokdepqrlfg
3040 if tag is None: 1hijcabmnokdepqrlfg
3041 raise PydanticUserError( 1hijcabmnokdepqrlfg
3042 f'`Tag` not provided for choice {choice} used with `Discriminator`',
3043 code='callable-discriminator-no-tag',
3044 )
3045 tagged_union_choices[tag] = choice 1hijcabmnokdepqrlfg
3047 # Have to do these verbose checks to ensure falsy values ('' and {}) don't get ignored
3048 custom_error_type = self.custom_error_type 1hijcabmnokdepqrlfg
3049 if custom_error_type is None: 1hijcabmnokdepqrlfg
3050 custom_error_type = original_schema.get('custom_error_type') 1hijcabmnokdepqrlfg
3052 custom_error_message = self.custom_error_message 1hijcabmnokdepqrlfg
3053 if custom_error_message is None: 1hijcabmnokdepqrlfg
3054 custom_error_message = original_schema.get('custom_error_message') 1hijcabmnokdepqrlfg
3056 custom_error_context = self.custom_error_context 1hijcabmnokdepqrlfg
3057 if custom_error_context is None: 1hijcabmnokdepqrlfg
3058 custom_error_context = original_schema.get('custom_error_context') 1hijcabmnokdepqrlfg
3060 custom_error_type = original_schema.get('custom_error_type') if custom_error_type is None else custom_error_type 1hijcabmnokdepqrlfg
3061 return core_schema.tagged_union_schema( 1hijcabmnokdepqrlfg
3062 tagged_union_choices,
3063 self.discriminator,
3064 custom_error_type=custom_error_type,
3065 custom_error_message=custom_error_message,
3066 custom_error_context=custom_error_context,
3067 strict=original_schema.get('strict'),
3068 ref=original_schema.get('ref'),
3069 metadata=original_schema.get('metadata'),
3070 serialization=original_schema.get('serialization'),
3071 )
3074_JSON_TYPES = {int, float, str, bool, list, dict, type(None)} 1hijcabmnokdespqrlfg
3077def _get_type_name(x: Any) -> str: 1hijcabmnokdespqrlfg
3078 type_ = type(x) 1hijcabmnokdepqrlfg
3079 if type_ in _JSON_TYPES: 1hijcabmnokdepqrlfg
3080 return type_.__name__ 1hijcabmnokdepqrlfg
3082 # Handle proper subclasses; note we don't need to handle None or bool here
3083 if isinstance(x, int): 1hijcabmnokdepqrlfg
3084 return 'int' 1hijcabmnokdepqrlfg
3085 if isinstance(x, float): 1hijcabmnokdepqrlfg
3086 return 'float' 1hijcabmnokdepqrlfg
3087 if isinstance(x, str): 1hijcabmnokdepqrlfg
3088 return 'str' 1hijcabmnokdepqrlfg
3089 if isinstance(x, list): 1hijcabmnokdepqrlfg
3090 return 'list' 1hijcabmnokdepqrlfg
3091 if isinstance(x, dict): 1hijcabmnokdepqrlfg
3092 return 'dict' 1hijcabmnokdepqrlfg
3094 # Fail by returning the type's actual name
3095 return getattr(type_, '__name__', '<no type name>') 1hijcabmnokdepqrlfg
3098class _AllowAnyJson: 1hijcabmnokdespqrlfg
3099 @classmethod 1hijcabmnokdespqrlfg
3100 def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: 1hijcabmnokdespqrlfg
3101 python_schema = handler(source_type) 1hijcabmnokdepqrlfg
3102 return core_schema.json_or_python_schema( 1hijcabmnokdepqrlfg
3103 json_schema=core_schema.any_schema(),
3104 python_schema=python_schema,
3105 # Valid JSON values are serialized identically by inference, which avoids the overhead
3106 # of the tagged union serializer (and its Python discriminator function) in Python mode:
3107 serialization=core_schema.simple_ser_schema('any'),
3108 )
3111if TYPE_CHECKING: 1hijcabmnokdespqrlfg
3112 # This seems to only be necessary for mypy
3113 JsonValue: TypeAlias = 'list[JsonValue] | dict[str, JsonValue] | str | bool | int | float | None'
3114 """A `JsonValue` is used to represent a value that can be serialized to JSON.
3116 It may be one of:
3118 * `list['JsonValue']`
3119 * `dict[str, 'JsonValue']`
3120 * `str`
3121 * `bool`
3122 * `int`
3123 * `float`
3124 * `None`
3126 The following example demonstrates how to use `JsonValue` to validate JSON data,
3127 and what kind of errors to expect when input data is not json serializable.
3129 ```python
3130 import json
3132 from pydantic import BaseModel, JsonValue, ValidationError
3134 class Model(BaseModel):
3135 j: JsonValue
3137 valid_json_data = {'j': {'a': {'b': {'c': 1, 'd': [2, None]}}}}
3138 invalid_json_data = {'j': {'a': {'b': ...}}}
3140 print(repr(Model.model_validate(valid_json_data)))
3141 #> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})
3142 print(repr(Model.model_validate_json(json.dumps(valid_json_data))))
3143 #> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})
3145 try:
3146 Model.model_validate(invalid_json_data)
3147 except ValidationError as e:
3148 print(e)
3149 '''
3150 1 validation error for Model
3151 j.dict.a.dict.b
3152 input was not a valid JSON value [type=invalid-json-value, input_value=Ellipsis, input_type=ellipsis]
3153 '''
3154 ```
3155 """
3157else:
3158 JsonValue = TypeAliasType( 1hijcabmnokdespqrlfg
3159 'JsonValue',
3160 Annotated[
3161 Annotated[list['JsonValue'], Tag('list')]
3162 | Annotated[dict[str, 'JsonValue'], Tag('dict')]
3163 | Annotated[str, Tag('str')]
3164 | Annotated[bool, Tag('bool')]
3165 | Annotated[int, Tag('int')]
3166 | Annotated[float, Tag('float')]
3167 | Annotated[None, Tag('NoneType')],
3168 Discriminator(
3169 _get_type_name,
3170 custom_error_type='invalid-json-value',
3171 custom_error_message='input was not a valid JSON value',
3172 ),
3173 _AllowAnyJson,
3174 ],
3175 )
3178class _OnErrorOmit: 1hijcabmnokdespqrlfg
3179 @classmethod 1hijcabmnokdespqrlfg
3180 def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: 1hijcabmnokdespqrlfg
3181 # there is no actual default value here but we use with_default_schema since it already has the on_error
3182 # behavior implemented and it would be no more efficient to implement it on every other validator
3183 # or as a standalone validator
3184 return core_schema.with_default_schema(schema=handler(source_type), on_error='omit') 1hijcabmnokdepqrlfg
3187OnErrorOmit = Annotated[T, _OnErrorOmit] 1hijcabmnokdespqrlfg
3188"""Discard the invalid items of a collection instead of failing validation. 1hijcabmnokdespqrlfg
3190/// version-added | v2.6
3191///
3193By default, when an item of a collection (such as a list, a dictionary or a [`TypedDict`][typing.TypedDict])
3194fails validation, a [`ValidationError`][pydantic_core.ValidationError] is raised and the whole collection is
3195discarded. This annotation changes this behavior: any item failing validation is silently omitted from the
3196result, and the valid ones are kept.
3198It can be applied to:
3200* the item type of an iterable (e.g. `list[OnErrorOmit[int]]`, `tuple[OnErrorOmit[int], ...]`).
3201* the key and/or value types of a mapping (e.g. `dict[OnErrorOmit[int], str]`). If either the key or the value of
3202 an entry fails validation, the whole entry is omitted.
3203* the value type of a [*not required*][typing.NotRequired] [`TypedDict`][typing.TypedDict] key.
3204 Using it on a required key is not allowed, as it would make the key effectively optional.
3206```python
3207from typing_extensions import NotRequired, TypedDict
3209from pydantic import BaseModel, OnErrorOmit
3211OmittableInt = OnErrorOmit[int]
3213class Settings(TypedDict):
3214 timeout: NotRequired[OmittableInt]
3216class Model(BaseModel):
3217 ids: list[OmittableInt]
3218 scores: dict[str, OnErrorOmit[float]]
3219 settings: Settings
3221model = Model(
3222 ids=[1, 2, 'a', 3],
3223 scores={'a': 1.5, 'b': 'invalid'},
3224 settings={'timeout': 'invalid'},
3225)
3226print(model)
3227#> ids=[1, 2, 3] scores={'a': 1.5} settings={}
3228```
3230!!! note
3231 The omitted items are discarded silently: no error is reported and there is no way to know
3232 which items were invalid. If you need to keep track of them, use a
3233 [wrap validator](../concepts/validators.md#field-wrap-validator) instead.
3235!!! warning
3236 `OnErrorOmit` is only meaningful when the annotated type is part of a collection.
3237 Using it on a top-level type (e.g. `TypeAdapter(OnErrorOmit[int])`) or on a model field is not supported.
3238"""
3241@_dataclasses.dataclass 1hijcabmnokdespqrlfg
3242class FailFast(_fields.PydanticMetadata, BaseMetadata): 1hijcabmnokdespqrlfg
3243 """Stop validating a collection at the first invalid item, instead of collecting the errors of every item.
3245 /// version-added | v2.8
3246 ///
3248 By default, when validating a collection, Pydantic validates every item and reports all the errors
3249 at once. This annotation can be applied to a collection type (such as a [`list`][], a [`tuple`][],
3250 a [`set`][] or a [`dict`][]) to stop as soon as an item fails validation.
3252 This can be useful when you want to validate a large amount of data and you only need to know if it's valid or not:
3253 validation will be faster, with the caveat that you get less information about the errors.
3255 ```python
3256 from typing import Annotated
3258 from pydantic import BaseModel, FailFast, ValidationError
3260 class Model(BaseModel):
3261 x: Annotated[list[int], FailFast()]
3263 # This will raise a single error for the first invalid value and stop validation
3264 try:
3265 obj = Model(x=[1, 2, 'a', 4, 5, 'b', 7, 8, 9, 'c'])
3266 except ValidationError as e:
3267 print(e)
3268 '''
3269 1 validation error for Model
3270 x.2
3271 Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
3272 '''
3273 ```
3274 """
3276 fail_fast: bool = True 1hijcabmnokdespqrlfg