-
Notifications
You must be signed in to change notification settings - Fork 229
/
_pydantic_core.pyi
901 lines (783 loc) · 34.4 KB
/
_pydantic_core.pyi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
import datetime
from typing import Any, Callable, Generic, Literal, TypeVar, final
from _typeshed import SupportsAllComparisons
from typing_extensions import LiteralString, Self, TypeAlias
from pydantic_core import ErrorDetails, ErrorTypeInfo, InitErrorDetails, MultiHostHost
from pydantic_core.core_schema import CoreConfig, CoreSchema, ErrorType
__all__ = [
'__version__',
'build_profile',
'build_info',
'_recursion_limit',
'ArgsKwargs',
'SchemaValidator',
'SchemaSerializer',
'Url',
'MultiHostUrl',
'SchemaError',
'ValidationError',
'PydanticCustomError',
'PydanticKnownError',
'PydanticOmit',
'PydanticUseDefault',
'PydanticSerializationError',
'PydanticSerializationUnexpectedValue',
'PydanticUndefined',
'PydanticUndefinedType',
'Some',
'to_json',
'from_json',
'to_jsonable_python',
'list_all_errors',
'TzInfo',
'validate_core_schema',
]
__version__: str
build_profile: str
build_info: str
_recursion_limit: int
_T = TypeVar('_T', default=Any, covariant=True)
_StringInput: TypeAlias = 'dict[str, _StringInput]'
@final
class Some(Generic[_T]):
"""
Similar to Rust's [`Option::Some`](https://doc.rust-lang.org/std/option/enum.Option.html) type, this
identifies a value as being present, and provides a way to access it.
Generally used in a union with `None` to different between "some value which could be None" and no value.
"""
__match_args__ = ('value',)
@property
def value(self) -> _T:
"""
Returns the value wrapped by `Some`.
"""
@classmethod
def __class_getitem__(cls, item: Any, /) -> type[Self]: ...
@final
class SchemaValidator:
"""
`SchemaValidator` is the Python wrapper for `pydantic-core`'s Rust validation logic, internally it owns one
`CombinedValidator` which may in turn own more `CombinedValidator`s which make up the full schema validator.
"""
def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self:
"""
Create a new SchemaValidator.
Arguments:
schema: The [`CoreSchema`][pydantic_core.core_schema.CoreSchema] to use for validation.
config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to configure validation.
"""
@property
def title(self) -> str:
"""
The title of the schema, as used in the heading of [`ValidationError.__str__()`][pydantic_core.ValidationError].
"""
def validate_python(
self,
input: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
self_instance: Any | None = None,
) -> Any:
"""
Validate a Python object against the schema and return the validated object.
Arguments:
input: The Python object to validate.
strict: Whether to validate the object in strict mode.
If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
from_attributes: Whether to validate objects as inputs to models by extracting attributes.
If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used.
context: The context to use for validation, this is passed to functional validators as
[`info.context`][pydantic_core.core_schema.ValidationInfo.context].
self_instance: An instance of a model set attributes on from validation, this is used when running
validation from the `__init__` method of a model.
Raises:
ValidationError: If validation fails.
Exception: Other error types maybe raised if internal errors occur.
Returns:
The validated object.
"""
def isinstance_python(
self,
input: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
self_instance: Any | None = None,
) -> bool:
"""
Similar to [`validate_python()`][pydantic_core.SchemaValidator.validate_python] but returns a boolean.
Arguments match `validate_python()`. This method will not raise `ValidationError`s but will raise internal
errors.
Returns:
`True` if validation succeeds, `False` if validation fails.
"""
def validate_json(
self,
input: str | bytes | bytearray,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
self_instance: Any | None = None,
) -> Any:
"""
Validate JSON data directly against the schema and return the validated Python object.
This method should be significantly faster than `validate_python(json.loads(json_data))` as it avoids the
need to create intermediate Python objects
It also handles constructing the correct Python type even in strict mode, where
`validate_python(json.loads(json_data))` would fail validation.
Arguments:
input: The JSON data to validate.
strict: Whether to validate the object in strict mode.
If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
context: The context to use for validation, this is passed to functional validators as
[`info.context`][pydantic_core.core_schema.ValidationInfo.context].
self_instance: An instance of a model set attributes on from validation.
Raises:
ValidationError: If validation fails or if the JSON data is invalid.
Exception: Other error types maybe raised if internal errors occur.
Returns:
The validated Python object.
"""
def validate_strings(
self, input: _StringInput, *, strict: bool | None = None, context: dict[str, Any] | None = None
) -> Any:
"""
Validate a string against the schema and return the validated Python object.
This is similar to `validate_json` but applies to scenarios where the input will be a string but not
JSON data, e.g. URL fragments, query parameters, etc.
Arguments:
input: The input as a string, or bytes/bytearray if `strict=False`.
strict: Whether to validate the object in strict mode.
If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
context: The context to use for validation, this is passed to functional validators as
[`info.context`][pydantic_core.core_schema.ValidationInfo.context].
Raises:
ValidationError: If validation fails or if the JSON data is invalid.
Exception: Other error types maybe raised if internal errors occur.
Returns:
The validated Python object.
"""
def validate_assignment(
self,
obj: Any,
field_name: str,
field_value: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]]:
"""
Validate an assignment to a field on a model.
Arguments:
obj: The model instance being assigned to.
field_name: The name of the field to validate assignment for.
field_value: The value to assign to the field.
strict: Whether to validate the object in strict mode.
If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
from_attributes: Whether to validate objects as inputs to models by extracting attributes.
If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used.
context: The context to use for validation, this is passed to functional validators as
[`info.context`][pydantic_core.core_schema.ValidationInfo.context].
Raises:
ValidationError: If validation fails.
Exception: Other error types maybe raised if internal errors occur.
Returns:
Either the model dict or a tuple of `(model_data, model_extra, fields_set)`
"""
def get_default_value(self, *, strict: bool | None = None, context: Any = None) -> Some | None:
"""
Get the default value for the schema, including running default value validation.
Arguments:
strict: Whether to validate the default value in strict mode.
If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
context: The context to use for validation, this is passed to functional validators as
[`info.context`][pydantic_core.core_schema.ValidationInfo.context].
Raises:
ValidationError: If validation fails.
Exception: Other error types maybe raised if internal errors occur.
Returns:
`None` if the schema has no default value, otherwise a [`Some`][pydantic_core.Some] containing the default.
"""
_IncEx: TypeAlias = set[int] | set[str] | dict[int, _IncEx] | dict[str, _IncEx] | None
@final
class SchemaSerializer:
"""
`SchemaSerializer` is the Python wrapper for `pydantic-core`'s Rust serialization logic, internally it owns one
`CombinedSerializer` which may in turn own more `CombinedSerializer`s which make up the full schema serializer.
"""
def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self:
"""
Create a new SchemaSerializer.
Arguments:
schema: The [`CoreSchema`][pydantic_core.core_schema.CoreSchema] to use for serialization.
config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to to configure serialization.
"""
def to_python(
self,
value: Any,
*,
mode: str | None = None,
include: _IncEx = None,
exclude: _IncEx = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: dict[str, Any] | None = None,
) -> Any:
"""
Serialize/marshal a Python object to a Python object including transforming and filtering data.
Arguments:
value: The Python object to serialize.
mode: The serialization mode to use, either `'python'` or `'json'`, defaults to `'python'`. In JSON mode,
all values are converted to JSON compatible types, e.g. `None`, `int`, `float`, `str`, `list`, `dict`.
include: A set of fields to include, if `None` all fields are included.
exclude: A set of fields to exclude, if `None` no fields are excluded.
by_alias: Whether to use the alias names of fields.
exclude_unset: Whether to exclude fields that are not set,
e.g. are not included in `__pydantic_fields_set__`.
exclude_defaults: Whether to exclude fields that are equal to their default value.
exclude_none: Whether to exclude fields that have a value of `None`.
round_trip: Whether to enable serialization and validation round-trip support.
warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
"error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
fallback: A function to call when an unknown value is encountered,
if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
context: The context to use for serialization, this is passed to functional serializers as
[`info.context`][pydantic_core.core_schema.SerializationInfo.context].
Raises:
PydanticSerializationError: If serialization fails and no `fallback` function is provided.
Returns:
The serialized Python object.
"""
def to_json(
self,
value: Any,
*,
indent: int | None = None,
include: _IncEx = None,
exclude: _IncEx = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: dict[str, Any] | None = None,
) -> bytes:
"""
Serialize a Python object to JSON including transforming and filtering data.
Arguments:
value: The Python object to serialize.
indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
include: A set of fields to include, if `None` all fields are included.
exclude: A set of fields to exclude, if `None` no fields are excluded.
by_alias: Whether to use the alias names of fields.
exclude_unset: Whether to exclude fields that are not set,
e.g. are not included in `__pydantic_fields_set__`.
exclude_defaults: Whether to exclude fields that are equal to their default value.
exclude_none: Whether to exclude fields that have a value of `None`.
round_trip: Whether to enable serialization and validation round-trip support.
warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
"error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
fallback: A function to call when an unknown value is encountered,
if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
context: The context to use for serialization, this is passed to functional serializers as
[`info.context`][pydantic_core.core_schema.SerializationInfo.context].
Raises:
PydanticSerializationError: If serialization fails and no `fallback` function is provided.
Returns:
JSON bytes.
"""
def to_json(
value: Any,
*,
indent: int | None = None,
include: _IncEx = None,
exclude: _IncEx = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
bytes_mode: Literal['utf8', 'base64'] = 'utf8',
inf_nan_mode: Literal['null', 'constants'] = 'constants',
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: dict[str, Any] | None = None,
) -> bytes:
"""
Serialize a Python object to JSON including transforming and filtering data.
This is effectively a standalone version of [`SchemaSerializer.to_json`][pydantic_core.SchemaSerializer.to_json].
Arguments:
value: The Python object to serialize.
indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
include: A set of fields to include, if `None` all fields are included.
exclude: A set of fields to exclude, if `None` no fields are excluded.
by_alias: Whether to use the alias names of fields.
exclude_none: Whether to exclude fields that have a value of `None`.
round_trip: Whether to enable serialization and validation round-trip support.
timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.
bytes_mode: How to serialize `bytes` objects, either `'utf8'` or `'base64'`.
inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'` or `'constants'`.
serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails
`"<Unserializable {value_type} object>"` will be used.
fallback: A function to call when an unknown value is encountered,
if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
context: The context to use for serialization, this is passed to functional serializers as
[`info.context`][pydantic_core.core_schema.SerializationInfo.context].
Raises:
PydanticSerializationError: If serialization fails and no `fallback` function is provided.
Returns:
JSON bytes.
"""
def from_json(
data: str | bytes | bytearray,
*,
allow_inf_nan: bool = True,
cache_strings: bool | Literal['all', 'keys', 'none'] = True,
allow_partial: bool = False,
) -> Any:
"""
Deserialize JSON data to a Python object.
This is effectively a faster version of `json.loads()`, with some extra functionality.
Arguments:
data: The JSON data to deserialize.
allow_inf_nan: Whether to allow `Infinity`, `-Infinity` and `NaN` values as `json.loads()` does by default.
cache_strings: Whether to cache strings to avoid constructing new Python objects,
this should have a significant impact on performance while increasing memory usage slightly,
`all/True` means cache all strings, `keys` means cache only dict keys, `none/False` means no caching.
allow_partial: Whether to allow partial deserialization, if `True` JSON data is returned if the end of the
input is reached before the full object is deserialized, e.g. `["aa", "bb", "c` would return `['aa', 'bb']`.
Raises:
ValueError: If deserialization fails.
Returns:
The deserialized Python object.
"""
def to_jsonable_python(
value: Any,
*,
include: _IncEx = None,
exclude: _IncEx = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
bytes_mode: Literal['utf8', 'base64'] = 'utf8',
inf_nan_mode: Literal['null', 'constants'] = 'constants',
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: dict[str, Any] | None = None,
) -> Any:
"""
Serialize/marshal a Python object to a JSON-serializable Python object including transforming and filtering data.
This is effectively a standalone version of
[`SchemaSerializer.to_python(mode='json')`][pydantic_core.SchemaSerializer.to_python].
Args:
value: The Python object to serialize.
include: A set of fields to include, if `None` all fields are included.
exclude: A set of fields to exclude, if `None` no fields are excluded.
by_alias: Whether to use the alias names of fields.
exclude_none: Whether to exclude fields that have a value of `None`.
round_trip: Whether to enable serialization and validation round-trip support.
timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.
bytes_mode: How to serialize `bytes` objects, either `'utf8'` or `'base64'`.
inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'` or `'constants'`.
serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails
`"<Unserializable {value_type} object>"` will be used.
fallback: A function to call when an unknown value is encountered,
if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
context: The context to use for serialization, this is passed to functional serializers as
[`info.context`][pydantic_core.core_schema.SerializationInfo.context].
Raises:
PydanticSerializationError: If serialization fails and no `fallback` function is provided.
Returns:
The serialized Python object.
"""
class Url(SupportsAllComparisons):
"""
A URL type, internal logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed
by Mozilla.
"""
def __new__(cls, url: str) -> Self:
"""
Create a new `Url` instance.
Args:
url: String representation of a URL.
Returns:
A new `Url` instance.
Raises:
ValidationError: If the URL is invalid.
"""
@property
def scheme(self) -> str:
"""
The scheme part of the URL.
e.g. `https` in `https://user:pass@host:port/path?query#fragment`
"""
@property
def username(self) -> str | None:
"""
The username part of the URL, or `None`.
e.g. `user` in `https://user:pass@host:port/path?query#fragment`
"""
@property
def password(self) -> str | None:
"""
The password part of the URL, or `None`.
e.g. `pass` in `https://user:pass@host:port/path?query#fragment`
"""
@property
def host(self) -> str | None:
"""
The host part of the URL, or `None`.
If the URL must be punycode encoded, this is the encoded host, e.g if the input URL is `https://£££.com`,
`host` will be `xn--9aaa.com`
"""
def unicode_host(self) -> str | None:
"""
The host part of the URL as a unicode string, or `None`.
e.g. `host` in `https://user:pass@host:port/path?query#fragment`
If the URL must be punycode encoded, this is the decoded host, e.g if the input URL is `https://£££.com`,
`unicode_host()` will be `£££.com`
"""
@property
def port(self) -> int | None:
"""
The port part of the URL, or `None`.
e.g. `port` in `https://user:pass@host:port/path?query#fragment`
"""
@property
def path(self) -> str | None:
"""
The path part of the URL, or `None`.
e.g. `/path` in `https://user:pass@host:port/path?query#fragment`
"""
@property
def query(self) -> str | None:
"""
The query part of the URL, or `None`.
e.g. `query` in `https://user:pass@host:port/path?query#fragment`
"""
def query_params(self) -> list[tuple[str, str]]:
"""
The query part of the URL as a list of key-value pairs.
e.g. `[('foo', 'bar')]` in `https://user:pass@host:port/path?foo=bar#fragment`
"""
@property
def fragment(self) -> str | None:
"""
The fragment part of the URL, or `None`.
e.g. `fragment` in `https://user:pass@host:port/path?query#fragment`
"""
def unicode_string(self) -> str:
"""
The URL as a unicode string, unlike `__str__()` this will not punycode encode the host.
If the URL must be punycode encoded, this is the decoded string, e.g if the input URL is `https://£££.com`,
`unicode_string()` will be `https://£££.com`
"""
def __repr__(self) -> str: ...
def __str__(self) -> str:
"""
The URL as a string, this will punycode encode the host if required.
"""
def __deepcopy__(self, memo: dict) -> str: ...
@classmethod
def build(
cls,
*,
scheme: str,
username: str | None = None,
password: str | None = None,
host: str,
port: int | None = None,
path: str | None = None,
query: str | None = None,
fragment: str | None = None,
) -> Self:
"""
Build a new `Url` instance from its component parts.
Args:
scheme: The scheme part of the URL.
username: The username part of the URL, or omit for no username.
password: The password part of the URL, or omit for no password.
host: The host part of the URL.
port: The port part of the URL, or omit for no port.
path: The path part of the URL, or omit for no path.
query: The query part of the URL, or omit for no query.
fragment: The fragment part of the URL, or omit for no fragment.
Returns:
An instance of URL
"""
class MultiHostUrl(SupportsAllComparisons):
"""
A URL type with support for multiple hosts, as used by some databases for DSNs, e.g. `https://foo.com,bar.com/path`.
Internal URL logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed
by Mozilla.
"""
def __new__(cls, url: str) -> Self:
"""
Create a new `MultiHostUrl` instance.
Args:
url: String representation of a URL.
Returns:
A new `MultiHostUrl` instance.
Raises:
ValidationError: If the URL is invalid.
"""
@property
def scheme(self) -> str:
"""
The scheme part of the URL.
e.g. `https` in `https://foo.com,bar.com/path?query#fragment`
"""
@property
def path(self) -> str | None:
"""
The path part of the URL, or `None`.
e.g. `/path` in `https://foo.com,bar.com/path?query#fragment`
"""
@property
def query(self) -> str | None:
"""
The query part of the URL, or `None`.
e.g. `query` in `https://foo.com,bar.com/path?query#fragment`
"""
def query_params(self) -> list[tuple[str, str]]:
"""
The query part of the URL as a list of key-value pairs.
e.g. `[('foo', 'bar')]` in `https://foo.com,bar.com/path?query#fragment`
"""
@property
def fragment(self) -> str | None:
"""
The fragment part of the URL, or `None`.
e.g. `fragment` in `https://foo.com,bar.com/path?query#fragment`
"""
def hosts(self) -> list[MultiHostHost]:
'''
The hosts of the `MultiHostUrl` as [`MultiHostHost`][pydantic_core.MultiHostHost] typed dicts.
```py
from pydantic_core import MultiHostUrl
mhu = MultiHostUrl('https://foo.com:123,foo:bar@bar.com/path')
print(mhu.hosts())
"""
[
{'username': None, 'password': None, 'host': 'foo.com', 'port': 123},
{'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443}
]
```
Returns:
A list of dicts, each representing a host.
'''
def unicode_string(self) -> str:
"""
The URL as a unicode string, unlike `__str__()` this will not punycode encode the hosts.
"""
def __repr__(self) -> str: ...
def __str__(self) -> str:
"""
The URL as a string, this will punycode encode the hosts if required.
"""
def __deepcopy__(self, memo: dict) -> Self: ...
@classmethod
def build(
cls,
*,
scheme: str,
hosts: list[MultiHostHost] | None = None,
username: str | None = None,
password: str | None = None,
host: str | None = None,
port: int | None = None,
path: str | None = None,
query: str | None = None,
fragment: str | None = None,
) -> Self:
"""
Build a new `MultiHostUrl` instance from its component parts.
This method takes either `hosts` - a list of `MultiHostHost` typed dicts, or the individual components
`username`, `password`, `host` and `port`.
Args:
scheme: The scheme part of the URL.
hosts: Multiple hosts to build the URL from.
username: The username part of the URL.
password: The password part of the URL.
host: The host part of the URL.
port: The port part of the URL.
path: The path part of the URL.
query: The query part of the URL, or omit for no query.
fragment: The fragment part of the URL, or omit for no fragment.
Returns:
An instance of `MultiHostUrl`
"""
@final
class SchemaError(Exception):
"""
Information about errors that occur while building a [`SchemaValidator`][pydantic_core.SchemaValidator]
or [`SchemaSerializer`][pydantic_core.SchemaSerializer].
"""
def error_count(self) -> int:
"""
Returns:
The number of errors in the schema.
"""
def errors(self) -> list[ErrorDetails]:
"""
Returns:
A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the schema.
"""
@final
class ValidationError(ValueError):
"""
`ValidationError` is the exception raised by `pydantic-core` when validation fails, it contains a list of errors
which detail why validation failed.
"""
@staticmethod
def from_exception_data(
title: str,
line_errors: list[InitErrorDetails],
input_type: Literal['python', 'json'] = 'python',
hide_input: bool = False,
) -> ValidationError:
"""
Python constructor for a Validation Error.
The API for constructing validation errors will probably change in the future,
hence the static method rather than `__init__`.
Arguments:
title: The title of the error, as used in the heading of `str(validation_error)`
line_errors: A list of [`InitErrorDetails`][pydantic_core.InitErrorDetails] which contain information
about errors that occurred during validation.
input_type: Whether the error is for a Python object or JSON.
hide_input: Whether to hide the input value in the error message.
"""
@property
def title(self) -> str:
"""
The title of the error, as used in the heading of `str(validation_error)`.
"""
def error_count(self) -> int:
"""
Returns:
The number of errors in the validation error.
"""
def errors(
self, *, include_url: bool = True, include_context: bool = True, include_input: bool = True
) -> list[ErrorDetails]:
"""
Details about each error in the validation error.
Args:
include_url: Whether to include a URL to documentation on the error each error.
include_context: Whether to include the context of each error.
include_input: Whether to include the input value of each error.
Returns:
A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the validation error.
"""
def json(
self,
*,
indent: int | None = None,
include_url: bool = True,
include_context: bool = True,
include_input: bool = True,
) -> str:
"""
Same as [`errors()`][pydantic_core.ValidationError.errors] but returns a JSON string.
Args:
indent: The number of spaces to indent the JSON by, or `None` for no indentation - compact JSON.
include_url: Whether to include a URL to documentation on the error each error.
include_context: Whether to include the context of each error.
include_input: Whether to include the input value of each error.
Returns:
a JSON string.
"""
def __repr__(self) -> str:
"""
A string representation of the validation error.
Whether or not documentation URLs are included in the repr is controlled by the
environment variable `PYDANTIC_ERRORS_INCLUDE_URL` being set to `1` or
`true`; by default, URLs are shown.
Due to implementation details, this environment variable can only be set once,
before the first validation error is created.
"""
@final
class PydanticCustomError(ValueError):
def __new__(
cls, error_type: LiteralString, message_template: LiteralString, context: dict[str, Any] | None = None
) -> Self: ...
@property
def context(self) -> dict[str, Any] | None: ...
@property
def type(self) -> str: ...
@property
def message_template(self) -> str: ...
def message(self) -> str: ...
@final
class PydanticKnownError(ValueError):
def __new__(cls, error_type: ErrorType, context: dict[str, Any] | None = None) -> Self: ...
@property
def context(self) -> dict[str, Any] | None: ...
@property
def type(self) -> ErrorType: ...
@property
def message_template(self) -> str: ...
def message(self) -> str: ...
@final
class PydanticOmit(Exception):
def __new__(cls) -> Self: ...
@final
class PydanticUseDefault(Exception):
def __new__(cls) -> Self: ...
@final
class PydanticSerializationError(ValueError):
def __new__(cls, message: str) -> Self: ...
@final
class PydanticSerializationUnexpectedValue(ValueError):
def __new__(cls, message: str | None = None) -> Self: ...
@final
class ArgsKwargs:
def __new__(cls, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None) -> Self: ...
@property
def args(self) -> tuple[Any, ...]: ...
@property
def kwargs(self) -> dict[str, Any] | None: ...
@final
class PydanticUndefinedType:
def __copy__(self) -> Self: ...
def __deepcopy__(self, memo: Any) -> Self: ...
PydanticUndefined: PydanticUndefinedType
def list_all_errors() -> list[ErrorTypeInfo]:
"""
Get information about all built-in errors.
Returns:
A list of `ErrorTypeInfo` typed dicts.
"""
@final
class TzInfo(datetime.tzinfo):
def tzname(self, _dt: datetime.datetime | None) -> str | None: ...
def utcoffset(self, _dt: datetime.datetime | None) -> datetime.timedelta: ...
def dst(self, _dt: datetime.datetime | None) -> datetime.timedelta: ...
def fromutc(self, dt: datetime.datetime) -> datetime.datetime: ...
def __deepcopy__(self, _memo: dict[Any, Any]) -> TzInfo: ...
def validate_core_schema(schema: CoreSchema, *, strict: bool | None = None) -> CoreSchema:
"""Validate a CoreSchema
This currently uses lax mode for validation (i.e. will coerce strings to dates and such)
but may use strict mode in the future.
We may also remove this function altogether, do not rely on it being present if you are
using pydantic-core directly.
"""