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 collections.abc import Callable
7from re import Pattern
8from typing import TYPE_CHECKING, Any, Literal, TypeAlias, TypeVar, Union, cast, overload
10from typing_extensions import TypedDict, Unpack, deprecated
12from ._migration import getattr_migration
13from .aliases import AliasGenerator
14from .errors import PydanticUserError
15from .warnings import PydanticDeprecatedSince211
17if TYPE_CHECKING:
18 from ._internal._generate_schema import GenerateSchema as _GenerateSchema
19 from .fields import ComputedFieldInfo, FieldInfo
21__all__ = ('ConfigDict', 'with_config')
24JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict']
25JsonDict: TypeAlias = dict[str, JsonValue]
27JsonEncoder = Callable[[Any], Any]
29JsonSchemaExtraCallable: TypeAlias = Callable[[JsonDict], None] | Callable[[JsonDict, type[Any]], None]
31ExtraValues = Literal['allow', 'ignore', 'forbid']
34class ConfigDict(TypedDict, total=False):
35 """A TypedDict for configuring Pydantic behaviour."""
37 title: str | None
38 """The title for the generated JSON schema, defaults to the model's name"""
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`."""
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`."""
46 str_to_lower: bool
47 """Whether to convert all characters to lowercase for str types. Defaults to `False`."""
49 str_to_upper: bool
50 """Whether to convert all characters to uppercase for str types. Defaults to `False`."""
52 str_strip_whitespace: bool
53 """Whether to strip leading and trailing whitespace for str types."""
55 str_min_length: int
56 """The minimum length for str types. Defaults to `0`."""
58 str_max_length: int | None
59 """The maximum length for str types. Defaults to `None`."""
61 extra: ExtraValues | None
62 '''
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.
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 pydantic import BaseModel, ConfigDict, ValidationError
160 class Model(BaseModel):
161 x: int
162 model_config = ConfigDict(extra="allow")
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 '''
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`.
183 Note:
184 On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
185 """
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`.
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`][pydantic.config.ConfigDict.validate_by_name] configuration setting.
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`.
199 In v2.11, we also introduced a [`validate_by_alias`][pydantic.config.ConfigDict.validate_by_alias] setting that introduces more fine grained
200 control for validation behavior.
202 Here's how you might go about using the new settings to achieve the same behavior:
204 ```python
205 from pydantic import BaseModel, ConfigDict, Field
207 class Model(BaseModel):
208 model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
210 my_field: str = Field(alias='my_alias') # (1)!
212 m = Model(my_alias='foo') # (2)!
213 print(m)
214 #> my_field='foo'
216 m = Model(my_field='foo') # (3)!
217 print(m)
218 #> my_field='foo'
219 ```
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 """
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`.
231 !!! note
232 If you have a field typed as an enum with a default value, the [`validate_default`][pydantic.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.
236 ```python
237 from enum import Enum
239 from pydantic import BaseModel, ConfigDict, Field
241 class SomeEnum(Enum):
242 FOO = 'foo'
243 BAR = 'bar'
244 BAZ = 'baz'
246 class SomeModel(BaseModel):
247 model_config = ConfigDict(use_enum_values=True)
249 some_enum: SomeEnum
250 another_enum: SomeEnum | None = Field(
251 default=SomeEnum.FOO, validate_default=True
252 )
254 model1 = SomeModel(some_enum=SomeEnum.BAR)
255 print(model1.model_dump())
256 #> {'some_enum': 'bar', 'another_enum': 'foo'}
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 """
264 validate_assignment: bool
265 """
266 Whether to validate the data when the model is changed. Defaults to `False`.
268 The default behavior of Pydantic is to validate the data when the model is created.
270 In case the user changes the data after the model is created, the model is _not_ revalidated.
272 ```python
273 from pydantic import BaseModel
275 class User(BaseModel):
276 name: str
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 ```
286 1. The validation happens only when the model is created.
287 2. The validation does not happen when the data is changed.
289 In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
291 ```python
292 from pydantic import BaseModel, ValidationError
294 class User(BaseModel, validate_assignment=True): # (1)!
295 name: str
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 ```
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 """
316 arbitrary_types_allowed: bool
317 """
318 Whether arbitrary types are allowed for field types. Defaults to `False`.
320 ```python
321 from pydantic import BaseModel, ConfigDict, ValidationError
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
328 class Model(BaseModel):
329 model_config = ConfigDict(arbitrary_types_allowed=True)
331 pet: Pet
332 owner: str
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 '''
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 """
371 from_attributes: bool
372 """
373 Whether to build models and look up discriminators of tagged unions using python object attributes.
374 """
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`."""
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`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
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`][pydantic.aliases.AliasGenerator] instead.
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:
392 ```python
393 from pydantic import BaseModel, ConfigDict
394 from pydantic.alias_generators import to_pascal
396 class Voice(BaseModel):
397 model_config = ConfigDict(alias_generator=to_pascal)
399 name: str
400 language_code: str
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 ```
409 If you want to use different alias generators for validation and serialization, you can use
410 [`AliasGenerator`][pydantic.aliases.AliasGenerator].
412 ```python
413 from pydantic import AliasGenerator, BaseModel, ConfigDict
414 from pydantic.alias_generators import to_camel, to_pascal
416 class Athlete(BaseModel):
417 first_name: str
418 last_name: str
419 sport: str
421 model_config = ConfigDict(
422 alias_generator=AliasGenerator(
423 validation_alias=to_camel,
424 serialization_alias=to_pascal,
425 )
426 )
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 ```
433 Note:
434 Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
435 [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
436 """
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 """
445 allow_inf_nan: bool
446 """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`."""
448 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
449 """A dict or callable to provide extra JSON schema properties. Defaults to `None`."""
451 json_encoders: dict[type[object], JsonEncoder] | None
452 """
453 A `dict` of custom JSON encoders for specific types. Defaults to `None`.
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 """
461 # new in V2
462 strict: bool
463 """
464 Whether strict validation is applied to all fields on the model.
466 By default, Pydantic attempts to coerce values to the correct type, when possible.
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.
471 To configure strict mode for all fields on a model, you can set `strict=True` on the model.
473 ```python
474 from pydantic import BaseModel, ConfigDict
476 class Model(BaseModel):
477 model_config = ConfigDict(strict=True)
479 name: str
480 age: int
481 ```
483 See [Strict Mode](../concepts/strict_mode.md) for more details.
485 See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
486 strict and lax modes.
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:
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
501 The default is `'never'` (no revalidation).
503 This configuration only affects *the current model* it is applied on, and does *not* propagate to the models
504 referenced in fields.
506 ```python
507 from pydantic import BaseModel
509 class User(BaseModel, revalidate_instances='never'): # (1)!
510 name: str
512 class Transaction(BaseModel):
513 user: User
515 my_user = User(name='John')
516 t = Transaction(user=my_user)
518 my_user.name = 1 # (2)!
519 t = Transaction(user=my_user) # (3)!
520 print(t)
521 #> user=User(name=1)
522 ```
524 1. This is the default behavior.
525 2. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.ConfigDict.validate_assignment] in the configuration.
526 3. Since `revalidate_instances` is set to `'never'`, the user instance is not revalidated.
528 Here is an example demonstrating the behavior of `'subclass-instances'`:
530 ```python
531 from pydantic import BaseModel
533 class User(BaseModel, revalidate_instances='subclass-instances'):
534 name: str
536 class SubUser(User):
537 age: int
539 class Transaction(BaseModel):
540 user: User
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)
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 ```
554 1. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.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.
560 /// version-added | v2
561 ///
562 """
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'`.
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.
572 /// version-changed | v2.12
573 It is now recommended to use the [`ser_json_temporal`][pydantic.config.ConfigDict.ser_json_temporal]
574 setting. `ser_json_timedelta` will be deprecated in v3.
575 ///
576 """
578 ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']
579 """
580 The format of JSON serialized temporal types from the [`datetime`][] module. This includes:
582 - [`datetime.datetime`][]
583 - [`datetime.date`][]
584 - [`datetime.time`][]
585 - [`datetime.timedelta`][]
587 Can be one of:
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.
593 Defaults to `'iso8601'`.
595 /// version-added | v2.12
596 This setting replaces [`ser_json_timedelta`][pydantic.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 """
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:
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:
610 * seconds since the [epoch] if $-2^{10} <= v <= 2^{10}$
611 * milliseconds since the [epoch] (if $v < -2^{10}$ or $v > 2^{10}$).
613 Defaults to `'infer'`.
615 /// version-added | v2.12
616 ///
618 [epoch]: https://en.wikipedia.org/wiki/Unix_time
619 """
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.
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 """
631 val_json_bytes: Literal['utf8', 'base64', 'hex']
632 """
633 /// version-added | v2.9
634 ///
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.
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 """
644 ser_json_inf_nan: Literal['null', 'constants', 'strings']
645 """
646 The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
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 """
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`."""
657 validate_return: bool
658 """Whether to validate the return value from call validators. Defaults to `False`."""
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.
664 Strings are matched on a prefix basis. For instance, with `'dog'`, having a field named `'dog_name'` will be disallowed.
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.
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.
672 ```python
673 import warnings
675 from pydantic import BaseModel
677 warnings.filterwarnings('error') # Raise warnings as errors
679 try:
681 class Model(BaseModel):
682 model_dump_something: str
684 except UserWarning as e:
685 print(e)
686 '''
687 Field 'model_dump_something' in 'Model' conflicts with protected namespace 'model_dump'.
689 You may be able to solve this by setting the 'protected_namespaces' configuration to ('model_validate',).
690 '''
691 ```
693 You can customize this behavior using the `protected_namespaces` setting:
695 ```python {test="skip"}
696 import re
697 import warnings
699 from pydantic import BaseModel, ConfigDict
701 with warnings.catch_warnings(record=True) as caught_warnings:
702 warnings.simplefilter('always') # Catch all warnings
704 class Model(BaseModel):
705 safe_field: str
706 also_protect_field: str
707 protect_this: str
709 model_config = ConfigDict(
710 protected_namespaces=(
711 'protect_me_',
712 'also_protect_',
713 re.compile('^protect_this$'),
714 )
715 )
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$'))`.
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 ```
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:
731 ```python
732 from pydantic import BaseModel, ConfigDict
734 try:
736 class Model(BaseModel):
737 model_validate: str
739 model_config = ConfigDict(protected_namespaces=('model_',))
741 except ValueError as e:
742 print(e)
743 '''
744 Field 'model_validate' conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace 'model_'.
745 '''
746 ```
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 """
754 hide_input_in_errors: bool
755 """
756 Whether to hide inputs when printing errors. Defaults to `False`.
758 Pydantic shows the input value and type when it raises `ValidationError` during the validation.
760 ```python
761 from pydantic import BaseModel, ValidationError
763 class Model(BaseModel):
764 a: str
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 ```
777 You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
779 ```python
780 from pydantic import BaseModel, ConfigDict, ValidationError
782 class Model(BaseModel):
783 a: str
784 model_config = ConfigDict(hide_input_in_errors=True)
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 """
798 defer_build: bool
799 """
800 Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
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=...)`][pydantic.BaseModel.model_rebuild].
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 """
811 plugin_settings: dict[str, object] | None
812 """A `dict` of settings for plugins. Defaults to `None`."""
814 schema_generator: type[_GenerateSchema] | None
815 """
816 The `GenerateSchema` class to use during core schema generation.
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 """
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`.
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.
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.
835 ```python
836 from pydantic import BaseModel, ConfigDict
838 class Model(BaseModel):
839 a: str = 'a'
841 model_config = ConfigDict(json_schema_serialization_defaults_required=True)
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 ```
862 /// version-added | v2.4
863 ///
864 """
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`.
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.
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.
881 ```python
882 from pydantic import BaseModel, ConfigDict, Json
884 class Model(BaseModel):
885 a: Json[int] # requires a string to validate, but will dump an int
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 '''
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')
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 ```
920 /// version-added | v2.4
921 ///
922 """
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`.
928 Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
930 ```python
931 from decimal import Decimal
933 from pydantic import BaseModel, ConfigDict, ValidationError
935 class Model(BaseModel):
936 value: str
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 '''
948 class Model(BaseModel):
949 model_config = ConfigDict(coerce_numbers_to_str=True)
951 value: str
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 """
962 regex_engine: Literal['rust-regex', 'python-re']
963 """
964 The regex engine to be used for pattern validation.
965 Defaults to `'rust-regex'`.
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.
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.
975 ```python
976 from pydantic import BaseModel, ConfigDict, Field, ValidationError
978 class Model(BaseModel):
979 model_config = ConfigDict(regex_engine='python-re')
981 value: str = Field(pattern=r'^abc(?=def)')
983 print(Model(value='abcdef').value)
984 #> abcdef
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 ```
997 /// version-added | v2.5
998 ///
999 """
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`.
1005 Note:
1006 Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
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.
1011 /// version-added | v2.5
1012 ///
1013 """
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`.
1020 ```python
1021 from pydantic import BaseModel, ConfigDict, Field
1024 class Model(BaseModel):
1025 model_config = ConfigDict(use_attribute_docstrings=True)
1027 x: str
1028 """
1029 Example of an attribute docstring
1030 """
1032 y: int = Field(description="Description in Field")
1033 """
1034 Description in Field overrides attribute docstring
1035 """
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).
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:
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).
1052 /// version-added | v2.7
1053 ///
1054 '''
1056 cache_strings: bool | Literal['all', 'keys', 'none']
1057 """
1058 Whether to cache strings to avoid constructing new Python objects. Defaults to True.
1060 Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
1062 - `True` or `'all'` (the default): cache all strings
1063 - `'keys'`: cache only dictionary keys
1064 - `False` or `'none'`: no caching
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.
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.
1074 /// version-added | v2.7
1075 ///
1076 """
1078 validate_by_alias: bool
1079 """
1080 Whether an aliased field may be populated by its alias. Defaults to `True`.
1082 Here's an example of disabling validation by alias:
1084 ```py
1085 from pydantic import BaseModel, ConfigDict, Field
1087 class Model(BaseModel):
1088 model_config = ConfigDict(validate_by_name=True, validate_by_alias=False)
1090 my_field: str = Field(validation_alias='my_alias') # (1)!
1092 m = Model(my_field='foo') # (2)!
1093 print(m)
1094 #> my_field='foo'
1095 ```
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'`.
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.
1104 See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
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.
1109 /// version-added | v2.11
1110 This setting was introduced in conjunction with [`validate_by_name`][pydantic.ConfigDict.validate_by_name]
1111 to empower users with more fine grained validation control.
1112 ///
1113 """
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`.
1120 ```python
1121 from pydantic import BaseModel, ConfigDict, Field
1123 class Model(BaseModel):
1124 model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
1126 my_field: str = Field(validation_alias='my_alias') # (1)!
1128 m = Model(my_alias='foo') # (2)!
1129 print(m)
1130 #> my_field='foo'
1132 m = Model(my_field='foo') # (3)!
1133 print(m)
1134 #> my_field='foo'
1135 ```
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'`.
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.
1145 See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
1147 /// version-added | v2.11
1148 This setting was introduced in conjunction with [`validate_by_alias`][pydantic.ConfigDict.validate_by_alias]
1149 to empower users with more fine grained validation control. It is an alternative to [`populate_by_name`][pydantic.ConfigDict.populate_by_name],
1150 that enables validation by name **and** by alias.
1151 ///
1152 """
1154 serialize_by_alias: bool
1155 """
1156 Whether an aliased field should be serialized by its alias. Defaults to `False`.
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.
1163 ```python
1164 from pydantic import BaseModel, ConfigDict, Field
1166 class Model(BaseModel):
1167 model_config = ConfigDict(serialize_by_alias=True)
1169 my_field: str = Field(serialization_alias='my_alias') # (1)!
1171 m = Model(my_field='foo')
1172 print(m.model_dump()) # (2)!
1173 #> {'my_alias': 'foo'}
1174 ```
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.
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.
1184 In v3, the default value is expected to change to `True` for consistency with the validation default.
1185 ///
1186 """
1188 url_preserve_empty_path: bool
1189 """
1190 Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`.
1192 ```python
1193 from pydantic import AnyUrl, BaseModel, ConfigDict
1195 class Model(BaseModel):
1196 model_config = ConfigDict(url_preserve_empty_path=True)
1198 url: AnyUrl
1200 m = Model(url='https://example.com')
1201 print(m.url)
1202 #> https://example.com
1203 ```
1205 /// version-added | v2.12
1206 ///
1207 """
1209 polymorphic_serialization: bool
1210 """
1211 Whether to use polymorphic serialization for subclasses of the model or Pydantic dataclass. Defaults to `False`.
1212 """
1215_TypeT = TypeVar('_TypeT', bound=type)
1218@overload
1219@deprecated('Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead.')
1220def with_config(*, config: ConfigDict) -> Callable[[_TypeT], _TypeT]: ...
1223@overload
1224def with_config(config: ConfigDict, /) -> Callable[[_TypeT], _TypeT]: ...
1227@overload
1228def with_config(**config: Unpack[ConfigDict]) -> Callable[[_TypeT], _TypeT]: ...
1231def 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)
1235 A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
1237 Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
1238 especially with `TypedDict`.
1240 !!! example "Usage"
1242 ```python
1243 from typing_extensions import TypedDict
1245 from pydantic import ConfigDict, TypeAdapter, with_config
1247 @with_config(ConfigDict(str_to_lower=True))
1248 class TD(TypedDict):
1249 x: str
1251 ta = TypeAdapter(TD)
1253 print(ta.validate_python({'x': 'ABC'}))
1254 #> {'x': 'abc'}
1255 ```
1257 /// deprecated-removed | v2.11 v3
1258 Passing `config` as a keyword argument.
1259 ///
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')
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)
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
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_
1292 return inner
1295__getattr__ = getattr_migration(__name__)