pboot-validator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1295 @@
1
+ """Configuration for Pydantic models."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import warnings
6
+ from collections.abc import Callable
7
+ from re import Pattern
8
+ from typing import TYPE_CHECKING, Any, Literal, TypeAlias, TypeVar, Union, cast, overload
9
+
10
+ from typing_extensions import TypedDict, Unpack, deprecated
11
+
12
+ from ._migration import getattr_migration
13
+ from .aliases import AliasGenerator
14
+ from .errors import PydanticUserError
15
+ from .warnings import PydanticDeprecatedSince211
16
+
17
+ if TYPE_CHECKING:
18
+ from ._internal._generate_schema import GenerateSchema as _GenerateSchema
19
+ from .fields import ComputedFieldInfo, FieldInfo
20
+
21
+ __all__ = ('ConfigDict', 'with_config')
22
+
23
+
24
+ JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict']
25
+ JsonDict: TypeAlias = dict[str, JsonValue]
26
+
27
+ JsonEncoder = Callable[[Any], Any]
28
+
29
+ JsonSchemaExtraCallable: TypeAlias = Callable[[JsonDict], None] | Callable[[JsonDict, type[Any]], None]
30
+
31
+ ExtraValues = Literal['allow', 'ignore', 'forbid']
32
+
33
+
34
+ class ConfigDict(TypedDict, total=False):
35
+ """A TypedDict for configuring Pydantic behaviour."""
36
+
37
+ title: str | None
38
+ """The title for the generated JSON schema, defaults to the model's name"""
39
+
40
+ model_title_generator: Callable[[type], str] | None
41
+ """A callable that takes a model class and returns the title for it. Defaults to `None`."""
42
+
43
+ field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
44
+ """A callable that takes a field's name and info and returns title for it. Defaults to `None`."""
45
+
46
+ str_to_lower: bool
47
+ """Whether to convert all characters to lowercase for str types. Defaults to `False`."""
48
+
49
+ str_to_upper: bool
50
+ """Whether to convert all characters to uppercase for str types. Defaults to `False`."""
51
+
52
+ str_strip_whitespace: bool
53
+ """Whether to strip leading and trailing whitespace for str types."""
54
+
55
+ str_min_length: int
56
+ """The minimum length for str types. Defaults to `0`."""
57
+
58
+ str_max_length: int | None
59
+ """The maximum length for str types. Defaults to `None`."""
60
+
61
+ extra: ExtraValues | None
62
+ '''
63
+ Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`.
64
+
65
+ Three configuration values are available:
66
+
67
+ - `'ignore'`: Providing extra data is ignored (the default):
68
+ ```python
69
+ from pboot_validator import BaseModel, ConfigDict
70
+
71
+ class User(BaseModel):
72
+ model_config = ConfigDict(extra='ignore') # (1)!
73
+
74
+ name: str
75
+
76
+ user = User(name='John Doe', age=20) # (2)!
77
+ print(user)
78
+ #> name='John Doe'
79
+ ```
80
+
81
+ 1. This is the default behaviour.
82
+ 2. The `age` argument is ignored.
83
+
84
+ - `'forbid'`: Providing extra data is not permitted, and a [`ValidationError`][pydantic_core.ValidationError]
85
+ will be raised if this is the case:
86
+ ```python
87
+ from pboot_validator import BaseModel, ConfigDict, ValidationError
88
+
89
+
90
+ class Model(BaseModel):
91
+ x: int
92
+
93
+ model_config = ConfigDict(extra='forbid')
94
+
95
+
96
+ try:
97
+ Model(x=1, y='a')
98
+ except ValidationError as exc:
99
+ print(exc)
100
+ """
101
+ 1 validation error for Model
102
+ y
103
+ Extra inputs are not permitted [type=extra_forbidden, input_value='a', input_type=str]
104
+ """
105
+ ```
106
+
107
+ - `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute:
108
+ ```python
109
+ from pboot_validator import BaseModel, ConfigDict
110
+
111
+
112
+ class Model(BaseModel):
113
+ x: int
114
+
115
+ model_config = ConfigDict(extra='allow')
116
+
117
+
118
+ m = Model(x=1, y='a')
119
+ assert m.__pydantic_extra__ == {'y': 'a'}
120
+ ```
121
+ By default, no validation will be applied to these extra items, but you can set a type for the values by overriding
122
+ the type annotation for `__pydantic_extra__`:
123
+ ```python
124
+ from pboot_validator import BaseModel, ConfigDict, Field, ValidationError
125
+
126
+
127
+ class Model(BaseModel):
128
+ __pydantic_extra__: dict[str, int] = Field(init=False) # (1)!
129
+
130
+ x: int
131
+
132
+ model_config = ConfigDict(extra='allow')
133
+
134
+
135
+ try:
136
+ Model(x=1, y='a')
137
+ except ValidationError as exc:
138
+ print(exc)
139
+ """
140
+ 1 validation error for Model
141
+ y
142
+ Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
143
+ """
144
+
145
+ m = Model(x=1, y='2')
146
+ assert m.x == 1
147
+ assert m.y == 2
148
+ assert m.model_dump() == {'x': 1, 'y': 2}
149
+ assert m.__pydantic_extra__ == {'y': 2}
150
+ ```
151
+
152
+ 1. The `= Field(init=False)` does not have any effect at runtime, but prevents the `__pydantic_extra__` field from
153
+ being included as a parameter to the model's `__init__` method by type checkers.
154
+
155
+ As well as specifying an `extra` configuration value on the model, you can also provide it as an argument to the validation methods.
156
+ This will override any `extra` configuration value set on the model:
157
+ ```python
158
+ from pboot_validator import BaseModel, ConfigDict, ValidationError
159
+
160
+ class Model(BaseModel):
161
+ x: int
162
+ model_config = ConfigDict(extra="allow")
163
+
164
+ try:
165
+ # Override model config and forbid extra fields just this time
166
+ Model.model_validate({"x": 1, "y": 2}, extra="forbid")
167
+ except ValidationError as exc:
168
+ print(exc)
169
+ """
170
+ 1 validation error for Model
171
+ y
172
+ Extra inputs are not permitted [type=extra_forbidden, input_value=2, input_type=int]
173
+ """
174
+ ```
175
+ '''
176
+
177
+ frozen: bool
178
+ """
179
+ Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
180
+ a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
181
+ attributes are hashable. Defaults to `False`.
182
+
183
+ Note:
184
+ On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
185
+ """
186
+
187
+ populate_by_name: bool
188
+ """
189
+ Whether an aliased field may be populated by its name as given by the model
190
+ attribute, as well as the alias. Defaults to `False`.
191
+
192
+ !!! warning
193
+ `populate_by_name` usage is not recommended in v2.11+ and will be deprecated in v3.
194
+ Instead, you should use the [`validate_by_name`][pboot_validator.config.ConfigDict.validate_by_name] configuration setting.
195
+
196
+ When `validate_by_name=True` and `validate_by_alias=True`, this is strictly equivalent to the
197
+ previous behavior of `populate_by_name=True`.
198
+
199
+ In v2.11, we also introduced a [`validate_by_alias`][pboot_validator.config.ConfigDict.validate_by_alias] setting that introduces more fine grained
200
+ control for validation behavior.
201
+
202
+ Here's how you might go about using the new settings to achieve the same behavior:
203
+
204
+ ```python
205
+ from pboot_validator import BaseModel, ConfigDict, Field
206
+
207
+ class Model(BaseModel):
208
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
209
+
210
+ my_field: str = Field(alias='my_alias') # (1)!
211
+
212
+ m = Model(my_alias='foo') # (2)!
213
+ print(m)
214
+ #> my_field='foo'
215
+
216
+ m = Model(my_field='foo') # (3)!
217
+ print(m)
218
+ #> my_field='foo'
219
+ ```
220
+
221
+ 1. The field `'my_field'` has an alias `'my_alias'`.
222
+ 2. The model is populated by the alias `'my_alias'`.
223
+ 3. The model is populated by the attribute name `'my_field'`.
224
+ """
225
+
226
+ use_enum_values: bool
227
+ """
228
+ Whether to populate models with the [`value`][enum.Enum.value] property of enums, rather than the raw enum.
229
+ This may be useful if you want to serialize the value later. Defaults to `False`.
230
+
231
+ !!! note
232
+ If you have a field typed as an enum with a default value, the [`validate_default`][pboot_validator.ConfigDict.validate_default]
233
+ configuration needs to be set to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
234
+ enum's value occurs during validation, not serialization.
235
+
236
+ ```python
237
+ from enum import Enum
238
+
239
+ from pboot_validator import BaseModel, ConfigDict, Field
240
+
241
+ class SomeEnum(Enum):
242
+ FOO = 'foo'
243
+ BAR = 'bar'
244
+ BAZ = 'baz'
245
+
246
+ class SomeModel(BaseModel):
247
+ model_config = ConfigDict(use_enum_values=True)
248
+
249
+ some_enum: SomeEnum
250
+ another_enum: SomeEnum | None = Field(
251
+ default=SomeEnum.FOO, validate_default=True
252
+ )
253
+
254
+ model1 = SomeModel(some_enum=SomeEnum.BAR)
255
+ print(model1.model_dump())
256
+ #> {'some_enum': 'bar', 'another_enum': 'foo'}
257
+
258
+ model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
259
+ print(model2.model_dump())
260
+ #> {'some_enum': 'bar', 'another_enum': 'baz'}
261
+ ```
262
+ """
263
+
264
+ validate_assignment: bool
265
+ """
266
+ Whether to validate the data when the model is changed. Defaults to `False`.
267
+
268
+ The default behavior of Pydantic is to validate the data when the model is created.
269
+
270
+ In case the user changes the data after the model is created, the model is _not_ revalidated.
271
+
272
+ ```python
273
+ from pboot_validator import BaseModel
274
+
275
+ class User(BaseModel):
276
+ name: str
277
+
278
+ user = User(name='John Doe') # (1)!
279
+ print(user)
280
+ #> name='John Doe'
281
+ user.name = 123 # (1)!
282
+ print(user)
283
+ #> name=123
284
+ ```
285
+
286
+ 1. The validation happens only when the model is created.
287
+ 2. The validation does not happen when the data is changed.
288
+
289
+ In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
290
+
291
+ ```python
292
+ from pboot_validator import BaseModel, ValidationError
293
+
294
+ class User(BaseModel, validate_assignment=True): # (1)!
295
+ name: str
296
+
297
+ user = User(name='John Doe') # (2)!
298
+ print(user)
299
+ #> name='John Doe'
300
+ try:
301
+ user.name = 123 # (3)!
302
+ except ValidationError as e:
303
+ print(e)
304
+ '''
305
+ 1 validation error for User
306
+ name
307
+ Input should be a valid string [type=string_type, input_value=123, input_type=int]
308
+ '''
309
+ ```
310
+
311
+ 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
312
+ 2. The validation happens when the model is created.
313
+ 3. The validation _also_ happens when the data is changed.
314
+ """
315
+
316
+ arbitrary_types_allowed: bool
317
+ """
318
+ Whether arbitrary types are allowed for field types. Defaults to `False`.
319
+
320
+ ```python
321
+ from pboot_validator import BaseModel, ConfigDict, ValidationError
322
+
323
+ # This is not a pydantic model, it's an arbitrary class
324
+ class Pet:
325
+ def __init__(self, name: str):
326
+ self.name = name
327
+
328
+ class Model(BaseModel):
329
+ model_config = ConfigDict(arbitrary_types_allowed=True)
330
+
331
+ pet: Pet
332
+ owner: str
333
+
334
+ pet = Pet(name='Hedwig')
335
+ # A simple check of instance type is used to validate the data
336
+ model = Model(owner='Harry', pet=pet)
337
+ print(model)
338
+ #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
339
+ print(model.pet)
340
+ #> <__main__.Pet object at 0x0123456789ab>
341
+ print(model.pet.name)
342
+ #> Hedwig
343
+ print(type(model.pet))
344
+ #> <class '__main__.Pet'>
345
+ try:
346
+ # If the value is not an instance of the type, it's invalid
347
+ Model(owner='Harry', pet='Hedwig')
348
+ except ValidationError as e:
349
+ print(e)
350
+ '''
351
+ 1 validation error for Model
352
+ pet
353
+ Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
354
+ '''
355
+
356
+ # Nothing in the instance of the arbitrary type is checked
357
+ # Here name probably should have been a str, but it's not validated
358
+ pet2 = Pet(name=42)
359
+ model2 = Model(owner='Harry', pet=pet2)
360
+ print(model2)
361
+ #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
362
+ print(model2.pet)
363
+ #> <__main__.Pet object at 0x0123456789ab>
364
+ print(model2.pet.name)
365
+ #> 42
366
+ print(type(model2.pet))
367
+ #> <class '__main__.Pet'>
368
+ ```
369
+ """
370
+
371
+ from_attributes: bool
372
+ """
373
+ Whether to build models and look up discriminators of tagged unions using python object attributes.
374
+ """
375
+
376
+ loc_by_alias: bool
377
+ """Whether to use the actual key provided in the data (e.g. alias) for error `loc`s rather than the field's name. Defaults to `True`."""
378
+
379
+ alias_generator: Callable[[str], str] | AliasGenerator | None
380
+ """
381
+ A callable that takes a field name and returns an alias for it
382
+ or an instance of [`AliasGenerator`][pboot_validator.aliases.AliasGenerator]. Defaults to `None`.
383
+
384
+ When using a callable, the alias generator is used for both validation and serialization.
385
+ If you want to use different alias generators for validation and serialization, you can use
386
+ [`AliasGenerator`][pboot_validator.aliases.AliasGenerator] instead.
387
+
388
+ If data source field names do not match your code style (e.g. CamelCase fields),
389
+ you can automatically generate aliases using `alias_generator`. Here's an example with
390
+ a basic callable:
391
+
392
+ ```python
393
+ from pboot_validator import BaseModel, ConfigDict
394
+ from pboot_validator.alias_generators import to_pascal
395
+
396
+ class Voice(BaseModel):
397
+ model_config = ConfigDict(alias_generator=to_pascal)
398
+
399
+ name: str
400
+ language_code: str
401
+
402
+ voice = Voice(Name='Filiz', LanguageCode='tr-TR')
403
+ print(voice.language_code)
404
+ #> tr-TR
405
+ print(voice.model_dump(by_alias=True))
406
+ #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
407
+ ```
408
+
409
+ If you want to use different alias generators for validation and serialization, you can use
410
+ [`AliasGenerator`][pboot_validator.aliases.AliasGenerator].
411
+
412
+ ```python
413
+ from pboot_validator import AliasGenerator, BaseModel, ConfigDict
414
+ from pboot_validator.alias_generators import to_camel, to_pascal
415
+
416
+ class Athlete(BaseModel):
417
+ first_name: str
418
+ last_name: str
419
+ sport: str
420
+
421
+ model_config = ConfigDict(
422
+ alias_generator=AliasGenerator(
423
+ validation_alias=to_camel,
424
+ serialization_alias=to_pascal,
425
+ )
426
+ )
427
+
428
+ athlete = Athlete(firstName='John', lastName='Doe', sport='track')
429
+ print(athlete.model_dump(by_alias=True))
430
+ #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
431
+ ```
432
+
433
+ Note:
434
+ Pydantic offers three built-in alias generators: [`to_pascal`][pboot_validator.alias_generators.to_pascal],
435
+ [`to_camel`][pboot_validator.alias_generators.to_camel], and [`to_snake`][pboot_validator.alias_generators.to_snake].
436
+ """
437
+
438
+ ignored_types: tuple[type, ...]
439
+ """A tuple of types that may occur as values of class attributes without annotations. This is
440
+ typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
441
+ class without an annotation and has a type that is not in this tuple (or otherwise recognized by
442
+ _pydantic_), an error will be raised. Defaults to `()`.
443
+ """
444
+
445
+ allow_inf_nan: bool
446
+ """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`."""
447
+
448
+ json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
449
+ """A dict or callable to provide extra JSON schema properties. Defaults to `None`."""
450
+
451
+ json_encoders: dict[type[object], JsonEncoder] | None
452
+ """
453
+ A `dict` of custom JSON encoders for specific types. Defaults to `None`.
454
+
455
+ /// version-deprecated | v2
456
+ This configuration option is a carryover from v1. We originally planned to remove it in v2 but didn't have a 1:1 replacement
457
+ so we are keeping it for now. It is still deprecated and will likely be removed in the future.
458
+ ///
459
+ """
460
+
461
+ # new in V2
462
+ strict: bool
463
+ """
464
+ Whether strict validation is applied to all fields on the model.
465
+
466
+ By default, Pydantic attempts to coerce values to the correct type, when possible.
467
+
468
+ There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
469
+ does not match the field's type annotation.
470
+
471
+ To configure strict mode for all fields on a model, you can set `strict=True` on the model.
472
+
473
+ ```python
474
+ from pboot_validator import BaseModel, ConfigDict
475
+
476
+ class Model(BaseModel):
477
+ model_config = ConfigDict(strict=True)
478
+
479
+ name: str
480
+ age: int
481
+ ```
482
+
483
+ See [Strict Mode](../concepts/strict_mode.md) for more details.
484
+
485
+ See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
486
+ strict and lax modes.
487
+
488
+ /// version-added | v2
489
+ ///
490
+ """
491
+ # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
492
+ revalidate_instances: Literal['always', 'never', 'subclass-instances']
493
+ """
494
+ When and how to revalidate models and dataclasses during validation. Can be one of:
495
+
496
+ - `'never'`: will *not* revalidate models and dataclasses during validation
497
+ - `'always'`: will revalidate models and dataclasses during validation
498
+ - `'subclass-instances'`: will revalidate models and dataclasses during validation if the instance is a
499
+ subclass of the model or dataclass
500
+
501
+ The default is `'never'` (no revalidation).
502
+
503
+ This configuration only affects *the current model* it is applied on, and does *not* propagate to the models
504
+ referenced in fields.
505
+
506
+ ```python
507
+ from pboot_validator import BaseModel
508
+
509
+ class User(BaseModel, revalidate_instances='never'): # (1)!
510
+ name: str
511
+
512
+ class Transaction(BaseModel):
513
+ user: User
514
+
515
+ my_user = User(name='John')
516
+ t = Transaction(user=my_user)
517
+
518
+ my_user.name = 1 # (2)!
519
+ t = Transaction(user=my_user) # (3)!
520
+ print(t)
521
+ #> user=User(name=1)
522
+ ```
523
+
524
+ 1. This is the default behavior.
525
+ 2. The assignment is *not* validated, unless you set [`validate_assignment`][pboot_validator.ConfigDict.validate_assignment] in the configuration.
526
+ 3. Since `revalidate_instances` is set to `'never'`, the user instance is not revalidated.
527
+
528
+ Here is an example demonstrating the behavior of `'subclass-instances'`:
529
+
530
+ ```python
531
+ from pboot_validator import BaseModel
532
+
533
+ class User(BaseModel, revalidate_instances='subclass-instances'):
534
+ name: str
535
+
536
+ class SubUser(User):
537
+ age: int
538
+
539
+ class Transaction(BaseModel):
540
+ user: User
541
+
542
+ my_user = User(name='John')
543
+ my_user.name = 1 # (1)!
544
+ t = Transaction(user=my_user) # (2)!
545
+ print(t)
546
+ #> user=User(name=1)
547
+
548
+ my_sub_user = SubUser(name='John', age=20)
549
+ t = Transaction(user=my_sub_user)
550
+ print(t) # (3)!
551
+ #> user=User(name='John')
552
+ ```
553
+
554
+ 1. The assignment is *not* validated, unless you set [`validate_assignment`][pboot_validator.ConfigDict.validate_assignment] in the configuration.
555
+ 2. Because `my_user` is a "direct" instance of `User`, it is *not* being revalidated. It would have been the case if
556
+ `revalidate_instances` was set to `'always'`.
557
+ 3. Because `my_sub_user` is an instance of a `User` subclass, it is being revalidated. In this case, Pydantic coerces `my_sub_user` to the defined
558
+ `User` class defined on `Transaction`. If one of its fields had an invalid value, a validation error would have been raised.
559
+
560
+ /// version-added | v2
561
+ ///
562
+ """
563
+
564
+ ser_json_timedelta: Literal['iso8601', 'float']
565
+ """
566
+ The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
567
+ `'float'`. Defaults to `'iso8601'`.
568
+
569
+ - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
570
+ - `'float'` will serialize timedeltas to the total number of seconds.
571
+
572
+ /// version-changed | v2.12
573
+ It is now recommended to use the [`ser_json_temporal`][pboot_validator.config.ConfigDict.ser_json_temporal]
574
+ setting. `ser_json_timedelta` will be deprecated in v3.
575
+ ///
576
+ """
577
+
578
+ ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']
579
+ """
580
+ The format of JSON serialized temporal types from the [`datetime`][] module. This includes:
581
+
582
+ - [`datetime.datetime`][]
583
+ - [`datetime.date`][]
584
+ - [`datetime.time`][]
585
+ - [`datetime.timedelta`][]
586
+
587
+ Can be one of:
588
+
589
+ - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
590
+ - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch.
591
+ - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch.
592
+
593
+ Defaults to `'iso8601'`.
594
+
595
+ /// version-added | v2.12
596
+ This setting replaces [`ser_json_timedelta`][pboot_validator.config.ConfigDict.ser_json_timedelta],
597
+ which will be deprecated in v3. `ser_json_temporal` adds more configurability for the other temporal types.
598
+ It takes precedence over `ser_json_timedelta`.
599
+ ///
600
+ """
601
+
602
+ val_temporal_unit: Literal['seconds', 'milliseconds', 'infer']
603
+ """
604
+ The unit to assume for validating numeric input for datetime-like types ([`datetime.datetime`][] and [`datetime.date`][]). Can be one of:
605
+
606
+ - `'seconds'` will validate date or time numeric inputs as seconds since the [epoch].
607
+ - `'milliseconds'` will validate date or time numeric inputs as milliseconds since the [epoch].
608
+ - `'infer'` will infer the unit from the string numeric input on unix time as:
609
+
610
+ * seconds since the [epoch] if $-2^{10} <= v <= 2^{10}$
611
+ * milliseconds since the [epoch] (if $v < -2^{10}$ or $v > 2^{10}$).
612
+
613
+ Defaults to `'infer'`.
614
+
615
+ /// version-added | v2.12
616
+ ///
617
+
618
+ [epoch]: https://en.wikipedia.org/wiki/Unix_time
619
+ """
620
+
621
+ ser_json_bytes: Literal['utf8', 'base64', 'hex']
622
+ """
623
+ The encoding of JSON serialized bytes. Defaults to `'utf8'`.
624
+ Set equal to `val_json_bytes` to get back an equal value after serialization round trip.
625
+
626
+ - `'utf8'` will serialize bytes to UTF-8 strings.
627
+ - `'base64'` will serialize bytes to URL safe base64 strings.
628
+ - `'hex'` will serialize bytes to hexadecimal strings.
629
+ """
630
+
631
+ val_json_bytes: Literal['utf8', 'base64', 'hex']
632
+ """
633
+ /// version-added | v2.9
634
+ ///
635
+
636
+ The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`.
637
+ Set equal to `ser_json_bytes` to get back an equal value after serialization round trip.
638
+
639
+ - `'utf8'` will deserialize UTF-8 strings to bytes.
640
+ - `'base64'` will deserialize URL safe base64 strings to bytes.
641
+ - `'hex'` will deserialize hexadecimal strings to bytes.
642
+ """
643
+
644
+ ser_json_inf_nan: Literal['null', 'constants', 'strings']
645
+ """
646
+ The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
647
+
648
+ - `'null'` will serialize infinity and NaN values as `null`.
649
+ - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
650
+ - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.
651
+ """
652
+
653
+ # whether to validate default values during validation, default False
654
+ validate_default: bool
655
+ """Whether to validate default values during validation. Defaults to `False`."""
656
+
657
+ validate_return: bool
658
+ """Whether to validate the return value from call validators. Defaults to `False`."""
659
+
660
+ protected_namespaces: tuple[str | Pattern[str], ...]
661
+ """
662
+ A tuple of strings and/or regex patterns that prevent models from having fields with names that conflict with its existing members/methods.
663
+
664
+ Strings are matched on a prefix basis. For instance, with `'dog'`, having a field named `'dog_name'` will be disallowed.
665
+
666
+ Regex patterns are matched on the entire field name. For instance, with the pattern `'^dog$'`, having a field named `'dog'` will be disallowed,
667
+ but `'dog_name'` will be accepted.
668
+
669
+ Defaults to `('model_validate', 'model_dump')`. This default is used to prevent collisions with the existing (and possibly future)
670
+ [validation](../concepts/models.md#validating-data) and [serialization](../concepts/serialization.md#serializing-data) methods.
671
+
672
+ ```python
673
+ import warnings
674
+
675
+ from pboot_validator import BaseModel
676
+
677
+ warnings.filterwarnings('error') # Raise warnings as errors
678
+
679
+ try:
680
+
681
+ class Model(BaseModel):
682
+ model_dump_something: str
683
+
684
+ except UserWarning as e:
685
+ print(e)
686
+ '''
687
+ Field 'model_dump_something' in 'Model' conflicts with protected namespace 'model_dump'.
688
+
689
+ You may be able to solve this by setting the 'protected_namespaces' configuration to ('model_validate',).
690
+ '''
691
+ ```
692
+
693
+ You can customize this behavior using the `protected_namespaces` setting:
694
+
695
+ ```python {test="skip"}
696
+ import re
697
+ import warnings
698
+
699
+ from pboot_validator import BaseModel, ConfigDict
700
+
701
+ with warnings.catch_warnings(record=True) as caught_warnings:
702
+ warnings.simplefilter('always') # Catch all warnings
703
+
704
+ class Model(BaseModel):
705
+ safe_field: str
706
+ also_protect_field: str
707
+ protect_this: str
708
+
709
+ model_config = ConfigDict(
710
+ protected_namespaces=(
711
+ 'protect_me_',
712
+ 'also_protect_',
713
+ re.compile('^protect_this$'),
714
+ )
715
+ )
716
+
717
+ for warning in caught_warnings:
718
+ print(f'{warning.message}')
719
+ '''
720
+ Field 'also_protect_field' in 'Model' conflicts with protected namespace 'also_protect_'.
721
+ You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', re.compile('^protect_this$'))`.
722
+
723
+ Field 'protect_this' in 'Model' conflicts with protected namespace 're.compile('^protect_this$')'.
724
+ You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', 'also_protect_')`.
725
+ '''
726
+ ```
727
+
728
+ While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
729
+ an error _is_ raised if there is an actual collision with an existing attribute:
730
+
731
+ ```python
732
+ from pboot_validator import BaseModel, ConfigDict
733
+
734
+ try:
735
+
736
+ class Model(BaseModel):
737
+ model_validate: str
738
+
739
+ model_config = ConfigDict(protected_namespaces=('model_',))
740
+
741
+ except ValueError as e:
742
+ print(e)
743
+ '''
744
+ Field 'model_validate' conflicts with member <bound method BaseModel.model_validate of <class 'pboot_validator.main.BaseModel'>> of protected namespace 'model_'.
745
+ '''
746
+ ```
747
+
748
+ /// version-changed | v2.10
749
+ The default protected namespaces was changed from `('model_',)` to `('model_validate', 'model_dump')`, to allow
750
+ for fields like `model_id`, `model_name` to be used.
751
+ ///
752
+ """
753
+
754
+ hide_input_in_errors: bool
755
+ """
756
+ Whether to hide inputs when printing errors. Defaults to `False`.
757
+
758
+ Pydantic shows the input value and type when it raises `ValidationError` during the validation.
759
+
760
+ ```python
761
+ from pboot_validator import BaseModel, ValidationError
762
+
763
+ class Model(BaseModel):
764
+ a: str
765
+
766
+ try:
767
+ Model(a=123)
768
+ except ValidationError as e:
769
+ print(e)
770
+ '''
771
+ 1 validation error for Model
772
+ a
773
+ Input should be a valid string [type=string_type, input_value=123, input_type=int]
774
+ '''
775
+ ```
776
+
777
+ You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
778
+
779
+ ```python
780
+ from pboot_validator import BaseModel, ConfigDict, ValidationError
781
+
782
+ class Model(BaseModel):
783
+ a: str
784
+ model_config = ConfigDict(hide_input_in_errors=True)
785
+
786
+ try:
787
+ Model(a=123)
788
+ except ValidationError as e:
789
+ print(e)
790
+ '''
791
+ 1 validation error for Model
792
+ a
793
+ Input should be a valid string [type=string_type]
794
+ '''
795
+ ```
796
+ """
797
+
798
+ defer_build: bool
799
+ """
800
+ Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
801
+
802
+ This can be useful to avoid the overhead of building models which are only
803
+ used nested within other models, or when you want to manually define type namespace via
804
+ [`Model.model_rebuild(_types_namespace=...)`][pboot_validator.BaseModel.model_rebuild].
805
+
806
+ /// version-changed | v2.10
807
+ The setting also applies to [Pydantic dataclasses](../concepts/dataclasses.md) and [type adapters](../concepts/type_adapter.md).
808
+ ///
809
+ """
810
+
811
+ plugin_settings: dict[str, object] | None
812
+ """A `dict` of settings for plugins. Defaults to `None`."""
813
+
814
+ schema_generator: type[_GenerateSchema] | None
815
+ """
816
+ The `GenerateSchema` class to use during core schema generation.
817
+
818
+ /// version-deprecated | v2.10
819
+ The `GenerateSchema` class is private and highly subject to change. This setting
820
+ no longer has any effect.
821
+ ///
822
+ """
823
+
824
+ json_schema_serialization_defaults_required: bool
825
+ """
826
+ Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
827
+
828
+ This ensures that the serialization schema will reflect the fact a field with a default will always be present
829
+ when serializing the model, even though it is not required for validation.
830
+
831
+ However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
832
+ between validation and serialization, and don't mind fields with defaults being marked as not required during
833
+ serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
834
+
835
+ ```python
836
+ from pboot_validator import BaseModel, ConfigDict
837
+
838
+ class Model(BaseModel):
839
+ a: str = 'a'
840
+
841
+ model_config = ConfigDict(json_schema_serialization_defaults_required=True)
842
+
843
+ print(Model.model_json_schema(mode='validation'))
844
+ '''
845
+ {
846
+ 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
847
+ 'title': 'Model',
848
+ 'type': 'object',
849
+ }
850
+ '''
851
+ print(Model.model_json_schema(mode='serialization'))
852
+ '''
853
+ {
854
+ 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
855
+ 'required': ['a'],
856
+ 'title': 'Model',
857
+ 'type': 'object',
858
+ }
859
+ '''
860
+ ```
861
+
862
+ /// version-added | v2.4
863
+ ///
864
+ """
865
+
866
+ json_schema_mode_override: Literal['validation', 'serialization', None]
867
+ """
868
+ If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
869
+ the function call. Defaults to `None`.
870
+
871
+ This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
872
+ validation schema.
873
+
874
+ It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
875
+ and serialization that must both be referenced from the same schema; when this happens, we automatically append
876
+ `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
877
+ serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
878
+ the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
879
+ from being added to the definition references.
880
+
881
+ ```python
882
+ from pboot_validator import BaseModel, ConfigDict, Json
883
+
884
+ class Model(BaseModel):
885
+ a: Json[int] # requires a string to validate, but will dump an int
886
+
887
+ print(Model.model_json_schema(mode='serialization'))
888
+ '''
889
+ {
890
+ 'properties': {'a': {'title': 'A', 'type': 'integer'}},
891
+ 'required': ['a'],
892
+ 'title': 'Model',
893
+ 'type': 'object',
894
+ }
895
+ '''
896
+
897
+ class ForceInputModel(Model):
898
+ # the following ensures that even with mode='serialization', we
899
+ # will get the schema that would be generated for validation.
900
+ model_config = ConfigDict(json_schema_mode_override='validation')
901
+
902
+ print(ForceInputModel.model_json_schema(mode='serialization'))
903
+ '''
904
+ {
905
+ 'properties': {
906
+ 'a': {
907
+ 'contentMediaType': 'application/json',
908
+ 'contentSchema': {'type': 'integer'},
909
+ 'title': 'A',
910
+ 'type': 'string',
911
+ }
912
+ },
913
+ 'required': ['a'],
914
+ 'title': 'ForceInputModel',
915
+ 'type': 'object',
916
+ }
917
+ '''
918
+ ```
919
+
920
+ /// version-added | v2.4
921
+ ///
922
+ """
923
+
924
+ coerce_numbers_to_str: bool
925
+ """
926
+ If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
927
+
928
+ Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
929
+
930
+ ```python
931
+ from decimal import Decimal
932
+
933
+ from pboot_validator import BaseModel, ConfigDict, ValidationError
934
+
935
+ class Model(BaseModel):
936
+ value: str
937
+
938
+ try:
939
+ print(Model(value=42))
940
+ except ValidationError as e:
941
+ print(e)
942
+ '''
943
+ 1 validation error for Model
944
+ value
945
+ Input should be a valid string [type=string_type, input_value=42, input_type=int]
946
+ '''
947
+
948
+ class Model(BaseModel):
949
+ model_config = ConfigDict(coerce_numbers_to_str=True)
950
+
951
+ value: str
952
+
953
+ repr(Model(value=42).value)
954
+ #> "42"
955
+ repr(Model(value=42.13).value)
956
+ #> "42.13"
957
+ repr(Model(value=Decimal('42.13')).value)
958
+ #> "42.13"
959
+ ```
960
+ """
961
+
962
+ regex_engine: Literal['rust-regex', 'python-re']
963
+ """
964
+ The regex engine to be used for pattern validation.
965
+ Defaults to `'rust-regex'`.
966
+
967
+ - `'rust-regex'` uses the [`regex`](https://docs.rs/regex) Rust crate,
968
+ which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
969
+ - `'python-re'` use the [`re`][] module, which supports all regex features, but may be slower.
970
+
971
+ !!! note
972
+ If you use a compiled regex pattern, the `'python-re'` engine will be used regardless of this setting.
973
+ This is so that flags such as [`re.IGNORECASE`][] are respected.
974
+
975
+ ```python
976
+ from pboot_validator import BaseModel, ConfigDict, Field, ValidationError
977
+
978
+ class Model(BaseModel):
979
+ model_config = ConfigDict(regex_engine='python-re')
980
+
981
+ value: str = Field(pattern=r'^abc(?=def)')
982
+
983
+ print(Model(value='abcdef').value)
984
+ #> abcdef
985
+
986
+ try:
987
+ print(Model(value='abxyzcdef'))
988
+ except ValidationError as e:
989
+ print(e)
990
+ '''
991
+ 1 validation error for Model
992
+ value
993
+ String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
994
+ '''
995
+ ```
996
+
997
+ /// version-added | v2.5
998
+ ///
999
+ """
1000
+
1001
+ validation_error_cause: bool
1002
+ """
1003
+ If `True`, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to `False`.
1004
+
1005
+ Note:
1006
+ Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
1007
+
1008
+ Note:
1009
+ The structure of validation errors are likely to change in future Pydantic versions. Pydantic offers no guarantees about their structure. Should be used for visual traceback debugging only.
1010
+
1011
+ /// version-added | v2.5
1012
+ ///
1013
+ """
1014
+
1015
+ use_attribute_docstrings: bool
1016
+ '''
1017
+ Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
1018
+ should be used for field descriptions. Defaults to `False`.
1019
+
1020
+ ```python
1021
+ from pboot_validator import BaseModel, ConfigDict, Field
1022
+
1023
+
1024
+ class Model(BaseModel):
1025
+ model_config = ConfigDict(use_attribute_docstrings=True)
1026
+
1027
+ x: str
1028
+ """
1029
+ Example of an attribute docstring
1030
+ """
1031
+
1032
+ y: int = Field(description="Description in Field")
1033
+ """
1034
+ Description in Field overrides attribute docstring
1035
+ """
1036
+
1037
+
1038
+ print(Model.model_fields["x"].description)
1039
+ # > Example of an attribute docstring
1040
+ print(Model.model_fields["y"].description)
1041
+ # > Description in Field
1042
+ ```
1043
+ This requires the source code of the class to be available at runtime (and so won't work in the interactive interpreter shell).
1044
+
1045
+ !!! warning "Usage with `TypedDict` and stdlib dataclasses"
1046
+ Due to current limitations, attribute docstrings detection may not work as expected when using
1047
+ [`TypedDict`][typing.TypedDict] and stdlib dataclasses, in particular when:
1048
+
1049
+ - inheritance is being used.
1050
+ - multiple classes have the same name in the same source file (unless Python 3.13 or greater is used).
1051
+
1052
+ /// version-added | v2.7
1053
+ ///
1054
+ '''
1055
+
1056
+ cache_strings: bool | Literal['all', 'keys', 'none']
1057
+ """
1058
+ Whether to cache strings to avoid constructing new Python objects. Defaults to True.
1059
+
1060
+ Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
1061
+
1062
+ - `True` or `'all'` (the default): cache all strings
1063
+ - `'keys'`: cache only dictionary keys
1064
+ - `False` or `'none'`: no caching
1065
+
1066
+ !!! note
1067
+ `True` or `'all'` is required to cache strings during general validation because
1068
+ validators don't know if they're in a key or a value.
1069
+
1070
+ !!! tip
1071
+ If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
1072
+ as the performance difference is minimal if repeated strings are rare.
1073
+
1074
+ /// version-added | v2.7
1075
+ ///
1076
+ """
1077
+
1078
+ validate_by_alias: bool
1079
+ """
1080
+ Whether an aliased field may be populated by its alias. Defaults to `True`.
1081
+
1082
+ Here's an example of disabling validation by alias:
1083
+
1084
+ ```py
1085
+ from pboot_validator import BaseModel, ConfigDict, Field
1086
+
1087
+ class Model(BaseModel):
1088
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=False)
1089
+
1090
+ my_field: str = Field(validation_alias='my_alias') # (1)!
1091
+
1092
+ m = Model(my_field='foo') # (2)!
1093
+ print(m)
1094
+ #> my_field='foo'
1095
+ ```
1096
+
1097
+ 1. The field `'my_field'` has an alias `'my_alias'`.
1098
+ 2. The model can only be populated by the attribute name `'my_field'`.
1099
+
1100
+ !!! warning
1101
+ You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
1102
+ This would make it impossible to populate an attribute.
1103
+
1104
+ See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
1105
+
1106
+ If you set `validate_by_alias` to `False`, under the hood, Pydantic dynamically sets
1107
+ `validate_by_name` to `True` to ensure that validation can still occur.
1108
+
1109
+ /// version-added | v2.11
1110
+ This setting was introduced in conjunction with [`validate_by_name`][pboot_validator.ConfigDict.validate_by_name]
1111
+ to empower users with more fine grained validation control.
1112
+ ///
1113
+ """
1114
+
1115
+ validate_by_name: bool
1116
+ """
1117
+ Whether an aliased field may be populated by its name as given by the model
1118
+ attribute. Defaults to `False`.
1119
+
1120
+ ```python
1121
+ from pboot_validator import BaseModel, ConfigDict, Field
1122
+
1123
+ class Model(BaseModel):
1124
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
1125
+
1126
+ my_field: str = Field(validation_alias='my_alias') # (1)!
1127
+
1128
+ m = Model(my_alias='foo') # (2)!
1129
+ print(m)
1130
+ #> my_field='foo'
1131
+
1132
+ m = Model(my_field='foo') # (3)!
1133
+ print(m)
1134
+ #> my_field='foo'
1135
+ ```
1136
+
1137
+ 1. The field `'my_field'` has an alias `'my_alias'`.
1138
+ 2. The model is populated by the alias `'my_alias'`.
1139
+ 3. The model is populated by the attribute name `'my_field'`.
1140
+
1141
+ !!! warning
1142
+ You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
1143
+ This would make it impossible to populate an attribute.
1144
+
1145
+ See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
1146
+
1147
+ /// version-added | v2.11
1148
+ This setting was introduced in conjunction with [`validate_by_alias`][pboot_validator.ConfigDict.validate_by_alias]
1149
+ to empower users with more fine grained validation control. It is an alternative to [`populate_by_name`][pboot_validator.ConfigDict.populate_by_name],
1150
+ that enables validation by name **and** by alias.
1151
+ ///
1152
+ """
1153
+
1154
+ serialize_by_alias: bool
1155
+ """
1156
+ Whether an aliased field should be serialized by its alias. Defaults to `False`.
1157
+
1158
+ Note: In v2.11, `serialize_by_alias` was introduced to address the
1159
+ [popular request](https://github.com/pydantic/pydantic/issues/8379)
1160
+ for consistency with alias behavior for validation and serialization settings.
1161
+ In v3, the default value is expected to change to `True` for consistency with the validation default.
1162
+
1163
+ ```python
1164
+ from pboot_validator import BaseModel, ConfigDict, Field
1165
+
1166
+ class Model(BaseModel):
1167
+ model_config = ConfigDict(serialize_by_alias=True)
1168
+
1169
+ my_field: str = Field(serialization_alias='my_alias') # (1)!
1170
+
1171
+ m = Model(my_field='foo')
1172
+ print(m.model_dump()) # (2)!
1173
+ #> {'my_alias': 'foo'}
1174
+ ```
1175
+
1176
+ 1. The field `'my_field'` has an alias `'my_alias'`.
1177
+ 2. The model is serialized using the alias `'my_alias'` for the `'my_field'` attribute.
1178
+
1179
+
1180
+ /// version-added | v2.11
1181
+ This setting was introduced to address the [popular request](https://github.com/pydantic/pydantic/issues/8379)
1182
+ for consistency with alias behavior for validation and serialization.
1183
+
1184
+ In v3, the default value is expected to change to `True` for consistency with the validation default.
1185
+ ///
1186
+ """
1187
+
1188
+ url_preserve_empty_path: bool
1189
+ """
1190
+ Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`.
1191
+
1192
+ ```python
1193
+ from pboot_validator import AnyUrl, BaseModel, ConfigDict
1194
+
1195
+ class Model(BaseModel):
1196
+ model_config = ConfigDict(url_preserve_empty_path=True)
1197
+
1198
+ url: AnyUrl
1199
+
1200
+ m = Model(url='https://example.com')
1201
+ print(m.url)
1202
+ #> https://example.com
1203
+ ```
1204
+
1205
+ /// version-added | v2.12
1206
+ ///
1207
+ """
1208
+
1209
+ polymorphic_serialization: bool
1210
+ """
1211
+ Whether to use polymorphic serialization for subclasses of the model or Pydantic dataclass. Defaults to `False`.
1212
+ """
1213
+
1214
+
1215
+ _TypeT = TypeVar('_TypeT', bound=type)
1216
+
1217
+
1218
+ @overload
1219
+ @deprecated('Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead.')
1220
+ def with_config(*, config: ConfigDict) -> Callable[[_TypeT], _TypeT]: ...
1221
+
1222
+
1223
+ @overload
1224
+ def with_config(config: ConfigDict, /) -> Callable[[_TypeT], _TypeT]: ...
1225
+
1226
+
1227
+ @overload
1228
+ def with_config(**config: Unpack[ConfigDict]) -> Callable[[_TypeT], _TypeT]: ...
1229
+
1230
+
1231
+ def with_config(config: ConfigDict | None = None, /, **kwargs: Any) -> Callable[[_TypeT], _TypeT]:
1232
+ """!!! abstract "Usage Documentation"
1233
+ [Configuration with other types](../concepts/config.md#configuration-on-other-supported-types)
1234
+
1235
+ A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
1236
+
1237
+ Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
1238
+ especially with `TypedDict`.
1239
+
1240
+ !!! example "Usage"
1241
+
1242
+ ```python
1243
+ from typing_extensions import TypedDict
1244
+
1245
+ from pboot_validator import ConfigDict, TypeAdapter, with_config
1246
+
1247
+ @with_config(ConfigDict(str_to_lower=True))
1248
+ class TD(TypedDict):
1249
+ x: str
1250
+
1251
+ ta = TypeAdapter(TD)
1252
+
1253
+ print(ta.validate_python({'x': 'ABC'}))
1254
+ #> {'x': 'abc'}
1255
+ ```
1256
+
1257
+ /// deprecated-removed | v2.11 v3
1258
+ Passing `config` as a keyword argument.
1259
+ ///
1260
+
1261
+ /// version-changed | v2.11
1262
+ Keyword arguments can be provided directly instead of a config dictionary.
1263
+ ///
1264
+ """
1265
+ if config is not None and kwargs:
1266
+ raise ValueError('Cannot specify both `config` and keyword arguments')
1267
+
1268
+ if len(kwargs) == 1 and (kwargs_conf := kwargs.get('config')) is not None:
1269
+ warnings.warn(
1270
+ 'Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead',
1271
+ category=PydanticDeprecatedSince211,
1272
+ stacklevel=2,
1273
+ )
1274
+ final_config = cast(ConfigDict, kwargs_conf)
1275
+ else:
1276
+ final_config = config if config is not None else cast(ConfigDict, kwargs)
1277
+
1278
+ def inner(class_: _TypeT, /) -> _TypeT:
1279
+ # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
1280
+ # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
1281
+ # common mistakes, we at least check for `class_` to not be a Pydantic model.
1282
+ from ._internal._utils import is_model_class
1283
+
1284
+ if is_model_class(class_):
1285
+ raise PydanticUserError(
1286
+ f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
1287
+ code='with-config-on-model',
1288
+ )
1289
+ class_.__pydantic_config__ = final_config
1290
+ return class_
1291
+
1292
+ return inner
1293
+
1294
+
1295
+ __getattr__ = getattr_migration(__name__)