Coverage for pydantic/config.py: 100.00%
101 statements
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-21 17:00 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-21 17:00 +0000
1"""Configuration for Pydantic models."""
3from __future__ import annotations as _annotations 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
5from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, TypeVar, Union 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
7from typing_extensions import Literal, TypeAlias, TypedDict 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
9from ._migration import getattr_migration 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
10from .aliases import AliasGenerator 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
11from .errors import PydanticUserError 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
13if TYPE_CHECKING: 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
14 from ._internal._generate_schema import GenerateSchema as _GenerateSchema
16__all__ = ('ConfigDict', 'with_config') 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
19JsonValue: TypeAlias = Union[int, float, str, bool, None, List['JsonValue'], 'JsonDict'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
20JsonDict: TypeAlias = Dict[str, JsonValue] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
22JsonEncoder = Callable[[Any], Any] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
24JsonSchemaExtraCallable: TypeAlias = Union[ 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
25 Callable[[JsonDict], None],
26 Callable[[JsonDict, Type[Any]], None],
27]
29ExtraValues = Literal['allow', 'ignore', 'forbid'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
32class ConfigDict(TypedDict, total=False): 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
33 """A TypedDict for configuring Pydantic behaviour."""
35 title: str | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
36 """The title for the generated JSON schema, defaults to the model's name""" 1abcdefghijklmtuvwxyznopqrs
38 str_to_lower: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
39 """Whether to convert all characters to lowercase for str types. Defaults to `False`.""" 1abcdefghijklmtuvwxyznopqrs
41 str_to_upper: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
42 """Whether to convert all characters to uppercase for str types. Defaults to `False`.""" 1abcdefghijklmtuvwxyznopqrs
43 str_strip_whitespace: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
44 """Whether to strip leading and trailing whitespace for str types.""" 1abcdefghijklmtuvwxyznopqrs
46 str_min_length: int 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
47 """The minimum length for str types. Defaults to `None`.""" 1abcdefghijklmtuvwxyznopqrs
49 str_max_length: int | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
50 """The maximum length for str types. Defaults to `None`.""" 1abcdefghijklmtuvwxyznopqrs
52 extra: ExtraValues | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
53 """ 1abcdefghijklmtuvwxyznopqrs
54 Whether to ignore, allow, or forbid extra attributes during model initialization. Defaults to `'ignore'`.
56 You can configure how pydantic handles the attributes that are not defined in the model:
58 * `allow` - Allow any extra attributes.
59 * `forbid` - Forbid any extra attributes.
60 * `ignore` - Ignore any extra attributes.
62 ```py
63 from pydantic import BaseModel, ConfigDict
66 class User(BaseModel):
67 model_config = ConfigDict(extra='ignore') # (1)!
69 name: str
72 user = User(name='John Doe', age=20) # (2)!
73 print(user)
74 #> name='John Doe'
75 ```
77 1. This is the default behaviour.
78 2. The `age` argument is ignored.
80 Instead, with `extra='allow'`, the `age` argument is included:
82 ```py
83 from pydantic import BaseModel, ConfigDict
86 class User(BaseModel):
87 model_config = ConfigDict(extra='allow')
89 name: str
92 user = User(name='John Doe', age=20) # (1)!
93 print(user)
94 #> name='John Doe' age=20
95 ```
97 1. The `age` argument is included.
99 With `extra='forbid'`, an error is raised:
101 ```py
102 from pydantic import BaseModel, ConfigDict, ValidationError
105 class User(BaseModel):
106 model_config = ConfigDict(extra='forbid')
108 name: str
111 try:
112 User(name='John Doe', age=20)
113 except ValidationError as e:
114 print(e)
115 '''
116 1 validation error for User
117 age
118 Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int]
119 '''
120 ```
121 """
123 frozen: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
124 """ 1abcdefghijklmtuvwxyznopqrs
125 Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
126 a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
127 attributes are hashable. Defaults to `False`.
129 Note:
130 On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
131 """
133 populate_by_name: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
134 """ 1abcdefghijklmtuvwxyznopqrs
135 Whether an aliased field may be populated by its name as given by the model
136 attribute, as well as the alias. Defaults to `False`.
138 Note:
139 The name of this configuration setting was changed in **v2.0** from
140 `allow_population_by_field_name` to `populate_by_name`.
142 ```py
143 from pydantic import BaseModel, ConfigDict, Field
146 class User(BaseModel):
147 model_config = ConfigDict(populate_by_name=True)
149 name: str = Field(alias='full_name') # (1)!
150 age: int
153 user = User(full_name='John Doe', age=20) # (2)!
154 print(user)
155 #> name='John Doe' age=20
156 user = User(name='John Doe', age=20) # (3)!
157 print(user)
158 #> name='John Doe' age=20
159 ```
161 1. The field `'name'` has an alias `'full_name'`.
162 2. The model is populated by the alias `'full_name'`.
163 3. The model is populated by the field name `'name'`.
164 """
166 use_enum_values: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
167 """ 1abcdefghijklmtuvwxyznopqrs
168 Whether to populate models with the `value` property of enums, rather than the raw enum.
169 This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
171 !!! note
172 If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
173 for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
174 enum's value occurs during validation, not serialization.
176 ```py
177 from enum import Enum
178 from typing import Optional
180 from pydantic import BaseModel, ConfigDict, Field
183 class SomeEnum(Enum):
184 FOO = 'foo'
185 BAR = 'bar'
186 BAZ = 'baz'
189 class SomeModel(BaseModel):
190 model_config = ConfigDict(use_enum_values=True)
192 some_enum: SomeEnum
193 another_enum: Optional[SomeEnum] = Field(default=SomeEnum.FOO, validate_default=True)
196 model1 = SomeModel(some_enum=SomeEnum.BAR)
197 print(model1.model_dump())
198 # {'some_enum': 'bar', 'another_enum': 'foo'}
200 model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
201 print(model2.model_dump())
202 #> {'some_enum': 'bar', 'another_enum': 'baz'}
203 ```
204 """
206 validate_assignment: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
207 """ 1abcdefghijklmtuvwxyznopqrs
208 Whether to validate the data when the model is changed. Defaults to `False`.
210 The default behavior of Pydantic is to validate the data when the model is created.
212 In case the user changes the data after the model is created, the model is _not_ revalidated.
214 ```py
215 from pydantic import BaseModel
217 class User(BaseModel):
218 name: str
220 user = User(name='John Doe') # (1)!
221 print(user)
222 #> name='John Doe'
223 user.name = 123 # (1)!
224 print(user)
225 #> name=123
226 ```
228 1. The validation happens only when the model is created.
229 2. The validation does not happen when the data is changed.
231 In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
233 ```py
234 from pydantic import BaseModel, ValidationError
236 class User(BaseModel, validate_assignment=True): # (1)!
237 name: str
239 user = User(name='John Doe') # (2)!
240 print(user)
241 #> name='John Doe'
242 try:
243 user.name = 123 # (3)!
244 except ValidationError as e:
245 print(e)
246 '''
247 1 validation error for User
248 name
249 Input should be a valid string [type=string_type, input_value=123, input_type=int]
250 '''
251 ```
253 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
254 2. The validation happens when the model is created.
255 3. The validation _also_ happens when the data is changed.
256 """
258 arbitrary_types_allowed: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
259 """ 1abcdefghijklmtuvwxyznopqrs
260 Whether arbitrary types are allowed for field types. Defaults to `False`.
262 ```py
263 from pydantic import BaseModel, ConfigDict, ValidationError
265 # This is not a pydantic model, it's an arbitrary class
266 class Pet:
267 def __init__(self, name: str):
268 self.name = name
270 class Model(BaseModel):
271 model_config = ConfigDict(arbitrary_types_allowed=True)
273 pet: Pet
274 owner: str
276 pet = Pet(name='Hedwig')
277 # A simple check of instance type is used to validate the data
278 model = Model(owner='Harry', pet=pet)
279 print(model)
280 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
281 print(model.pet)
282 #> <__main__.Pet object at 0x0123456789ab>
283 print(model.pet.name)
284 #> Hedwig
285 print(type(model.pet))
286 #> <class '__main__.Pet'>
287 try:
288 # If the value is not an instance of the type, it's invalid
289 Model(owner='Harry', pet='Hedwig')
290 except ValidationError as e:
291 print(e)
292 '''
293 1 validation error for Model
294 pet
295 Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
296 '''
298 # Nothing in the instance of the arbitrary type is checked
299 # Here name probably should have been a str, but it's not validated
300 pet2 = Pet(name=42)
301 model2 = Model(owner='Harry', pet=pet2)
302 print(model2)
303 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
304 print(model2.pet)
305 #> <__main__.Pet object at 0x0123456789ab>
306 print(model2.pet.name)
307 #> 42
308 print(type(model2.pet))
309 #> <class '__main__.Pet'>
310 ```
311 """
313 from_attributes: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
314 """ 1abcdefghijklmtuvwxyznopqrs
315 Whether to build models and look up discriminators of tagged unions using python object attributes.
316 """
318 loc_by_alias: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
319 """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`.""" 1abcdefghijklmtuvwxyznopqrs
321 alias_generator: Callable[[str], str] | AliasGenerator | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
322 """ 1abcdefghijklmtuvwxyznopqrs
323 A callable that takes a field name and returns an alias for it
324 or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
326 When using a callable, the alias generator is used for both validation and serialization.
327 If you want to use different alias generators for validation and serialization, you can use
328 [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.
330 If data source field names do not match your code style (e. g. CamelCase fields),
331 you can automatically generate aliases using `alias_generator`. Here's an example with
332 a basic callable:
334 ```py
335 from pydantic import BaseModel, ConfigDict
336 from pydantic.alias_generators import to_pascal
338 class Voice(BaseModel):
339 model_config = ConfigDict(alias_generator=to_pascal)
341 name: str
342 language_code: str
344 voice = Voice(Name='Filiz', LanguageCode='tr-TR')
345 print(voice.language_code)
346 #> tr-TR
347 print(voice.model_dump(by_alias=True))
348 #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
349 ```
351 If you want to use different alias generators for validation and serialization, you can use
352 [`AliasGenerator`][pydantic.aliases.AliasGenerator].
354 ```py
355 from pydantic import AliasGenerator, BaseModel, ConfigDict
356 from pydantic.alias_generators import to_camel, to_pascal
358 class Athlete(BaseModel):
359 first_name: str
360 last_name: str
361 sport: str
363 model_config = ConfigDict(
364 alias_generator=AliasGenerator(
365 validation_alias=to_camel,
366 serialization_alias=to_pascal,
367 )
368 )
370 athlete = Athlete(firstName='John', lastName='Doe', sport='track')
371 print(athlete.model_dump(by_alias=True))
372 #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
373 ```
375 Note:
376 Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
377 [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
378 """
380 ignored_types: tuple[type, ...] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
381 """A tuple of types that may occur as values of class attributes without annotations. This is 1abcdefghijklmtuvwxyznopqrs
382 typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
383 class without an annotation and has a type that is not in this tuple (or otherwise recognized by
384 _pydantic_), an error will be raised. Defaults to `()`.
385 """
387 allow_inf_nan: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
388 """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float fields. Defaults to `True`.""" 1abcdefghijklmtuvwxyznopqrs
390 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
391 """A dict or callable to provide extra JSON schema properties. Defaults to `None`.""" 1abcdefghijklmtuvwxyznopqrs
393 json_encoders: dict[type[object], JsonEncoder] | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
394 """ 1abcdefghijklmtuvwxyznopqrs
395 A `dict` of custom JSON encoders for specific types. Defaults to `None`.
397 !!! warning "Deprecated"
398 This config option is a carryover from v1.
399 We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
400 It is still deprecated and will likely be removed in the future.
401 """
403 # new in V2
404 strict: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
405 """ 1abcdefghijklmtuvwxyznopqrs
406 _(new in V2)_ If `True`, strict validation is applied to all fields on the model.
408 By default, Pydantic attempts to coerce values to the correct type, when possible.
410 There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
411 does not match the field's type annotation.
413 To configure strict mode for all fields on a model, you can set `strict=True` on the model.
415 ```py
416 from pydantic import BaseModel, ConfigDict
418 class Model(BaseModel):
419 model_config = ConfigDict(strict=True)
421 name: str
422 age: int
423 ```
425 See [Strict Mode](../concepts/strict_mode.md) for more details.
427 See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
428 strict and lax modes.
429 """
430 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
431 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
432 """ 1abcdefghijklmtuvwxyznopqrs
433 When and how to revalidate models and dataclasses during validation. Accepts the string
434 values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`.
436 - `'never'` will not revalidate models and dataclasses during validation
437 - `'always'` will revalidate models and dataclasses during validation
438 - `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a
439 subclass of the model or dataclass
441 By default, model and dataclass instances are not revalidated during validation.
443 ```py
444 from typing import List
446 from pydantic import BaseModel
448 class User(BaseModel, revalidate_instances='never'): # (1)!
449 hobbies: List[str]
451 class SubUser(User):
452 sins: List[str]
454 class Transaction(BaseModel):
455 user: User
457 my_user = User(hobbies=['reading'])
458 t = Transaction(user=my_user)
459 print(t)
460 #> user=User(hobbies=['reading'])
462 my_user.hobbies = [1] # (2)!
463 t = Transaction(user=my_user) # (3)!
464 print(t)
465 #> user=User(hobbies=[1])
467 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
468 t = Transaction(user=my_sub_user)
469 print(t)
470 #> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
471 ```
473 1. `revalidate_instances` is set to `'never'` by **default.
474 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config.
475 3. Since `revalidate_instances` is set to `never`, this is not revalidated.
477 If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'`
478 in the model's config.
480 ```py
481 from typing import List
483 from pydantic import BaseModel, ValidationError
485 class User(BaseModel, revalidate_instances='always'): # (1)!
486 hobbies: List[str]
488 class SubUser(User):
489 sins: List[str]
491 class Transaction(BaseModel):
492 user: User
494 my_user = User(hobbies=['reading'])
495 t = Transaction(user=my_user)
496 print(t)
497 #> user=User(hobbies=['reading'])
499 my_user.hobbies = [1]
500 try:
501 t = Transaction(user=my_user) # (2)!
502 except ValidationError as e:
503 print(e)
504 '''
505 1 validation error for Transaction
506 user.hobbies.0
507 Input should be a valid string [type=string_type, input_value=1, input_type=int]
508 '''
510 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
511 t = Transaction(user=my_sub_user)
512 print(t) # (3)!
513 #> user=User(hobbies=['scuba diving'])
514 ```
516 1. `revalidate_instances` is set to `'always'`.
517 2. The model is revalidated, since `revalidate_instances` is set to `'always'`.
518 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
520 It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances
521 of subclasses of the model.
523 ```py
524 from typing import List
526 from pydantic import BaseModel
528 class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
529 hobbies: List[str]
531 class SubUser(User):
532 sins: List[str]
534 class Transaction(BaseModel):
535 user: User
537 my_user = User(hobbies=['reading'])
538 t = Transaction(user=my_user)
539 print(t)
540 #> user=User(hobbies=['reading'])
542 my_user.hobbies = [1]
543 t = Transaction(user=my_user) # (2)!
544 print(t)
545 #> user=User(hobbies=[1])
547 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
548 t = Transaction(user=my_sub_user)
549 print(t) # (3)!
550 #> user=User(hobbies=['scuba diving'])
551 ```
553 1. `revalidate_instances` is set to `'subclass-instances'`.
554 2. This is not revalidated, since `my_user` is not a subclass of `User`.
555 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
556 """
558 ser_json_timedelta: Literal['iso8601', 'float'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
559 """ 1abcdefghijklmtuvwxyznopqrs
560 The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
561 `'float'`. Defaults to `'iso8601'`.
563 - `'iso8601'` will serialize timedeltas to ISO 8601 durations.
564 - `'float'` will serialize timedeltas to the total number of seconds.
565 """
567 ser_json_bytes: Literal['utf8', 'base64'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
568 """ 1abcdefghijklmtuvwxyznopqrs
569 The encoding of JSON serialized bytes. Accepts the string values of `'utf8'` and `'base64'`.
570 Defaults to `'utf8'`.
572 - `'utf8'` will serialize bytes to UTF-8 strings.
573 - `'base64'` will serialize bytes to URL safe base64 strings.
574 """
576 ser_json_inf_nan: Literal['null', 'constants'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
577 """ 1abcdefghijklmtuvwxyznopqrs
578 The encoding of JSON serialized infinity and NaN float values. Accepts the string values of `'null'` and `'constants'`.
579 Defaults to `'null'`.
581 - `'null'` will serialize infinity and NaN values as `null`.
582 - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
583 """
585 # whether to validate default values during validation, default False
586 validate_default: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
587 """Whether to validate default values during validation. Defaults to `False`.""" 1abcdefghijklmtuvwxyznopqrs
589 validate_return: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
590 """whether to validate the return value from call validators. Defaults to `False`.""" 1abcdefghijklmtuvwxyznopqrs
592 protected_namespaces: tuple[str, ...] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
593 """ 1abcdefghijklmtuvwxyznopqrs
594 A `tuple` of strings that prevent model to have field which conflict with them.
595 Defaults to `('model_', )`).
597 Pydantic prevents collisions between model attributes and `BaseModel`'s own methods by
598 namespacing them with the prefix `model_`.
600 ```py
601 import warnings
603 from pydantic import BaseModel
605 warnings.filterwarnings('error') # Raise warnings as errors
607 try:
609 class Model(BaseModel):
610 model_prefixed_field: str
612 except UserWarning as e:
613 print(e)
614 '''
615 Field "model_prefixed_field" has conflict with protected namespace "model_".
617 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`.
618 '''
619 ```
621 You can customize this behavior using the `protected_namespaces` setting:
623 ```py
624 import warnings
626 from pydantic import BaseModel, ConfigDict
628 warnings.filterwarnings('error') # Raise warnings as errors
630 try:
632 class Model(BaseModel):
633 model_prefixed_field: str
634 also_protect_field: str
636 model_config = ConfigDict(
637 protected_namespaces=('protect_me_', 'also_protect_')
638 )
640 except UserWarning as e:
641 print(e)
642 '''
643 Field "also_protect_field" has conflict with protected namespace "also_protect_".
645 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_',)`.
646 '''
647 ```
649 While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
650 an error _is_ raised if there is an actual collision with an existing attribute:
652 ```py
653 from pydantic import BaseModel
655 try:
657 class Model(BaseModel):
658 model_validate: str
660 except NameError as e:
661 print(e)
662 '''
663 Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
664 '''
665 ```
666 """
668 hide_input_in_errors: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
669 """ 1abcdefghijklmtuvwxyznopqrs
670 Whether to hide inputs when printing errors. Defaults to `False`.
672 Pydantic shows the input value and type when it raises `ValidationError` during the validation.
674 ```py
675 from pydantic import BaseModel, ValidationError
677 class Model(BaseModel):
678 a: str
680 try:
681 Model(a=123)
682 except ValidationError as e:
683 print(e)
684 '''
685 1 validation error for Model
686 a
687 Input should be a valid string [type=string_type, input_value=123, input_type=int]
688 '''
689 ```
691 You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
693 ```py
694 from pydantic import BaseModel, ConfigDict, ValidationError
696 class Model(BaseModel):
697 a: str
698 model_config = ConfigDict(hide_input_in_errors=True)
700 try:
701 Model(a=123)
702 except ValidationError as e:
703 print(e)
704 '''
705 1 validation error for Model
706 a
707 Input should be a valid string [type=string_type]
708 '''
709 ```
710 """
712 defer_build: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
713 """ 1abcdefghijklmtuvwxyznopqrs
714 Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
716 This can be useful to avoid the overhead of building models which are only
717 used nested within other models, or when you want to manually define type namespace via
718 [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
720 See also [`experimental_defer_build_mode`][pydantic.config.ConfigDict.experimental_defer_build_mode].
722 !!! note
723 `defer_build` does not work by default with FastAPI Pydantic models. By default, the validator and serializer
724 for said models is constructed immediately for FastAPI routes. You also need to define
725 [`experimental_defer_build_mode=('model', 'type_adapter')`][pydantic.config.ConfigDict.experimental_defer_build_mode] with FastAPI
726 models in order for `defer_build=True` to take effect. This additional (experimental) parameter is required for
727 the deferred building due to FastAPI relying on `TypeAdapter`s.
728 """
730 experimental_defer_build_mode: tuple[Literal['model', 'type_adapter'], ...] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
731 """ 1abcdefghijklmtuvwxyznopqrs
732 Controls when [`defer_build`][pydantic.config.ConfigDict.defer_build] is applicable. Defaults to `('model',)`.
734 Due to backwards compatibility reasons [`TypeAdapter`][pydantic.type_adapter.TypeAdapter] does not by default
735 respect `defer_build`. Meaning when `defer_build` is `True` and `experimental_defer_build_mode` is the default `('model',)`
736 then `TypeAdapter` immediately constructs its validator and serializer instead of postponing said construction until
737 the first model validation. Set this to `('model', 'type_adapter')` to make `TypeAdapter` respect the `defer_build`
738 so it postpones validator and serializer construction until the first validation or serialization.
740 !!! note
741 The `experimental_defer_build_mode` parameter is named with an underscore to suggest this is an experimental feature. It may
742 be removed or changed in the future in a minor release.
743 """
745 plugin_settings: dict[str, object] | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
746 """A `dict` of settings for plugins. Defaults to `None`. 1abcdefghijklmtuvwxyznopqrs
748 See [Pydantic Plugins](../concepts/plugins.md) for details.
749 """
751 schema_generator: type[_GenerateSchema] | None 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
752 """ 1abcdefghijklmtuvwxyznopqrs
753 A custom core schema generator class to use when generating JSON schemas.
754 Useful if you want to change the way types are validated across an entire model/schema. Defaults to `None`.
756 The `GenerateSchema` interface is subject to change, currently only the `string_schema` method is public.
758 See [#6737](https://github.com/pydantic/pydantic/pull/6737) for details.
759 """
761 json_schema_serialization_defaults_required: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
762 """ 1abcdefghijklmtuvwxyznopqrs
763 Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
765 This ensures that the serialization schema will reflect the fact a field with a default will always be present
766 when serializing the model, even though it is not required for validation.
768 However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
769 between validation and serialization, and don't mind fields with defaults being marked as not required during
770 serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
772 ```py
773 from pydantic import BaseModel, ConfigDict
775 class Model(BaseModel):
776 a: str = 'a'
778 model_config = ConfigDict(json_schema_serialization_defaults_required=True)
780 print(Model.model_json_schema(mode='validation'))
781 '''
782 {
783 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
784 'title': 'Model',
785 'type': 'object',
786 }
787 '''
788 print(Model.model_json_schema(mode='serialization'))
789 '''
790 {
791 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
792 'required': ['a'],
793 'title': 'Model',
794 'type': 'object',
795 }
796 '''
797 ```
798 """
800 json_schema_mode_override: Literal['validation', 'serialization', None] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
801 """ 1abcdefghijklmtuvwxyznopqrs
802 If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
803 the function call. Defaults to `None`.
805 This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
806 validation schema.
808 It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
809 and serialization that must both be referenced from the same schema; when this happens, we automatically append
810 `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
811 serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
812 the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
813 from being added to the definition references.
815 ```py
816 from pydantic import BaseModel, ConfigDict, Json
818 class Model(BaseModel):
819 a: Json[int] # requires a string to validate, but will dump an int
821 print(Model.model_json_schema(mode='serialization'))
822 '''
823 {
824 'properties': {'a': {'title': 'A', 'type': 'integer'}},
825 'required': ['a'],
826 'title': 'Model',
827 'type': 'object',
828 }
829 '''
831 class ForceInputModel(Model):
832 # the following ensures that even with mode='serialization', we
833 # will get the schema that would be generated for validation.
834 model_config = ConfigDict(json_schema_mode_override='validation')
836 print(ForceInputModel.model_json_schema(mode='serialization'))
837 '''
838 {
839 'properties': {
840 'a': {
841 'contentMediaType': 'application/json',
842 'contentSchema': {'type': 'integer'},
843 'title': 'A',
844 'type': 'string',
845 }
846 },
847 'required': ['a'],
848 'title': 'ForceInputModel',
849 'type': 'object',
850 }
851 '''
852 ```
853 """
855 coerce_numbers_to_str: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
856 """ 1abcdefghijklmtuvwxyznopqrs
857 If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
859 Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
861 ```py
862 from decimal import Decimal
864 from pydantic import BaseModel, ConfigDict, ValidationError
866 class Model(BaseModel):
867 value: str
869 try:
870 print(Model(value=42))
871 except ValidationError as e:
872 print(e)
873 '''
874 1 validation error for Model
875 value
876 Input should be a valid string [type=string_type, input_value=42, input_type=int]
877 '''
879 class Model(BaseModel):
880 model_config = ConfigDict(coerce_numbers_to_str=True)
882 value: str
884 repr(Model(value=42).value)
885 #> "42"
886 repr(Model(value=42.13).value)
887 #> "42.13"
888 repr(Model(value=Decimal('42.13')).value)
889 #> "42.13"
890 ```
891 """
893 regex_engine: Literal['rust-regex', 'python-re'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
894 """ 1abcdefghijklmtuvwxyznopqrs
895 The regex engine to be used for pattern validation.
896 Defaults to `'rust-regex'`.
898 - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
899 which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
900 - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
901 which supports all regex features, but may be slower.
903 !!! note
904 If you use a compiled regex pattern, the python-re engine will be used regardless of this setting.
905 This is so that flags such as `re.IGNORECASE` are respected.
907 ```py
908 from pydantic import BaseModel, ConfigDict, Field, ValidationError
910 class Model(BaseModel):
911 model_config = ConfigDict(regex_engine='python-re')
913 value: str = Field(pattern=r'^abc(?=def)')
915 print(Model(value='abcdef').value)
916 #> abcdef
918 try:
919 print(Model(value='abxyzcdef'))
920 except ValidationError as e:
921 print(e)
922 '''
923 1 validation error for Model
924 value
925 String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
926 '''
927 ```
928 """
930 validation_error_cause: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
931 """ 1abcdefghijklmtuvwxyznopqrs
932 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`.
934 Note:
935 Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
937 Note:
938 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.
939 """
941 use_attribute_docstrings: bool 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
942 ''' 1abcdefghijklmtuvwxyznopqrs
943 Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
944 should be used for field descriptions. Defaults to `False`.
946 Available in Pydantic v2.7+.
948 ```py
949 from pydantic import BaseModel, ConfigDict, Field
952 class Model(BaseModel):
953 model_config = ConfigDict(use_attribute_docstrings=True)
955 x: str
956 """
957 Example of an attribute docstring
958 """
960 y: int = Field(description="Description in Field")
961 """
962 Description in Field overrides attribute docstring
963 """
966 print(Model.model_fields["x"].description)
967 # > Example of an attribute docstring
968 print(Model.model_fields["y"].description)
969 # > Description in Field
970 ```
971 This requires the source code of the class to be available at runtime.
973 !!! warning "Usage with `TypedDict`"
974 Due to current limitations, attribute docstrings detection may not work as expected when using `TypedDict`
975 (in particular when multiple `TypedDict` classes have the same name in the same source file). The behavior
976 can be different depending on the Python version used.
977 '''
979 cache_strings: bool | Literal['all', 'keys', 'none'] 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
980 """ 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
981 Whether to cache strings to avoid constructing new Python objects. Defaults to True.
983 Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
985 - `True` or `'all'` (the default): cache all strings
986 - `'keys'`: cache only dictionary keys
987 - `False` or `'none'`: no caching
989 !!! note
990 `True` or `'all'` is required to cache strings during general validation because
991 validators don't know if they're in a key or a value.
993 !!! tip
994 If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
995 as the performance difference is minimal if repeated strings are rare.
996 """
999_TypeT = TypeVar('_TypeT', bound=type) 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
1002def with_config(config: ConfigDict) -> Callable[[_TypeT], _TypeT]: 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs
1003 """Usage docs: https://docs.pydantic.dev/2.8/concepts/config/#configuration-with-dataclass-from-the-standard-library-or-typeddict
1005 A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
1007 Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
1008 especially with `TypedDict`.
1010 !!! example "Usage"
1012 ```py
1013 from typing_extensions import TypedDict
1015 from pydantic import ConfigDict, TypeAdapter, with_config
1017 @with_config(ConfigDict(str_to_lower=True))
1018 class Model(TypedDict):
1019 x: str
1021 ta = TypeAdapter(Model)
1023 print(ta.validate_python({'x': 'ABC'}))
1024 #> {'x': 'abc'}
1025 ```
1026 """
1028 def inner(class_: _TypeT, /) -> _TypeT: 1ABCDabcdefEgFGHIhijklmJKLMnopqrs
1029 # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
1030 # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
1031 # common mistakes, we at least check for `class_` to not be a Pydantic model.
1032 from ._internal._utils import is_model_class 1ABCDabcdefEgFGHIhijklmJKLMnopqrs
1034 if is_model_class(class_): 1ABCDabcdefEgFGHIhijklmJKLMnopqrs
1035 raise PydanticUserError( 1ABCDabcdefEgFGHIhijklmJKLMnopqrs
1036 f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
1037 code='with-config-on-model',
1038 )
1039 class_.__pydantic_config__ = config 1ABCDabcdefEgFGHIhijklmJKLMnopqrs
1040 return class_ 1ABCDabcdefEgFGHIhijklmJKLMnopqrs
1042 return inner 1ABCDabcdefEgFGHIhijklmJKLMnopqrs
1045__getattr__ = getattr_migration(__name__) 1ABCDabcdefEgFGHIhijklmNOtuvwxyzJKLMnopqrs