Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic/config.py: 89%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""Configuration for Pydantic models."""
3from __future__ import annotations as _annotations
5import warnings
6from re import Pattern
7from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, cast, overload
9from typing_extensions import TypeAlias, TypedDict, Unpack, deprecated
11from ._migration import getattr_migration
12from .aliases import AliasGenerator
13from .errors import PydanticUserError
14from .warnings import PydanticDeprecatedSince211
16if TYPE_CHECKING:
17 from ._internal._generate_schema import GenerateSchema as _GenerateSchema
18 from .fields import ComputedFieldInfo, FieldInfo
20__all__ = ('ConfigDict', 'with_config')
23JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict']
24JsonDict: TypeAlias = dict[str, JsonValue]
26JsonEncoder = Callable[[Any], Any]
28JsonSchemaExtraCallable: TypeAlias = Union[
29 Callable[[JsonDict], None],
30 Callable[[JsonDict, type[Any]], None],
31]
33ExtraValues = Literal['allow', 'ignore', 'forbid']
36class ConfigDict(TypedDict, total=False):
37 """A TypedDict for configuring Pydantic behaviour."""
39 title: str | None
40 """The title for the generated JSON schema, defaults to the model's name"""
42 model_title_generator: Callable[[type], str] | None
43 """A callable that takes a model class and returns the title for it. Defaults to `None`."""
45 field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
46 """A callable that takes a field's name and info and returns title for it. Defaults to `None`."""
48 str_to_lower: bool
49 """Whether to convert all characters to lowercase for str types. Defaults to `False`."""
51 str_to_upper: bool
52 """Whether to convert all characters to uppercase for str types. Defaults to `False`."""
54 str_strip_whitespace: bool
55 """Whether to strip leading and trailing whitespace for str types."""
57 str_min_length: int
58 """The minimum length for str types. Defaults to `None`."""
60 str_max_length: int | None
61 """The maximum length for str types. Defaults to `None`."""
63 extra: ExtraValues | None
64 '''
65 Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`.
67 Three configuration values are available:
69 - `'ignore'`: Providing extra data is ignored (the default):
70 ```python
71 from pydantic import BaseModel, ConfigDict
73 class User(BaseModel):
74 model_config = ConfigDict(extra='ignore') # (1)!
76 name: str
78 user = User(name='John Doe', age=20) # (2)!
79 print(user)
80 #> name='John Doe'
81 ```
83 1. This is the default behaviour.
84 2. The `age` argument is ignored.
86 - `'forbid'`: Providing extra data is not permitted, and a [`ValidationError`][pydantic_core.ValidationError]
87 will be raised if this is the case:
88 ```python
89 from pydantic import BaseModel, ConfigDict, ValidationError
92 class Model(BaseModel):
93 x: int
95 model_config = ConfigDict(extra='forbid')
98 try:
99 Model(x=1, y='a')
100 except ValidationError as exc:
101 print(exc)
102 """
103 1 validation error for Model
104 y
105 Extra inputs are not permitted [type=extra_forbidden, input_value='a', input_type=str]
106 """
107 ```
109 - `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute:
110 ```python
111 from pydantic import BaseModel, ConfigDict
114 class Model(BaseModel):
115 x: int
117 model_config = ConfigDict(extra='allow')
120 m = Model(x=1, y='a')
121 assert m.__pydantic_extra__ == {'y': 'a'}
122 ```
123 By default, no validation will be applied to these extra items, but you can set a type for the values by overriding
124 the type annotation for `__pydantic_extra__`:
125 ```python
126 from pydantic import BaseModel, ConfigDict, Field, ValidationError
129 class Model(BaseModel):
130 __pydantic_extra__: dict[str, int] = Field(init=False) # (1)!
132 x: int
134 model_config = ConfigDict(extra='allow')
137 try:
138 Model(x=1, y='a')
139 except ValidationError as exc:
140 print(exc)
141 """
142 1 validation error for Model
143 y
144 Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
145 """
147 m = Model(x=1, y='2')
148 assert m.x == 1
149 assert m.y == 2
150 assert m.model_dump() == {'x': 1, 'y': 2}
151 assert m.__pydantic_extra__ == {'y': 2}
152 ```
154 1. The `= Field(init=False)` does not have any effect at runtime, but prevents the `__pydantic_extra__` field from
155 being included as a parameter to the model's `__init__` method by type checkers.
156 '''
158 frozen: bool
159 """
160 Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
161 a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
162 attributes are hashable. Defaults to `False`.
164 Note:
165 On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
166 """
168 populate_by_name: bool
169 """
170 Whether an aliased field may be populated by its name as given by the model
171 attribute, as well as the alias. Defaults to `False`.
173 !!! warning
174 `populate_by_name` usage is not recommended in v2.11+ and will be deprecated in v3.
175 Instead, you should use the [`validate_by_name`][pydantic.config.ConfigDict.validate_by_name] configuration setting.
177 When `validate_by_name=True` and `validate_by_alias=True`, this is strictly equivalent to the
178 previous behavior of `populate_by_name=True`.
180 In v2.11, we also introduced a [`validate_by_alias`][pydantic.config.ConfigDict.validate_by_alias] setting that introduces more fine grained
181 control for validation behavior.
183 Here's how you might go about using the new settings to achieve the same behavior:
185 ```python
186 from pydantic import BaseModel, ConfigDict, Field
188 class Model(BaseModel):
189 model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
191 my_field: str = Field(alias='my_alias') # (1)!
193 m = Model(my_alias='foo') # (2)!
194 print(m)
195 #> my_field='foo'
197 m = Model(my_alias='foo') # (3)!
198 print(m)
199 #> my_field='foo'
200 ```
202 1. The field `'my_field'` has an alias `'my_alias'`.
203 2. The model is populated by the alias `'my_alias'`.
204 3. The model is populated by the attribute name `'my_field'`.
205 """
207 use_enum_values: bool
208 """
209 Whether to populate models with the `value` property of enums, rather than the raw enum.
210 This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
212 !!! note
213 If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
214 for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
215 enum's value occurs during validation, not serialization.
217 ```python
218 from enum import Enum
219 from typing import Optional
221 from pydantic import BaseModel, ConfigDict, Field
223 class SomeEnum(Enum):
224 FOO = 'foo'
225 BAR = 'bar'
226 BAZ = 'baz'
228 class SomeModel(BaseModel):
229 model_config = ConfigDict(use_enum_values=True)
231 some_enum: SomeEnum
232 another_enum: Optional[SomeEnum] = Field(
233 default=SomeEnum.FOO, validate_default=True
234 )
236 model1 = SomeModel(some_enum=SomeEnum.BAR)
237 print(model1.model_dump())
238 #> {'some_enum': 'bar', 'another_enum': 'foo'}
240 model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
241 print(model2.model_dump())
242 #> {'some_enum': 'bar', 'another_enum': 'baz'}
243 ```
244 """
246 validate_assignment: bool
247 """
248 Whether to validate the data when the model is changed. Defaults to `False`.
250 The default behavior of Pydantic is to validate the data when the model is created.
252 In case the user changes the data after the model is created, the model is _not_ revalidated.
254 ```python
255 from pydantic import BaseModel
257 class User(BaseModel):
258 name: str
260 user = User(name='John Doe') # (1)!
261 print(user)
262 #> name='John Doe'
263 user.name = 123 # (1)!
264 print(user)
265 #> name=123
266 ```
268 1. The validation happens only when the model is created.
269 2. The validation does not happen when the data is changed.
271 In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
273 ```python
274 from pydantic import BaseModel, ValidationError
276 class User(BaseModel, validate_assignment=True): # (1)!
277 name: str
279 user = User(name='John Doe') # (2)!
280 print(user)
281 #> name='John Doe'
282 try:
283 user.name = 123 # (3)!
284 except ValidationError as e:
285 print(e)
286 '''
287 1 validation error for User
288 name
289 Input should be a valid string [type=string_type, input_value=123, input_type=int]
290 '''
291 ```
293 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
294 2. The validation happens when the model is created.
295 3. The validation _also_ happens when the data is changed.
296 """
298 arbitrary_types_allowed: bool
299 """
300 Whether arbitrary types are allowed for field types. Defaults to `False`.
302 ```python
303 from pydantic import BaseModel, ConfigDict, ValidationError
305 # This is not a pydantic model, it's an arbitrary class
306 class Pet:
307 def __init__(self, name: str):
308 self.name = name
310 class Model(BaseModel):
311 model_config = ConfigDict(arbitrary_types_allowed=True)
313 pet: Pet
314 owner: str
316 pet = Pet(name='Hedwig')
317 # A simple check of instance type is used to validate the data
318 model = Model(owner='Harry', pet=pet)
319 print(model)
320 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
321 print(model.pet)
322 #> <__main__.Pet object at 0x0123456789ab>
323 print(model.pet.name)
324 #> Hedwig
325 print(type(model.pet))
326 #> <class '__main__.Pet'>
327 try:
328 # If the value is not an instance of the type, it's invalid
329 Model(owner='Harry', pet='Hedwig')
330 except ValidationError as e:
331 print(e)
332 '''
333 1 validation error for Model
334 pet
335 Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
336 '''
338 # Nothing in the instance of the arbitrary type is checked
339 # Here name probably should have been a str, but it's not validated
340 pet2 = Pet(name=42)
341 model2 = Model(owner='Harry', pet=pet2)
342 print(model2)
343 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
344 print(model2.pet)
345 #> <__main__.Pet object at 0x0123456789ab>
346 print(model2.pet.name)
347 #> 42
348 print(type(model2.pet))
349 #> <class '__main__.Pet'>
350 ```
351 """
353 from_attributes: bool
354 """
355 Whether to build models and look up discriminators of tagged unions using python object attributes.
356 """
358 loc_by_alias: bool
359 """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`."""
361 alias_generator: Callable[[str], str] | AliasGenerator | None
362 """
363 A callable that takes a field name and returns an alias for it
364 or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
366 When using a callable, the alias generator is used for both validation and serialization.
367 If you want to use different alias generators for validation and serialization, you can use
368 [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.
370 If data source field names do not match your code style (e. g. CamelCase fields),
371 you can automatically generate aliases using `alias_generator`. Here's an example with
372 a basic callable:
374 ```python
375 from pydantic import BaseModel, ConfigDict
376 from pydantic.alias_generators import to_pascal
378 class Voice(BaseModel):
379 model_config = ConfigDict(alias_generator=to_pascal)
381 name: str
382 language_code: str
384 voice = Voice(Name='Filiz', LanguageCode='tr-TR')
385 print(voice.language_code)
386 #> tr-TR
387 print(voice.model_dump(by_alias=True))
388 #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
389 ```
391 If you want to use different alias generators for validation and serialization, you can use
392 [`AliasGenerator`][pydantic.aliases.AliasGenerator].
394 ```python
395 from pydantic import AliasGenerator, BaseModel, ConfigDict
396 from pydantic.alias_generators import to_camel, to_pascal
398 class Athlete(BaseModel):
399 first_name: str
400 last_name: str
401 sport: str
403 model_config = ConfigDict(
404 alias_generator=AliasGenerator(
405 validation_alias=to_camel,
406 serialization_alias=to_pascal,
407 )
408 )
410 athlete = Athlete(firstName='John', lastName='Doe', sport='track')
411 print(athlete.model_dump(by_alias=True))
412 #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
413 ```
415 Note:
416 Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
417 [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
418 """
420 ignored_types: tuple[type, ...]
421 """A tuple of types that may occur as values of class attributes without annotations. This is
422 typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
423 class without an annotation and has a type that is not in this tuple (or otherwise recognized by
424 _pydantic_), an error will be raised. Defaults to `()`.
425 """
427 allow_inf_nan: bool
428 """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`."""
430 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
431 """A dict or callable to provide extra JSON schema properties. Defaults to `None`."""
433 json_encoders: dict[type[object], JsonEncoder] | None
434 """
435 A `dict` of custom JSON encoders for specific types. Defaults to `None`.
437 !!! warning "Deprecated"
438 This config option is a carryover from v1.
439 We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
440 It is still deprecated and will likely be removed in the future.
441 """
443 # new in V2
444 strict: bool
445 """
446 _(new in V2)_ If `True`, strict validation is applied to all fields on the model.
448 By default, Pydantic attempts to coerce values to the correct type, when possible.
450 There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
451 does not match the field's type annotation.
453 To configure strict mode for all fields on a model, you can set `strict=True` on the model.
455 ```python
456 from pydantic import BaseModel, ConfigDict
458 class Model(BaseModel):
459 model_config = ConfigDict(strict=True)
461 name: str
462 age: int
463 ```
465 See [Strict Mode](../concepts/strict_mode.md) for more details.
467 See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
468 strict and lax modes.
469 """
470 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
471 revalidate_instances: Literal['always', 'never', 'subclass-instances']
472 """
473 When and how to revalidate models and dataclasses during validation. Accepts the string
474 values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`.
476 - `'never'` will not revalidate models and dataclasses during validation
477 - `'always'` will revalidate models and dataclasses during validation
478 - `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a
479 subclass of the model or dataclass
481 By default, model and dataclass instances are not revalidated during validation.
483 ```python
484 from pydantic import BaseModel
486 class User(BaseModel, revalidate_instances='never'): # (1)!
487 hobbies: list[str]
489 class SubUser(User):
490 sins: list[str]
492 class Transaction(BaseModel):
493 user: User
495 my_user = User(hobbies=['reading'])
496 t = Transaction(user=my_user)
497 print(t)
498 #> user=User(hobbies=['reading'])
500 my_user.hobbies = [1] # (2)!
501 t = Transaction(user=my_user) # (3)!
502 print(t)
503 #> user=User(hobbies=[1])
505 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
506 t = Transaction(user=my_sub_user)
507 print(t)
508 #> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
509 ```
511 1. `revalidate_instances` is set to `'never'` by **default.
512 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config.
513 3. Since `revalidate_instances` is set to `never`, this is not revalidated.
515 If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'`
516 in the model's config.
518 ```python
519 from pydantic import BaseModel, ValidationError
521 class User(BaseModel, revalidate_instances='always'): # (1)!
522 hobbies: list[str]
524 class SubUser(User):
525 sins: list[str]
527 class Transaction(BaseModel):
528 user: User
530 my_user = User(hobbies=['reading'])
531 t = Transaction(user=my_user)
532 print(t)
533 #> user=User(hobbies=['reading'])
535 my_user.hobbies = [1]
536 try:
537 t = Transaction(user=my_user) # (2)!
538 except ValidationError as e:
539 print(e)
540 '''
541 1 validation error for Transaction
542 user.hobbies.0
543 Input should be a valid string [type=string_type, input_value=1, input_type=int]
544 '''
546 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
547 t = Transaction(user=my_sub_user)
548 print(t) # (3)!
549 #> user=User(hobbies=['scuba diving'])
550 ```
552 1. `revalidate_instances` is set to `'always'`.
553 2. The model is revalidated, since `revalidate_instances` is set to `'always'`.
554 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
556 It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances
557 of subclasses of the model.
559 ```python
560 from pydantic import BaseModel
562 class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
563 hobbies: list[str]
565 class SubUser(User):
566 sins: list[str]
568 class Transaction(BaseModel):
569 user: User
571 my_user = User(hobbies=['reading'])
572 t = Transaction(user=my_user)
573 print(t)
574 #> user=User(hobbies=['reading'])
576 my_user.hobbies = [1]
577 t = Transaction(user=my_user) # (2)!
578 print(t)
579 #> user=User(hobbies=[1])
581 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
582 t = Transaction(user=my_sub_user)
583 print(t) # (3)!
584 #> user=User(hobbies=['scuba diving'])
585 ```
587 1. `revalidate_instances` is set to `'subclass-instances'`.
588 2. This is not revalidated, since `my_user` is not a subclass of `User`.
589 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
590 """
592 ser_json_timedelta: Literal['iso8601', 'float']
593 """
594 The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
595 `'float'`. Defaults to `'iso8601'`.
597 - `'iso8601'` will serialize timedeltas to ISO 8601 durations.
598 - `'float'` will serialize timedeltas to the total number of seconds.
599 """
601 ser_json_bytes: Literal['utf8', 'base64', 'hex']
602 """
603 The encoding of JSON serialized bytes. Defaults to `'utf8'`.
604 Set equal to `val_json_bytes` to get back an equal value after serialization round trip.
606 - `'utf8'` will serialize bytes to UTF-8 strings.
607 - `'base64'` will serialize bytes to URL safe base64 strings.
608 - `'hex'` will serialize bytes to hexadecimal strings.
609 """
611 val_json_bytes: Literal['utf8', 'base64', 'hex']
612 """
613 The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`.
614 Set equal to `ser_json_bytes` to get back an equal value after serialization round trip.
616 - `'utf8'` will deserialize UTF-8 strings to bytes.
617 - `'base64'` will deserialize URL safe base64 strings to bytes.
618 - `'hex'` will deserialize hexadecimal strings to bytes.
619 """
621 ser_json_inf_nan: Literal['null', 'constants', 'strings']
622 """
623 The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
625 - `'null'` will serialize infinity and NaN values as `null`.
626 - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
627 - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.
628 """
630 # whether to validate default values during validation, default False
631 validate_default: bool
632 """Whether to validate default values during validation. Defaults to `False`."""
634 validate_return: bool
635 """Whether to validate the return value from call validators. Defaults to `False`."""
637 protected_namespaces: tuple[str | Pattern[str], ...]
638 """
639 A `tuple` of strings and/or patterns that prevent models from having fields with names that conflict with them.
640 For strings, we match on a prefix basis. Ex, if 'dog' is in the protected namespace, 'dog_name' will be protected.
641 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.
642 Defaults to `('model_validate', 'model_dump',)`.
644 The reason we've selected these is to prevent collisions with other validation / dumping formats
645 in the future - ex, `model_validate_{some_newly_supported_format}`.
647 Before v2.10, Pydantic used `('model_',)` as the default value for this setting to
648 prevent collisions between model attributes and `BaseModel`'s own methods. This was changed
649 in v2.10 given feedback that this restriction was limiting in AI and data science contexts,
650 where it is common to have fields with names like `model_id`, `model_input`, `model_output`, etc.
652 For more details, see https://github.com/pydantic/pydantic/issues/10315.
654 ```python
655 import warnings
657 from pydantic import BaseModel
659 warnings.filterwarnings('error') # Raise warnings as errors
661 try:
663 class Model(BaseModel):
664 model_dump_something: str
666 except UserWarning as e:
667 print(e)
668 '''
669 Field "model_dump_something" in Model has conflict with protected namespace "model_dump".
671 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('model_validate',)`.
672 '''
673 ```
675 You can customize this behavior using the `protected_namespaces` setting:
677 ```python {test="skip"}
678 import re
679 import warnings
681 from pydantic import BaseModel, ConfigDict
683 with warnings.catch_warnings(record=True) as caught_warnings:
684 warnings.simplefilter('always') # Catch all warnings
686 class Model(BaseModel):
687 safe_field: str
688 also_protect_field: str
689 protect_this: str
691 model_config = ConfigDict(
692 protected_namespaces=(
693 'protect_me_',
694 'also_protect_',
695 re.compile('^protect_this$'),
696 )
697 )
699 for warning in caught_warnings:
700 print(f'{warning.message}')
701 '''
702 Field "also_protect_field" in Model has conflict with protected namespace "also_protect_".
703 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', re.compile('^protect_this$'))`.
705 Field "protect_this" in Model has conflict with protected namespace "re.compile('^protect_this$')".
706 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', 'also_protect_')`.
707 '''
708 ```
710 While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
711 an error _is_ raised if there is an actual collision with an existing attribute:
713 ```python
714 from pydantic import BaseModel, ConfigDict
716 try:
718 class Model(BaseModel):
719 model_validate: str
721 model_config = ConfigDict(protected_namespaces=('model_',))
723 except NameError as e:
724 print(e)
725 '''
726 Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
727 '''
728 ```
729 """
731 hide_input_in_errors: bool
732 """
733 Whether to hide inputs when printing errors. Defaults to `False`.
735 Pydantic shows the input value and type when it raises `ValidationError` during the validation.
737 ```python
738 from pydantic import BaseModel, ValidationError
740 class Model(BaseModel):
741 a: str
743 try:
744 Model(a=123)
745 except ValidationError as e:
746 print(e)
747 '''
748 1 validation error for Model
749 a
750 Input should be a valid string [type=string_type, input_value=123, input_type=int]
751 '''
752 ```
754 You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
756 ```python
757 from pydantic import BaseModel, ConfigDict, ValidationError
759 class Model(BaseModel):
760 a: str
761 model_config = ConfigDict(hide_input_in_errors=True)
763 try:
764 Model(a=123)
765 except ValidationError as e:
766 print(e)
767 '''
768 1 validation error for Model
769 a
770 Input should be a valid string [type=string_type]
771 '''
772 ```
773 """
775 defer_build: bool
776 """
777 Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
779 This can be useful to avoid the overhead of building models which are only
780 used nested within other models, or when you want to manually define type namespace via
781 [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
783 Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances.
784 """
786 plugin_settings: dict[str, object] | None
787 """A `dict` of settings for plugins. Defaults to `None`."""
789 schema_generator: type[_GenerateSchema] | None
790 """
791 !!! warning
792 `schema_generator` is deprecated in v2.10.
794 Prior to v2.10, this setting was advertised as highly subject to change.
795 It's possible that this interface may once again become public once the internal core schema generation
796 API is more stable, but that will likely come after significant performance improvements have been made.
797 """
799 json_schema_serialization_defaults_required: bool
800 """
801 Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
803 This ensures that the serialization schema will reflect the fact a field with a default will always be present
804 when serializing the model, even though it is not required for validation.
806 However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
807 between validation and serialization, and don't mind fields with defaults being marked as not required during
808 serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
810 ```python
811 from pydantic import BaseModel, ConfigDict
813 class Model(BaseModel):
814 a: str = 'a'
816 model_config = ConfigDict(json_schema_serialization_defaults_required=True)
818 print(Model.model_json_schema(mode='validation'))
819 '''
820 {
821 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
822 'title': 'Model',
823 'type': 'object',
824 }
825 '''
826 print(Model.model_json_schema(mode='serialization'))
827 '''
828 {
829 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
830 'required': ['a'],
831 'title': 'Model',
832 'type': 'object',
833 }
834 '''
835 ```
836 """
838 json_schema_mode_override: Literal['validation', 'serialization', None]
839 """
840 If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
841 the function call. Defaults to `None`.
843 This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
844 validation schema.
846 It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
847 and serialization that must both be referenced from the same schema; when this happens, we automatically append
848 `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
849 serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
850 the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
851 from being added to the definition references.
853 ```python
854 from pydantic import BaseModel, ConfigDict, Json
856 class Model(BaseModel):
857 a: Json[int] # requires a string to validate, but will dump an int
859 print(Model.model_json_schema(mode='serialization'))
860 '''
861 {
862 'properties': {'a': {'title': 'A', 'type': 'integer'}},
863 'required': ['a'],
864 'title': 'Model',
865 'type': 'object',
866 }
867 '''
869 class ForceInputModel(Model):
870 # the following ensures that even with mode='serialization', we
871 # will get the schema that would be generated for validation.
872 model_config = ConfigDict(json_schema_mode_override='validation')
874 print(ForceInputModel.model_json_schema(mode='serialization'))
875 '''
876 {
877 'properties': {
878 'a': {
879 'contentMediaType': 'application/json',
880 'contentSchema': {'type': 'integer'},
881 'title': 'A',
882 'type': 'string',
883 }
884 },
885 'required': ['a'],
886 'title': 'ForceInputModel',
887 'type': 'object',
888 }
889 '''
890 ```
891 """
893 coerce_numbers_to_str: bool
894 """
895 If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
897 Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
899 ```python
900 from decimal import Decimal
902 from pydantic import BaseModel, ConfigDict, ValidationError
904 class Model(BaseModel):
905 value: str
907 try:
908 print(Model(value=42))
909 except ValidationError as e:
910 print(e)
911 '''
912 1 validation error for Model
913 value
914 Input should be a valid string [type=string_type, input_value=42, input_type=int]
915 '''
917 class Model(BaseModel):
918 model_config = ConfigDict(coerce_numbers_to_str=True)
920 value: str
922 repr(Model(value=42).value)
923 #> "42"
924 repr(Model(value=42.13).value)
925 #> "42.13"
926 repr(Model(value=Decimal('42.13')).value)
927 #> "42.13"
928 ```
929 """
931 regex_engine: Literal['rust-regex', 'python-re']
932 """
933 The regex engine to be used for pattern validation.
934 Defaults to `'rust-regex'`.
936 - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
937 which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
938 - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
939 which supports all regex features, but may be slower.
941 !!! note
942 If you use a compiled regex pattern, the python-re engine will be used regardless of this setting.
943 This is so that flags such as `re.IGNORECASE` are respected.
945 ```python
946 from pydantic import BaseModel, ConfigDict, Field, ValidationError
948 class Model(BaseModel):
949 model_config = ConfigDict(regex_engine='python-re')
951 value: str = Field(pattern=r'^abc(?=def)')
953 print(Model(value='abcdef').value)
954 #> abcdef
956 try:
957 print(Model(value='abxyzcdef'))
958 except ValidationError as e:
959 print(e)
960 '''
961 1 validation error for Model
962 value
963 String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
964 '''
965 ```
966 """
968 validation_error_cause: bool
969 """
970 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`.
972 Note:
973 Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
975 Note:
976 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.
977 """
979 use_attribute_docstrings: bool
980 '''
981 Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
982 should be used for field descriptions. Defaults to `False`.
984 Available in Pydantic v2.7+.
986 ```python
987 from pydantic import BaseModel, ConfigDict, Field
990 class Model(BaseModel):
991 model_config = ConfigDict(use_attribute_docstrings=True)
993 x: str
994 """
995 Example of an attribute docstring
996 """
998 y: int = Field(description="Description in Field")
999 """
1000 Description in Field overrides attribute docstring
1001 """
1004 print(Model.model_fields["x"].description)
1005 # > Example of an attribute docstring
1006 print(Model.model_fields["y"].description)
1007 # > Description in Field
1008 ```
1009 This requires the source code of the class to be available at runtime.
1011 !!! warning "Usage with `TypedDict` and stdlib dataclasses"
1012 Due to current limitations, attribute docstrings detection may not work as expected when using
1013 [`TypedDict`][typing.TypedDict] and stdlib dataclasses, in particular when:
1015 - inheritance is being used.
1016 - multiple classes have the same name in the same source file.
1017 '''
1019 cache_strings: bool | Literal['all', 'keys', 'none']
1020 """
1021 Whether to cache strings to avoid constructing new Python objects. Defaults to True.
1023 Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
1025 - `True` or `'all'` (the default): cache all strings
1026 - `'keys'`: cache only dictionary keys
1027 - `False` or `'none'`: no caching
1029 !!! note
1030 `True` or `'all'` is required to cache strings during general validation because
1031 validators don't know if they're in a key or a value.
1033 !!! tip
1034 If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
1035 as the performance difference is minimal if repeated strings are rare.
1036 """
1038 validate_by_alias: bool
1039 """
1040 Whether an aliased field may be populated by its alias. Defaults to `True`.
1042 !!! note
1043 In v2.11, `validate_by_alias` was introduced in conjunction with [`validate_by_name`][pydantic.ConfigDict.validate_by_name]
1044 to empower users with more fine grained validation control. In <v2.11, disabling validation by alias was not possible.
1046 Here's an example of disabling validation by alias:
1048 ```py
1049 from pydantic import BaseModel, ConfigDict, Field
1051 class Model(BaseModel):
1052 model_config = ConfigDict(validate_by_name=True, validate_by_alias=False)
1054 my_field: str = Field(validation_alias='my_alias') # (1)!
1056 m = Model(my_field='foo') # (2)!
1057 print(m)
1058 #> my_field='foo'
1059 ```
1061 1. The field `'my_field'` has an alias `'my_alias'`.
1062 2. The model can only be populated by the attribute name `'my_field'`.
1064 !!! warning
1065 You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
1066 This would make it impossible to populate an attribute.
1068 See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
1070 If you set `validate_by_alias` to `False`, under the hood, Pydantic dynamically sets
1071 `validate_by_name` to `True` to ensure that validation can still occur.
1072 """
1074 validate_by_name: bool
1075 """
1076 Whether an aliased field may be populated by its name as given by the model
1077 attribute. Defaults to `False`.
1079 !!! note
1080 In v2.0-v2.10, the `populate_by_name` configuration setting was used to specify
1081 whether or not a field could be populated by its name **and** alias.
1083 In v2.11, `validate_by_name` was introduced in conjunction with [`validate_by_alias`][pydantic.ConfigDict.validate_by_alias]
1084 to empower users with more fine grained validation behavior control.
1086 ```python
1087 from pydantic import BaseModel, ConfigDict, Field
1089 class Model(BaseModel):
1090 model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
1092 my_field: str = Field(validation_alias='my_alias') # (1)!
1094 m = Model(my_alias='foo') # (2)!
1095 print(m)
1096 #> my_field='foo'
1098 m = Model(my_field='foo') # (3)!
1099 print(m)
1100 #> my_field='foo'
1101 ```
1103 1. The field `'my_field'` has an alias `'my_alias'`.
1104 2. The model is populated by the alias `'my_alias'`.
1105 3. The model is populated by the attribute name `'my_field'`.
1107 !!! warning
1108 You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
1109 This would make it impossible to populate an attribute.
1111 See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
1112 """
1114 serialize_by_alias: bool
1115 """
1116 Whether an aliased field should be serialized by its alias. Defaults to `False`.
1118 Note: In v2.11, `serialize_by_alias` was introduced to address the
1119 [popular request](https://github.com/pydantic/pydantic/issues/8379)
1120 for consistency with alias behavior for validation and serialization settings.
1121 In v3, the default value is expected to change to `True` for consistency with the validation default.
1123 ```python
1124 from pydantic import BaseModel, ConfigDict, Field
1126 class Model(BaseModel):
1127 model_config = ConfigDict(serialize_by_alias=True)
1129 my_field: str = Field(serialization_alias='my_alias') # (1)!
1131 m = Model(my_field='foo')
1132 print(m.model_dump()) # (2)!
1133 #> {'my_alias': 'foo'}
1134 ```
1136 1. The field `'my_field'` has an alias `'my_alias'`.
1137 2. The model is serialized using the alias `'my_alias'` for the `'my_field'` attribute.
1138 """
1141_TypeT = TypeVar('_TypeT', bound=type)
1144@overload
1145@deprecated('Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead.')
1146def with_config(*, config: ConfigDict) -> Callable[[_TypeT], _TypeT]: ...
1149@overload
1150def with_config(config: ConfigDict, /) -> Callable[[_TypeT], _TypeT]: ...
1153@overload
1154def with_config(**config: Unpack[ConfigDict]) -> Callable[[_TypeT], _TypeT]: ...
1157def with_config(config: ConfigDict | None = None, /, **kwargs: Any) -> Callable[[_TypeT], _TypeT]:
1158 """!!! abstract "Usage Documentation"
1159 [Configuration with other types](../concepts/config.md#configuration-on-other-supported-types)
1161 A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
1163 Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
1164 especially with `TypedDict`.
1166 !!! example "Usage"
1168 ```python
1169 from typing_extensions import TypedDict
1171 from pydantic import ConfigDict, TypeAdapter, with_config
1173 @with_config(ConfigDict(str_to_lower=True))
1174 class TD(TypedDict):
1175 x: str
1177 ta = TypeAdapter(TD)
1179 print(ta.validate_python({'x': 'ABC'}))
1180 #> {'x': 'abc'}
1181 ```
1182 """
1183 if config is not None and kwargs:
1184 raise ValueError('Cannot specify both `config` and keyword arguments')
1186 if len(kwargs) == 1 and (kwargs_conf := kwargs.get('config')) is not None:
1187 warnings.warn(
1188 'Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead',
1189 category=PydanticDeprecatedSince211,
1190 stacklevel=2,
1191 )
1192 final_config = cast(ConfigDict, kwargs_conf)
1193 else:
1194 final_config = config if config is not None else cast(ConfigDict, kwargs)
1196 def inner(class_: _TypeT, /) -> _TypeT:
1197 # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
1198 # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
1199 # common mistakes, we at least check for `class_` to not be a Pydantic model.
1200 from ._internal._utils import is_model_class
1202 if is_model_class(class_):
1203 raise PydanticUserError(
1204 f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
1205 code='with-config-on-model',
1206 )
1207 class_.__pydantic_config__ = final_config
1208 return class_
1210 return inner
1213__getattr__ = getattr_migration(__name__)