Coverage for pydantic/config.py: 100.00%
106 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-13 19:35 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-13 19:35 +0000
1"""Configuration for Pydantic models."""
3from __future__ import annotations as _annotations 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
5from re import Pattern 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
6from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
8from typing_extensions import TypeAlias, TypedDict 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
10from ._migration import getattr_migration 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
11from .aliases import AliasGenerator 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
12from .errors import PydanticUserError 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
14if TYPE_CHECKING: 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
15 from ._internal._generate_schema import GenerateSchema as _GenerateSchema
16 from .fields import ComputedFieldInfo, FieldInfo
18__all__ = ('ConfigDict', 'with_config') 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
21JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
22JsonDict: TypeAlias = dict[str, JsonValue] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
24JsonEncoder = Callable[[Any], Any] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
26JsonSchemaExtraCallable: TypeAlias = Union[ 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
27 Callable[[JsonDict], None],
28 Callable[[JsonDict, type[Any]], None],
29]
31ExtraValues = Literal['allow', 'ignore', 'forbid'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
34class ConfigDict(TypedDict, total=False): 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
35 """A TypedDict for configuring Pydantic behaviour."""
37 title: str | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
38 """The title for the generated JSON schema, defaults to the model's name""" 1abcdefghijklmnopqzABCDErstuvwxy
40 model_title_generator: Callable[[type], str] | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
41 """A callable that takes a model class and returns the title for it. Defaults to `None`.""" 1abcdefghijklmnopqzABCDErstuvwxy
43 field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
44 """A callable that takes a field's name and info and returns title for it. Defaults to `None`.""" 1abcdefghijklmnopqzABCDErstuvwxy
46 str_to_lower: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
47 """Whether to convert all characters to lowercase for str types. Defaults to `False`.""" 1abcdefghijklmnopqzABCDErstuvwxy
49 str_to_upper: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
50 """Whether to convert all characters to uppercase for str types. Defaults to `False`.""" 1abcdefghijklmnopqzABCDErstuvwxy
52 str_strip_whitespace: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
53 """Whether to strip leading and trailing whitespace for str types.""" 1abcdefghijklmnopqzABCDErstuvwxy
55 str_min_length: int 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
56 """The minimum length for str types. Defaults to `None`.""" 1abcdefghijklmnopqzABCDErstuvwxy
58 str_max_length: int | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
59 """The maximum length for str types. Defaults to `None`.""" 1abcdefghijklmnopqzABCDErstuvwxy
61 extra: ExtraValues | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
62 ''' 1abcdefghijklmnopqzABCDErstuvwxy
63 Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`.
65 Three configuration values are available:
67 - `'ignore'`: Providing extra data is ignored (the default):
68 ```python
69 from pydantic import BaseModel, ConfigDict
71 class User(BaseModel):
72 model_config = ConfigDict(extra='ignore') # (1)!
74 name: str
76 user = User(name='John Doe', age=20) # (2)!
77 print(user)
78 #> name='John Doe'
79 ```
81 1. This is the default behaviour.
82 2. The `age` argument is ignored.
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 pydantic import BaseModel, ConfigDict, ValidationError
90 class Model(BaseModel):
91 x: int
93 model_config = ConfigDict(extra='forbid')
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 ```
107 - `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute:
108 ```python
109 from pydantic import BaseModel, ConfigDict
112 class Model(BaseModel):
113 x: int
115 model_config = ConfigDict(extra='allow')
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 pydantic import BaseModel, ConfigDict, Field, ValidationError
127 class Model(BaseModel):
128 __pydantic_extra__: dict[str, int] = Field(init=False) # (1)!
130 x: int
132 model_config = ConfigDict(extra='allow')
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 """
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 ```
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 '''
156 frozen: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
157 """ 1abcdefghijklmnopqzABCDErstuvwxy
158 Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
159 a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
160 attributes are hashable. Defaults to `False`.
162 Note:
163 On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
164 """
166 populate_by_name: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
167 """ 1abcdefghijklmnopqzABCDErstuvwxy
168 Whether an aliased field may be populated by its name as given by the model
169 attribute, as well as the alias. Defaults to `False`.
171 Note:
172 The name of this configuration setting was changed in **v2.0** from
173 `allow_population_by_field_name` to `populate_by_name`.
175 ```python
176 from pydantic import BaseModel, ConfigDict, Field
178 class User(BaseModel):
179 model_config = ConfigDict(populate_by_name=True)
181 name: str = Field(alias='full_name') # (1)!
182 age: int
184 user = User(full_name='John Doe', age=20) # (2)!
185 print(user)
186 #> name='John Doe' age=20
187 user = User(name='John Doe', age=20) # (3)!
188 print(user)
189 #> name='John Doe' age=20
190 ```
192 1. The field `'name'` has an alias `'full_name'`.
193 2. The model is populated by the alias `'full_name'`.
194 3. The model is populated by the field name `'name'`.
195 """
197 use_enum_values: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
198 """ 1abcdefghijklmnopqzABCDErstuvwxy
199 Whether to populate models with the `value` property of enums, rather than the raw enum.
200 This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
202 !!! note
203 If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
204 for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
205 enum's value occurs during validation, not serialization.
207 ```python
208 from enum import Enum
209 from typing import Optional
211 from pydantic import BaseModel, ConfigDict, Field
213 class SomeEnum(Enum):
214 FOO = 'foo'
215 BAR = 'bar'
216 BAZ = 'baz'
218 class SomeModel(BaseModel):
219 model_config = ConfigDict(use_enum_values=True)
221 some_enum: SomeEnum
222 another_enum: Optional[SomeEnum] = Field(
223 default=SomeEnum.FOO, validate_default=True
224 )
226 model1 = SomeModel(some_enum=SomeEnum.BAR)
227 print(model1.model_dump())
228 #> {'some_enum': 'bar', 'another_enum': 'foo'}
230 model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
231 print(model2.model_dump())
232 #> {'some_enum': 'bar', 'another_enum': 'baz'}
233 ```
234 """
236 validate_assignment: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
237 """ 1abcdefghijklmnopqzABCDErstuvwxy
238 Whether to validate the data when the model is changed. Defaults to `False`.
240 The default behavior of Pydantic is to validate the data when the model is created.
242 In case the user changes the data after the model is created, the model is _not_ revalidated.
244 ```python
245 from pydantic import BaseModel
247 class User(BaseModel):
248 name: str
250 user = User(name='John Doe') # (1)!
251 print(user)
252 #> name='John Doe'
253 user.name = 123 # (1)!
254 print(user)
255 #> name=123
256 ```
258 1. The validation happens only when the model is created.
259 2. The validation does not happen when the data is changed.
261 In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
263 ```python
264 from pydantic import BaseModel, ValidationError
266 class User(BaseModel, validate_assignment=True): # (1)!
267 name: str
269 user = User(name='John Doe') # (2)!
270 print(user)
271 #> name='John Doe'
272 try:
273 user.name = 123 # (3)!
274 except ValidationError as e:
275 print(e)
276 '''
277 1 validation error for User
278 name
279 Input should be a valid string [type=string_type, input_value=123, input_type=int]
280 '''
281 ```
283 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
284 2. The validation happens when the model is created.
285 3. The validation _also_ happens when the data is changed.
286 """
288 arbitrary_types_allowed: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
289 """ 1abcdefghijklmnopqzABCDErstuvwxy
290 Whether arbitrary types are allowed for field types. Defaults to `False`.
292 ```python
293 from pydantic import BaseModel, ConfigDict, ValidationError
295 # This is not a pydantic model, it's an arbitrary class
296 class Pet:
297 def __init__(self, name: str):
298 self.name = name
300 class Model(BaseModel):
301 model_config = ConfigDict(arbitrary_types_allowed=True)
303 pet: Pet
304 owner: str
306 pet = Pet(name='Hedwig')
307 # A simple check of instance type is used to validate the data
308 model = Model(owner='Harry', pet=pet)
309 print(model)
310 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
311 print(model.pet)
312 #> <__main__.Pet object at 0x0123456789ab>
313 print(model.pet.name)
314 #> Hedwig
315 print(type(model.pet))
316 #> <class '__main__.Pet'>
317 try:
318 # If the value is not an instance of the type, it's invalid
319 Model(owner='Harry', pet='Hedwig')
320 except ValidationError as e:
321 print(e)
322 '''
323 1 validation error for Model
324 pet
325 Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
326 '''
328 # Nothing in the instance of the arbitrary type is checked
329 # Here name probably should have been a str, but it's not validated
330 pet2 = Pet(name=42)
331 model2 = Model(owner='Harry', pet=pet2)
332 print(model2)
333 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
334 print(model2.pet)
335 #> <__main__.Pet object at 0x0123456789ab>
336 print(model2.pet.name)
337 #> 42
338 print(type(model2.pet))
339 #> <class '__main__.Pet'>
340 ```
341 """
343 from_attributes: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
344 """ 1abcdefghijklmnopqzABCDErstuvwxy
345 Whether to build models and look up discriminators of tagged unions using python object attributes.
346 """
348 loc_by_alias: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
349 """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`.""" 1abcdefghijklmnopqzABCDErstuvwxy
351 alias_generator: Callable[[str], str] | AliasGenerator | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
352 """ 1abcdefghijklmnopqzABCDErstuvwxy
353 A callable that takes a field name and returns an alias for it
354 or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
356 When using a callable, the alias generator is used for both validation and serialization.
357 If you want to use different alias generators for validation and serialization, you can use
358 [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.
360 If data source field names do not match your code style (e. g. CamelCase fields),
361 you can automatically generate aliases using `alias_generator`. Here's an example with
362 a basic callable:
364 ```python
365 from pydantic import BaseModel, ConfigDict
366 from pydantic.alias_generators import to_pascal
368 class Voice(BaseModel):
369 model_config = ConfigDict(alias_generator=to_pascal)
371 name: str
372 language_code: str
374 voice = Voice(Name='Filiz', LanguageCode='tr-TR')
375 print(voice.language_code)
376 #> tr-TR
377 print(voice.model_dump(by_alias=True))
378 #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
379 ```
381 If you want to use different alias generators for validation and serialization, you can use
382 [`AliasGenerator`][pydantic.aliases.AliasGenerator].
384 ```python
385 from pydantic import AliasGenerator, BaseModel, ConfigDict
386 from pydantic.alias_generators import to_camel, to_pascal
388 class Athlete(BaseModel):
389 first_name: str
390 last_name: str
391 sport: str
393 model_config = ConfigDict(
394 alias_generator=AliasGenerator(
395 validation_alias=to_camel,
396 serialization_alias=to_pascal,
397 )
398 )
400 athlete = Athlete(firstName='John', lastName='Doe', sport='track')
401 print(athlete.model_dump(by_alias=True))
402 #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
403 ```
405 Note:
406 Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
407 [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
408 """
410 ignored_types: tuple[type, ...] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
411 """A tuple of types that may occur as values of class attributes without annotations. This is 1abcdefghijklmnopqzABCDErstuvwxy
412 typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
413 class without an annotation and has a type that is not in this tuple (or otherwise recognized by
414 _pydantic_), an error will be raised. Defaults to `()`.
415 """
417 allow_inf_nan: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
418 """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`.""" 1abcdefghijklmnopqzABCDErstuvwxy
420 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
421 """A dict or callable to provide extra JSON schema properties. Defaults to `None`.""" 1abcdefghijklmnopqzABCDErstuvwxy
423 json_encoders: dict[type[object], JsonEncoder] | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
424 """ 1abcdefghijklmnopqzABCDErstuvwxy
425 A `dict` of custom JSON encoders for specific types. Defaults to `None`.
427 !!! warning "Deprecated"
428 This config option is a carryover from v1.
429 We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
430 It is still deprecated and will likely be removed in the future.
431 """
433 # new in V2
434 strict: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
435 """ 1abcdefghijklmnopqzABCDErstuvwxy
436 _(new in V2)_ If `True`, strict validation is applied to all fields on the model.
438 By default, Pydantic attempts to coerce values to the correct type, when possible.
440 There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
441 does not match the field's type annotation.
443 To configure strict mode for all fields on a model, you can set `strict=True` on the model.
445 ```python
446 from pydantic import BaseModel, ConfigDict
448 class Model(BaseModel):
449 model_config = ConfigDict(strict=True)
451 name: str
452 age: int
453 ```
455 See [Strict Mode](../concepts/strict_mode.md) for more details.
457 See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
458 strict and lax modes.
459 """
460 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
461 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
462 """ 1abcdefghijklmnopqzABCDErstuvwxy
463 When and how to revalidate models and dataclasses during validation. Accepts the string
464 values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`.
466 - `'never'` will not revalidate models and dataclasses during validation
467 - `'always'` will revalidate models and dataclasses during validation
468 - `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a
469 subclass of the model or dataclass
471 By default, model and dataclass instances are not revalidated during validation.
473 ```python
474 from pydantic import BaseModel
476 class User(BaseModel, revalidate_instances='never'): # (1)!
477 hobbies: list[str]
479 class SubUser(User):
480 sins: list[str]
482 class Transaction(BaseModel):
483 user: User
485 my_user = User(hobbies=['reading'])
486 t = Transaction(user=my_user)
487 print(t)
488 #> user=User(hobbies=['reading'])
490 my_user.hobbies = [1] # (2)!
491 t = Transaction(user=my_user) # (3)!
492 print(t)
493 #> user=User(hobbies=[1])
495 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
496 t = Transaction(user=my_sub_user)
497 print(t)
498 #> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
499 ```
501 1. `revalidate_instances` is set to `'never'` by **default.
502 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config.
503 3. Since `revalidate_instances` is set to `never`, this is not revalidated.
505 If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'`
506 in the model's config.
508 ```python
509 from pydantic import BaseModel, ValidationError
511 class User(BaseModel, revalidate_instances='always'): # (1)!
512 hobbies: list[str]
514 class SubUser(User):
515 sins: list[str]
517 class Transaction(BaseModel):
518 user: User
520 my_user = User(hobbies=['reading'])
521 t = Transaction(user=my_user)
522 print(t)
523 #> user=User(hobbies=['reading'])
525 my_user.hobbies = [1]
526 try:
527 t = Transaction(user=my_user) # (2)!
528 except ValidationError as e:
529 print(e)
530 '''
531 1 validation error for Transaction
532 user.hobbies.0
533 Input should be a valid string [type=string_type, input_value=1, input_type=int]
534 '''
536 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
537 t = Transaction(user=my_sub_user)
538 print(t) # (3)!
539 #> user=User(hobbies=['scuba diving'])
540 ```
542 1. `revalidate_instances` is set to `'always'`.
543 2. The model is revalidated, since `revalidate_instances` is set to `'always'`.
544 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
546 It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances
547 of subclasses of the model.
549 ```python
550 from pydantic import BaseModel
552 class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
553 hobbies: list[str]
555 class SubUser(User):
556 sins: list[str]
558 class Transaction(BaseModel):
559 user: User
561 my_user = User(hobbies=['reading'])
562 t = Transaction(user=my_user)
563 print(t)
564 #> user=User(hobbies=['reading'])
566 my_user.hobbies = [1]
567 t = Transaction(user=my_user) # (2)!
568 print(t)
569 #> user=User(hobbies=[1])
571 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
572 t = Transaction(user=my_sub_user)
573 print(t) # (3)!
574 #> user=User(hobbies=['scuba diving'])
575 ```
577 1. `revalidate_instances` is set to `'subclass-instances'`.
578 2. This is not revalidated, since `my_user` is not a subclass of `User`.
579 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
580 """
582 ser_json_timedelta: Literal['iso8601', 'float'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
583 """ 1abcdefghijklmnopqzABCDErstuvwxy
584 The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
585 `'float'`. Defaults to `'iso8601'`.
587 - `'iso8601'` will serialize timedeltas to ISO 8601 durations.
588 - `'float'` will serialize timedeltas to the total number of seconds.
589 """
591 ser_json_bytes: Literal['utf8', 'base64', 'hex'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
592 """ 1abcdefghijklmnopqzABCDErstuvwxy
593 The encoding of JSON serialized bytes. Defaults to `'utf8'`.
594 Set equal to `val_json_bytes` to get back an equal value after serialization round trip.
596 - `'utf8'` will serialize bytes to UTF-8 strings.
597 - `'base64'` will serialize bytes to URL safe base64 strings.
598 - `'hex'` will serialize bytes to hexadecimal strings.
599 """
601 val_json_bytes: Literal['utf8', 'base64', 'hex'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
602 """ 1abcdefghijklmnopqzABCDErstuvwxy
603 The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`.
604 Set equal to `ser_json_bytes` to get back an equal value after serialization round trip.
606 - `'utf8'` will deserialize UTF-8 strings to bytes.
607 - `'base64'` will deserialize URL safe base64 strings to bytes.
608 - `'hex'` will deserialize hexadecimal strings to bytes.
609 """
611 ser_json_inf_nan: Literal['null', 'constants', 'strings'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
612 """ 1abcdefghijklmnopqzABCDErstuvwxy
613 The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
615 - `'null'` will serialize infinity and NaN values as `null`.
616 - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
617 - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.
618 """
620 # whether to validate default values during validation, default False
621 validate_default: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
622 """Whether to validate default values during validation. Defaults to `False`.""" 1abcdefghijklmnopqzABCDErstuvwxy
624 validate_return: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
625 """Whether to validate the return value from call validators. Defaults to `False`.""" 1abcdefghijklmnopqzABCDErstuvwxy
627 protected_namespaces: tuple[str | Pattern[str], ...] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
628 """ 1abcdefghijklmnopqzABCDErstuvwxy
629 A `tuple` of strings and/or patterns that prevent models from having fields with names that conflict with them.
630 For strings, we match on a prefix basis. Ex, if 'dog' is in the protected namespace, 'dog_name' will be protected.
631 For patterns, we match on the entire field name. Ex, if `re.compile(r'^dog$')` is in the protected namespace, 'dog' will be protected, but 'dog_name' will not be.
632 Defaults to `('model_validate', 'model_dump',)`.
634 The reason we've selected these is to prevent collisions with other validation / dumping formats
635 in the future - ex, `model_validate_{some_newly_supported_format}`.
637 Before v2.10, Pydantic used `('model_',)` as the default value for this setting to
638 prevent collisions between model attributes and `BaseModel`'s own methods. This was changed
639 in v2.10 given feedback that this restriction was limiting in AI and data science contexts,
640 where it is common to have fields with names like `model_id`, `model_input`, `model_output`, etc.
642 For more details, see https://github.com/pydantic/pydantic/issues/10315.
644 ```python
645 import warnings
647 from pydantic import BaseModel
649 warnings.filterwarnings('error') # Raise warnings as errors
651 try:
653 class Model(BaseModel):
654 model_dump_something: str
656 except UserWarning as e:
657 print(e)
658 '''
659 Field "model_dump_something" in Model has conflict with protected namespace "model_dump".
661 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('model_validate',)`.
662 '''
663 ```
665 You can customize this behavior using the `protected_namespaces` setting:
667 ```python {test="skip"}
668 import re
669 import warnings
671 from pydantic import BaseModel, ConfigDict
673 with warnings.catch_warnings(record=True) as caught_warnings:
674 warnings.simplefilter('always') # Catch all warnings
676 class Model(BaseModel):
677 safe_field: str
678 also_protect_field: str
679 protect_this: str
681 model_config = ConfigDict(
682 protected_namespaces=(
683 'protect_me_',
684 'also_protect_',
685 re.compile('^protect_this$'),
686 )
687 )
689 for warning in caught_warnings:
690 print(f'{warning.message}')
691 '''
692 Field "also_protect_field" in Model has conflict with protected namespace "also_protect_".
693 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', re.compile('^protect_this$'))`.
695 Field "protect_this" in Model has conflict with protected namespace "re.compile('^protect_this$')".
696 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', 'also_protect_')`.
697 '''
698 ```
700 While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
701 an error _is_ raised if there is an actual collision with an existing attribute:
703 ```python
704 from pydantic import BaseModel, ConfigDict
706 try:
708 class Model(BaseModel):
709 model_validate: str
711 model_config = ConfigDict(protected_namespaces=('model_',))
713 except NameError as e:
714 print(e)
715 '''
716 Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
717 '''
718 ```
719 """
721 hide_input_in_errors: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
722 """ 1abcdefghijklmnopqzABCDErstuvwxy
723 Whether to hide inputs when printing errors. Defaults to `False`.
725 Pydantic shows the input value and type when it raises `ValidationError` during the validation.
727 ```python
728 from pydantic import BaseModel, ValidationError
730 class Model(BaseModel):
731 a: str
733 try:
734 Model(a=123)
735 except ValidationError as e:
736 print(e)
737 '''
738 1 validation error for Model
739 a
740 Input should be a valid string [type=string_type, input_value=123, input_type=int]
741 '''
742 ```
744 You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
746 ```python
747 from pydantic import BaseModel, ConfigDict, ValidationError
749 class Model(BaseModel):
750 a: str
751 model_config = ConfigDict(hide_input_in_errors=True)
753 try:
754 Model(a=123)
755 except ValidationError as e:
756 print(e)
757 '''
758 1 validation error for Model
759 a
760 Input should be a valid string [type=string_type]
761 '''
762 ```
763 """
765 defer_build: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
766 """ 1abcdefghijklmnopqzABCDErstuvwxy
767 Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
769 This can be useful to avoid the overhead of building models which are only
770 used nested within other models, or when you want to manually define type namespace via
771 [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
773 Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances.
774 """
776 plugin_settings: dict[str, object] | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
777 """A `dict` of settings for plugins. Defaults to `None`.""" 1abcdefghijklmnopqzABCDErstuvwxy
779 schema_generator: type[_GenerateSchema] | None 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
780 """ 1abcdefghijklmnopqzABCDErstuvwxy
781 !!! warning
782 `schema_generator` is deprecated in v2.10.
784 Prior to v2.10, this setting was advertised as highly subject to change.
785 It's possible that this interface may once again become public once the internal core schema generation
786 API is more stable, but that will likely come after significant performance improvements have been made.
787 """
789 json_schema_serialization_defaults_required: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
790 """ 1abcdefghijklmnopqzABCDErstuvwxy
791 Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
793 This ensures that the serialization schema will reflect the fact a field with a default will always be present
794 when serializing the model, even though it is not required for validation.
796 However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
797 between validation and serialization, and don't mind fields with defaults being marked as not required during
798 serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
800 ```python
801 from pydantic import BaseModel, ConfigDict
803 class Model(BaseModel):
804 a: str = 'a'
806 model_config = ConfigDict(json_schema_serialization_defaults_required=True)
808 print(Model.model_json_schema(mode='validation'))
809 '''
810 {
811 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
812 'title': 'Model',
813 'type': 'object',
814 }
815 '''
816 print(Model.model_json_schema(mode='serialization'))
817 '''
818 {
819 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
820 'required': ['a'],
821 'title': 'Model',
822 'type': 'object',
823 }
824 '''
825 ```
826 """
828 json_schema_mode_override: Literal['validation', 'serialization', None] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
829 """ 1abcdefghijklmnopqzABCDErstuvwxy
830 If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
831 the function call. Defaults to `None`.
833 This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
834 validation schema.
836 It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
837 and serialization that must both be referenced from the same schema; when this happens, we automatically append
838 `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
839 serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
840 the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
841 from being added to the definition references.
843 ```python
844 from pydantic import BaseModel, ConfigDict, Json
846 class Model(BaseModel):
847 a: Json[int] # requires a string to validate, but will dump an int
849 print(Model.model_json_schema(mode='serialization'))
850 '''
851 {
852 'properties': {'a': {'title': 'A', 'type': 'integer'}},
853 'required': ['a'],
854 'title': 'Model',
855 'type': 'object',
856 }
857 '''
859 class ForceInputModel(Model):
860 # the following ensures that even with mode='serialization', we
861 # will get the schema that would be generated for validation.
862 model_config = ConfigDict(json_schema_mode_override='validation')
864 print(ForceInputModel.model_json_schema(mode='serialization'))
865 '''
866 {
867 'properties': {
868 'a': {
869 'contentMediaType': 'application/json',
870 'contentSchema': {'type': 'integer'},
871 'title': 'A',
872 'type': 'string',
873 }
874 },
875 'required': ['a'],
876 'title': 'ForceInputModel',
877 'type': 'object',
878 }
879 '''
880 ```
881 """
883 coerce_numbers_to_str: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
884 """ 1abcdefghijklmnopqzABCDErstuvwxy
885 If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
887 Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
889 ```python
890 from decimal import Decimal
892 from pydantic import BaseModel, ConfigDict, ValidationError
894 class Model(BaseModel):
895 value: str
897 try:
898 print(Model(value=42))
899 except ValidationError as e:
900 print(e)
901 '''
902 1 validation error for Model
903 value
904 Input should be a valid string [type=string_type, input_value=42, input_type=int]
905 '''
907 class Model(BaseModel):
908 model_config = ConfigDict(coerce_numbers_to_str=True)
910 value: str
912 repr(Model(value=42).value)
913 #> "42"
914 repr(Model(value=42.13).value)
915 #> "42.13"
916 repr(Model(value=Decimal('42.13')).value)
917 #> "42.13"
918 ```
919 """
921 regex_engine: Literal['rust-regex', 'python-re'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
922 """ 1abcdefghijklmnopqzABCDErstuvwxy
923 The regex engine to be used for pattern validation.
924 Defaults to `'rust-regex'`.
926 - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
927 which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
928 - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
929 which supports all regex features, but may be slower.
931 !!! note
932 If you use a compiled regex pattern, the python-re engine will be used regardless of this setting.
933 This is so that flags such as `re.IGNORECASE` are respected.
935 ```python
936 from pydantic import BaseModel, ConfigDict, Field, ValidationError
938 class Model(BaseModel):
939 model_config = ConfigDict(regex_engine='python-re')
941 value: str = Field(pattern=r'^abc(?=def)')
943 print(Model(value='abcdef').value)
944 #> abcdef
946 try:
947 print(Model(value='abxyzcdef'))
948 except ValidationError as e:
949 print(e)
950 '''
951 1 validation error for Model
952 value
953 String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
954 '''
955 ```
956 """
958 validation_error_cause: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
959 """ 1abcdefghijklmnopqzABCDErstuvwxy
960 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`.
962 Note:
963 Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
965 Note:
966 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.
967 """
969 use_attribute_docstrings: bool 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
970 ''' 1abcdefghijklmnopqzABCDErstuvwxy
971 Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
972 should be used for field descriptions. Defaults to `False`.
974 Available in Pydantic v2.7+.
976 ```python
977 from pydantic import BaseModel, ConfigDict, Field
980 class Model(BaseModel):
981 model_config = ConfigDict(use_attribute_docstrings=True)
983 x: str
984 """
985 Example of an attribute docstring
986 """
988 y: int = Field(description="Description in Field")
989 """
990 Description in Field overrides attribute docstring
991 """
994 print(Model.model_fields["x"].description)
995 # > Example of an attribute docstring
996 print(Model.model_fields["y"].description)
997 # > Description in Field
998 ```
999 This requires the source code of the class to be available at runtime.
1001 !!! warning "Usage with `TypedDict` and stdlib dataclasses"
1002 Due to current limitations, attribute docstrings detection may not work as expected when using
1003 [`TypedDict`][typing.TypedDict] and stdlib dataclasses, in particular when:
1005 - inheritance is being used.
1006 - multiple classes have the same name in the same source file.
1007 '''
1009 cache_strings: bool | Literal['all', 'keys', 'none'] 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
1010 """ 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
1011 Whether to cache strings to avoid constructing new Python objects. Defaults to True.
1013 Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
1015 - `True` or `'all'` (the default): cache all strings
1016 - `'keys'`: cache only dictionary keys
1017 - `False` or `'none'`: no caching
1019 !!! note
1020 `True` or `'all'` is required to cache strings during general validation because
1021 validators don't know if they're in a key or a value.
1023 !!! tip
1024 If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
1025 as the performance difference is minimal if repeated strings are rare.
1026 """
1029_TypeT = TypeVar('_TypeT', bound=type) 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
1032def with_config(config: ConfigDict) -> Callable[[_TypeT], _TypeT]: 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy
1033 """!!! abstract "Usage Documentation"
1034 [Configuration with other types](../concepts/config.md#configuration-on-other-supported-types)
1036 A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
1038 Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
1039 especially with `TypedDict`.
1041 !!! example "Usage"
1043 ```python
1044 from typing_extensions import TypedDict
1046 from pydantic import ConfigDict, TypeAdapter, with_config
1048 @with_config(ConfigDict(str_to_lower=True))
1049 class Model(TypedDict):
1050 x: str
1052 ta = TypeAdapter(Model)
1054 print(ta.validate_python({'x': 'ABC'}))
1055 #> {'x': 'abc'}
1056 ```
1057 """
1059 def inner(class_: _TypeT, /) -> _TypeT: 1FGabcdefghHiIJjklmnopqKLrstuvwxy
1060 # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
1061 # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
1062 # common mistakes, we at least check for `class_` to not be a Pydantic model.
1063 from ._internal._utils import is_model_class 1FGabcdefghHiIJjklmnopqKLrstuvwxy
1065 if is_model_class(class_): 1FGabcdefghHiIJjklmnopqKLrstuvwxy
1066 raise PydanticUserError( 1FGabcdefghHiIJjklmnopqKLrstuvwxy
1067 f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
1068 code='with-config-on-model',
1069 )
1070 class_.__pydantic_config__ = config 1FGabcdefghHiIJjklmnopqKLrstuvwxy
1071 return class_ 1FGabcdefghHiIJjklmnopqKLrstuvwxy
1073 return inner 1FGabcdefghHiIJjklmnopqKLrstuvwxy
1076__getattr__ = getattr_migration(__name__) 1FGabcdefghHiIJjklmnopqMzABCDEKLrstuvwxy