Coverage for pydantic/config.py: 100.00%
105 statements
« prev ^ index » next coverage.py v7.5.4, created at 2024-07-03 19:29 +0000
« prev ^ index » next coverage.py v7.5.4, created at 2024-07-03 19:29 +0000
1"""Configuration for Pydantic models."""
3from __future__ import annotations as _annotations 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
5from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, TypeVar, Union 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
7from typing_extensions import Literal, TypeAlias, TypedDict 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
9from ._migration import getattr_migration 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
10from .aliases import AliasGenerator 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
11from .errors import PydanticUserError 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
13if TYPE_CHECKING: 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
14 from ._internal._generate_schema import GenerateSchema as _GenerateSchema
15 from .fields import ComputedFieldInfo, FieldInfo
17__all__ = ('ConfigDict', 'with_config') 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
20JsonValue: TypeAlias = Union[int, float, str, bool, None, List['JsonValue'], 'JsonDict'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
21JsonDict: TypeAlias = Dict[str, JsonValue] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
23JsonEncoder = Callable[[Any], Any] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
25JsonSchemaExtraCallable: TypeAlias = Union[ 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
26 Callable[[JsonDict], None],
27 Callable[[JsonDict, Type[Any]], None],
28]
30ExtraValues = Literal['allow', 'ignore', 'forbid'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
33class ConfigDict(TypedDict, total=False): 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
34 """A TypedDict for configuring Pydantic behaviour."""
36 title: str | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
37 """The title for the generated JSON schema, defaults to the model's name""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
39 model_title_generator: Callable[[type], str] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
40 """A callable that takes a model class and returns the title for it. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
42 field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
43 """A callable that takes a field's name and info and returns title for it. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
45 str_to_lower: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
46 """Whether to convert all characters to lowercase for str types. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
48 str_to_upper: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
49 """Whether to convert all characters to uppercase for str types. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
51 str_strip_whitespace: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
52 """Whether to strip leading and trailing whitespace for str types.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
54 str_min_length: int 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
55 """The minimum length for str types. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
57 str_max_length: int | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
58 """The maximum length for str types. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
60 extra: ExtraValues | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
61 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
62 Whether to ignore, allow, or forbid extra attributes during model initialization. Defaults to `'ignore'`.
64 You can configure how pydantic handles the attributes that are not defined in the model:
66 * `allow` - Allow any extra attributes.
67 * `forbid` - Forbid any extra attributes.
68 * `ignore` - Ignore any extra attributes.
70 ```py
71 from pydantic import BaseModel, ConfigDict
74 class User(BaseModel):
75 model_config = ConfigDict(extra='ignore') # (1)!
77 name: str
80 user = User(name='John Doe', age=20) # (2)!
81 print(user)
82 #> name='John Doe'
83 ```
85 1. This is the default behaviour.
86 2. The `age` argument is ignored.
88 Instead, with `extra='allow'`, the `age` argument is included:
90 ```py
91 from pydantic import BaseModel, ConfigDict
94 class User(BaseModel):
95 model_config = ConfigDict(extra='allow')
97 name: str
100 user = User(name='John Doe', age=20) # (1)!
101 print(user)
102 #> name='John Doe' age=20
103 ```
105 1. The `age` argument is included.
107 With `extra='forbid'`, an error is raised:
109 ```py
110 from pydantic import BaseModel, ConfigDict, ValidationError
113 class User(BaseModel):
114 model_config = ConfigDict(extra='forbid')
116 name: str
119 try:
120 User(name='John Doe', age=20)
121 except ValidationError as e:
122 print(e)
123 '''
124 1 validation error for User
125 age
126 Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int]
127 '''
128 ```
129 """
131 frozen: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
132 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
133 Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
134 a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
135 attributes are hashable. Defaults to `False`.
137 Note:
138 On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
139 """
141 populate_by_name: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
142 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
143 Whether an aliased field may be populated by its name as given by the model
144 attribute, as well as the alias. Defaults to `False`.
146 Note:
147 The name of this configuration setting was changed in **v2.0** from
148 `allow_population_by_field_name` to `populate_by_name`.
150 ```py
151 from pydantic import BaseModel, ConfigDict, Field
154 class User(BaseModel):
155 model_config = ConfigDict(populate_by_name=True)
157 name: str = Field(alias='full_name') # (1)!
158 age: int
161 user = User(full_name='John Doe', age=20) # (2)!
162 print(user)
163 #> name='John Doe' age=20
164 user = User(name='John Doe', age=20) # (3)!
165 print(user)
166 #> name='John Doe' age=20
167 ```
169 1. The field `'name'` has an alias `'full_name'`.
170 2. The model is populated by the alias `'full_name'`.
171 3. The model is populated by the field name `'name'`.
172 """
174 use_enum_values: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
175 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
176 Whether to populate models with the `value` property of enums, rather than the raw enum.
177 This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
179 !!! note
180 If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
181 for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
182 enum's value occurs during validation, not serialization.
184 ```py
185 from enum import Enum
186 from typing import Optional
188 from pydantic import BaseModel, ConfigDict, Field
191 class SomeEnum(Enum):
192 FOO = 'foo'
193 BAR = 'bar'
194 BAZ = 'baz'
197 class SomeModel(BaseModel):
198 model_config = ConfigDict(use_enum_values=True)
200 some_enum: SomeEnum
201 another_enum: Optional[SomeEnum] = Field(default=SomeEnum.FOO, validate_default=True)
204 model1 = SomeModel(some_enum=SomeEnum.BAR)
205 print(model1.model_dump())
206 # {'some_enum': 'bar', 'another_enum': 'foo'}
208 model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
209 print(model2.model_dump())
210 #> {'some_enum': 'bar', 'another_enum': 'baz'}
211 ```
212 """
214 validate_assignment: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
215 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
216 Whether to validate the data when the model is changed. Defaults to `False`.
218 The default behavior of Pydantic is to validate the data when the model is created.
220 In case the user changes the data after the model is created, the model is _not_ revalidated.
222 ```py
223 from pydantic import BaseModel
225 class User(BaseModel):
226 name: str
228 user = User(name='John Doe') # (1)!
229 print(user)
230 #> name='John Doe'
231 user.name = 123 # (1)!
232 print(user)
233 #> name=123
234 ```
236 1. The validation happens only when the model is created.
237 2. The validation does not happen when the data is changed.
239 In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
241 ```py
242 from pydantic import BaseModel, ValidationError
244 class User(BaseModel, validate_assignment=True): # (1)!
245 name: str
247 user = User(name='John Doe') # (2)!
248 print(user)
249 #> name='John Doe'
250 try:
251 user.name = 123 # (3)!
252 except ValidationError as e:
253 print(e)
254 '''
255 1 validation error for User
256 name
257 Input should be a valid string [type=string_type, input_value=123, input_type=int]
258 '''
259 ```
261 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
262 2. The validation happens when the model is created.
263 3. The validation _also_ happens when the data is changed.
264 """
266 arbitrary_types_allowed: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
267 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
268 Whether arbitrary types are allowed for field types. Defaults to `False`.
270 ```py
271 from pydantic import BaseModel, ConfigDict, ValidationError
273 # This is not a pydantic model, it's an arbitrary class
274 class Pet:
275 def __init__(self, name: str):
276 self.name = name
278 class Model(BaseModel):
279 model_config = ConfigDict(arbitrary_types_allowed=True)
281 pet: Pet
282 owner: str
284 pet = Pet(name='Hedwig')
285 # A simple check of instance type is used to validate the data
286 model = Model(owner='Harry', pet=pet)
287 print(model)
288 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
289 print(model.pet)
290 #> <__main__.Pet object at 0x0123456789ab>
291 print(model.pet.name)
292 #> Hedwig
293 print(type(model.pet))
294 #> <class '__main__.Pet'>
295 try:
296 # If the value is not an instance of the type, it's invalid
297 Model(owner='Harry', pet='Hedwig')
298 except ValidationError as e:
299 print(e)
300 '''
301 1 validation error for Model
302 pet
303 Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
304 '''
306 # Nothing in the instance of the arbitrary type is checked
307 # Here name probably should have been a str, but it's not validated
308 pet2 = Pet(name=42)
309 model2 = Model(owner='Harry', pet=pet2)
310 print(model2)
311 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
312 print(model2.pet)
313 #> <__main__.Pet object at 0x0123456789ab>
314 print(model2.pet.name)
315 #> 42
316 print(type(model2.pet))
317 #> <class '__main__.Pet'>
318 ```
319 """
321 from_attributes: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
322 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
323 Whether to build models and look up discriminators of tagged unions using python object attributes.
324 """
326 loc_by_alias: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
327 """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`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
329 alias_generator: Callable[[str], str] | AliasGenerator | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
330 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
331 A callable that takes a field name and returns an alias for it
332 or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
334 When using a callable, the alias generator is used for both validation and serialization.
335 If you want to use different alias generators for validation and serialization, you can use
336 [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.
338 If data source field names do not match your code style (e. g. CamelCase fields),
339 you can automatically generate aliases using `alias_generator`. Here's an example with
340 a basic callable:
342 ```py
343 from pydantic import BaseModel, ConfigDict
344 from pydantic.alias_generators import to_pascal
346 class Voice(BaseModel):
347 model_config = ConfigDict(alias_generator=to_pascal)
349 name: str
350 language_code: str
352 voice = Voice(Name='Filiz', LanguageCode='tr-TR')
353 print(voice.language_code)
354 #> tr-TR
355 print(voice.model_dump(by_alias=True))
356 #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
357 ```
359 If you want to use different alias generators for validation and serialization, you can use
360 [`AliasGenerator`][pydantic.aliases.AliasGenerator].
362 ```py
363 from pydantic import AliasGenerator, BaseModel, ConfigDict
364 from pydantic.alias_generators import to_camel, to_pascal
366 class Athlete(BaseModel):
367 first_name: str
368 last_name: str
369 sport: str
371 model_config = ConfigDict(
372 alias_generator=AliasGenerator(
373 validation_alias=to_camel,
374 serialization_alias=to_pascal,
375 )
376 )
378 athlete = Athlete(firstName='John', lastName='Doe', sport='track')
379 print(athlete.model_dump(by_alias=True))
380 #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
381 ```
383 Note:
384 Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
385 [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
386 """
388 ignored_types: tuple[type, ...] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
389 """A tuple of types that may occur as values of class attributes without annotations. This is 1abcdefghijklmnopqzABCDEFGrstuvwxy
390 typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
391 class without an annotation and has a type that is not in this tuple (or otherwise recognized by
392 _pydantic_), an error will be raised. Defaults to `()`.
393 """
395 allow_inf_nan: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
396 """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float fields. Defaults to `True`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
398 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
399 """A dict or callable to provide extra JSON schema properties. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
401 json_encoders: dict[type[object], JsonEncoder] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
402 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
403 A `dict` of custom JSON encoders for specific types. Defaults to `None`.
405 !!! warning "Deprecated"
406 This config option is a carryover from v1.
407 We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
408 It is still deprecated and will likely be removed in the future.
409 """
411 # new in V2
412 strict: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
413 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
414 _(new in V2)_ If `True`, strict validation is applied to all fields on the model.
416 By default, Pydantic attempts to coerce values to the correct type, when possible.
418 There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
419 does not match the field's type annotation.
421 To configure strict mode for all fields on a model, you can set `strict=True` on the model.
423 ```py
424 from pydantic import BaseModel, ConfigDict
426 class Model(BaseModel):
427 model_config = ConfigDict(strict=True)
429 name: str
430 age: int
431 ```
433 See [Strict Mode](../concepts/strict_mode.md) for more details.
435 See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
436 strict and lax modes.
437 """
438 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
439 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
440 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
441 When and how to revalidate models and dataclasses during validation. Accepts the string
442 values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`.
444 - `'never'` will not revalidate models and dataclasses during validation
445 - `'always'` will revalidate models and dataclasses during validation
446 - `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a
447 subclass of the model or dataclass
449 By default, model and dataclass instances are not revalidated during validation.
451 ```py
452 from typing import List
454 from pydantic import BaseModel
456 class User(BaseModel, revalidate_instances='never'): # (1)!
457 hobbies: List[str]
459 class SubUser(User):
460 sins: List[str]
462 class Transaction(BaseModel):
463 user: User
465 my_user = User(hobbies=['reading'])
466 t = Transaction(user=my_user)
467 print(t)
468 #> user=User(hobbies=['reading'])
470 my_user.hobbies = [1] # (2)!
471 t = Transaction(user=my_user) # (3)!
472 print(t)
473 #> user=User(hobbies=[1])
475 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
476 t = Transaction(user=my_sub_user)
477 print(t)
478 #> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
479 ```
481 1. `revalidate_instances` is set to `'never'` by **default.
482 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config.
483 3. Since `revalidate_instances` is set to `never`, this is not revalidated.
485 If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'`
486 in the model's config.
488 ```py
489 from typing import List
491 from pydantic import BaseModel, ValidationError
493 class User(BaseModel, revalidate_instances='always'): # (1)!
494 hobbies: List[str]
496 class SubUser(User):
497 sins: List[str]
499 class Transaction(BaseModel):
500 user: User
502 my_user = User(hobbies=['reading'])
503 t = Transaction(user=my_user)
504 print(t)
505 #> user=User(hobbies=['reading'])
507 my_user.hobbies = [1]
508 try:
509 t = Transaction(user=my_user) # (2)!
510 except ValidationError as e:
511 print(e)
512 '''
513 1 validation error for Transaction
514 user.hobbies.0
515 Input should be a valid string [type=string_type, input_value=1, input_type=int]
516 '''
518 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
519 t = Transaction(user=my_sub_user)
520 print(t) # (3)!
521 #> user=User(hobbies=['scuba diving'])
522 ```
524 1. `revalidate_instances` is set to `'always'`.
525 2. The model is revalidated, since `revalidate_instances` is set to `'always'`.
526 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
528 It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances
529 of subclasses of the model.
531 ```py
532 from typing import List
534 from pydantic import BaseModel
536 class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
537 hobbies: List[str]
539 class SubUser(User):
540 sins: List[str]
542 class Transaction(BaseModel):
543 user: User
545 my_user = User(hobbies=['reading'])
546 t = Transaction(user=my_user)
547 print(t)
548 #> user=User(hobbies=['reading'])
550 my_user.hobbies = [1]
551 t = Transaction(user=my_user) # (2)!
552 print(t)
553 #> user=User(hobbies=[1])
555 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
556 t = Transaction(user=my_sub_user)
557 print(t) # (3)!
558 #> user=User(hobbies=['scuba diving'])
559 ```
561 1. `revalidate_instances` is set to `'subclass-instances'`.
562 2. This is not revalidated, since `my_user` is not a subclass of `User`.
563 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
564 """
566 ser_json_timedelta: Literal['iso8601', 'float'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
567 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
568 The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
569 `'float'`. Defaults to `'iso8601'`.
571 - `'iso8601'` will serialize timedeltas to ISO 8601 durations.
572 - `'float'` will serialize timedeltas to the total number of seconds.
573 """
575 ser_json_bytes: Literal['utf8', 'base64'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
576 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
577 The encoding of JSON serialized bytes. Accepts the string values of `'utf8'` and `'base64'`.
578 Defaults to `'utf8'`.
580 - `'utf8'` will serialize bytes to UTF-8 strings.
581 - `'base64'` will serialize bytes to URL safe base64 strings.
582 """
584 ser_json_inf_nan: Literal['null', 'constants', 'strings'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
585 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
586 The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
588 - `'null'` will serialize infinity and NaN values as `null`.
589 - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
590 - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.
591 """
593 # whether to validate default values during validation, default False
594 validate_default: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
595 """Whether to validate default values during validation. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
597 validate_return: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
598 """whether to validate the return value from call validators. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy
600 protected_namespaces: tuple[str, ...] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
601 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
602 A `tuple` of strings that prevent model to have field which conflict with them.
603 Defaults to `('model_', )`).
605 Pydantic prevents collisions between model attributes and `BaseModel`'s own methods by
606 namespacing them with the prefix `model_`.
608 ```py
609 import warnings
611 from pydantic import BaseModel
613 warnings.filterwarnings('error') # Raise warnings as errors
615 try:
617 class Model(BaseModel):
618 model_prefixed_field: str
620 except UserWarning as e:
621 print(e)
622 '''
623 Field "model_prefixed_field" has conflict with protected namespace "model_".
625 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`.
626 '''
627 ```
629 You can customize this behavior using the `protected_namespaces` setting:
631 ```py
632 import warnings
634 from pydantic import BaseModel, ConfigDict
636 warnings.filterwarnings('error') # Raise warnings as errors
638 try:
640 class Model(BaseModel):
641 model_prefixed_field: str
642 also_protect_field: str
644 model_config = ConfigDict(
645 protected_namespaces=('protect_me_', 'also_protect_')
646 )
648 except UserWarning as e:
649 print(e)
650 '''
651 Field "also_protect_field" has conflict with protected namespace "also_protect_".
653 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_',)`.
654 '''
655 ```
657 While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
658 an error _is_ raised if there is an actual collision with an existing attribute:
660 ```py
661 from pydantic import BaseModel
663 try:
665 class Model(BaseModel):
666 model_validate: str
668 except NameError as e:
669 print(e)
670 '''
671 Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
672 '''
673 ```
674 """
676 hide_input_in_errors: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
677 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
678 Whether to hide inputs when printing errors. Defaults to `False`.
680 Pydantic shows the input value and type when it raises `ValidationError` during the validation.
682 ```py
683 from pydantic import BaseModel, ValidationError
685 class Model(BaseModel):
686 a: str
688 try:
689 Model(a=123)
690 except ValidationError as e:
691 print(e)
692 '''
693 1 validation error for Model
694 a
695 Input should be a valid string [type=string_type, input_value=123, input_type=int]
696 '''
697 ```
699 You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
701 ```py
702 from pydantic import BaseModel, ConfigDict, ValidationError
704 class Model(BaseModel):
705 a: str
706 model_config = ConfigDict(hide_input_in_errors=True)
708 try:
709 Model(a=123)
710 except ValidationError as e:
711 print(e)
712 '''
713 1 validation error for Model
714 a
715 Input should be a valid string [type=string_type]
716 '''
717 ```
718 """
720 defer_build: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
721 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
722 Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
724 This can be useful to avoid the overhead of building models which are only
725 used nested within other models, or when you want to manually define type namespace via
726 [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
728 See also [`experimental_defer_build_mode`][pydantic.config.ConfigDict.experimental_defer_build_mode].
730 !!! note
731 `defer_build` does not work by default with FastAPI Pydantic models. By default, the validator and serializer
732 for said models is constructed immediately for FastAPI routes. You also need to define
733 [`experimental_defer_build_mode=('model', 'type_adapter')`][pydantic.config.ConfigDict.experimental_defer_build_mode] with FastAPI
734 models in order for `defer_build=True` to take effect. This additional (experimental) parameter is required for
735 the deferred building due to FastAPI relying on `TypeAdapter`s.
736 """
738 experimental_defer_build_mode: tuple[Literal['model', 'type_adapter'], ...] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
739 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
740 Controls when [`defer_build`][pydantic.config.ConfigDict.defer_build] is applicable. Defaults to `('model',)`.
742 Due to backwards compatibility reasons [`TypeAdapter`][pydantic.type_adapter.TypeAdapter] does not by default
743 respect `defer_build`. Meaning when `defer_build` is `True` and `experimental_defer_build_mode` is the default `('model',)`
744 then `TypeAdapter` immediately constructs its validator and serializer instead of postponing said construction until
745 the first model validation. Set this to `('model', 'type_adapter')` to make `TypeAdapter` respect the `defer_build`
746 so it postpones validator and serializer construction until the first validation or serialization.
748 !!! note
749 The `experimental_defer_build_mode` parameter is named with an underscore to suggest this is an experimental feature. It may
750 be removed or changed in the future in a minor release.
751 """
753 plugin_settings: dict[str, object] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
754 """A `dict` of settings for plugins. Defaults to `None`. 1abcdefghijklmnopqzABCDEFGrstuvwxy
756 See [Pydantic Plugins](../concepts/plugins.md) for details.
757 """
759 schema_generator: type[_GenerateSchema] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
760 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
761 A custom core schema generator class to use when generating JSON schemas.
762 Useful if you want to change the way types are validated across an entire model/schema. Defaults to `None`.
764 The `GenerateSchema` interface is subject to change, currently only the `string_schema` method is public.
766 See [#6737](https://github.com/pydantic/pydantic/pull/6737) for details.
767 """
769 json_schema_serialization_defaults_required: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
770 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
771 Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
773 This ensures that the serialization schema will reflect the fact a field with a default will always be present
774 when serializing the model, even though it is not required for validation.
776 However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
777 between validation and serialization, and don't mind fields with defaults being marked as not required during
778 serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
780 ```py
781 from pydantic import BaseModel, ConfigDict
783 class Model(BaseModel):
784 a: str = 'a'
786 model_config = ConfigDict(json_schema_serialization_defaults_required=True)
788 print(Model.model_json_schema(mode='validation'))
789 '''
790 {
791 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
792 'title': 'Model',
793 'type': 'object',
794 }
795 '''
796 print(Model.model_json_schema(mode='serialization'))
797 '''
798 {
799 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
800 'required': ['a'],
801 'title': 'Model',
802 'type': 'object',
803 }
804 '''
805 ```
806 """
808 json_schema_mode_override: Literal['validation', 'serialization', None] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
809 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
810 If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
811 the function call. Defaults to `None`.
813 This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
814 validation schema.
816 It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
817 and serialization that must both be referenced from the same schema; when this happens, we automatically append
818 `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
819 serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
820 the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
821 from being added to the definition references.
823 ```py
824 from pydantic import BaseModel, ConfigDict, Json
826 class Model(BaseModel):
827 a: Json[int] # requires a string to validate, but will dump an int
829 print(Model.model_json_schema(mode='serialization'))
830 '''
831 {
832 'properties': {'a': {'title': 'A', 'type': 'integer'}},
833 'required': ['a'],
834 'title': 'Model',
835 'type': 'object',
836 }
837 '''
839 class ForceInputModel(Model):
840 # the following ensures that even with mode='serialization', we
841 # will get the schema that would be generated for validation.
842 model_config = ConfigDict(json_schema_mode_override='validation')
844 print(ForceInputModel.model_json_schema(mode='serialization'))
845 '''
846 {
847 'properties': {
848 'a': {
849 'contentMediaType': 'application/json',
850 'contentSchema': {'type': 'integer'},
851 'title': 'A',
852 'type': 'string',
853 }
854 },
855 'required': ['a'],
856 'title': 'ForceInputModel',
857 'type': 'object',
858 }
859 '''
860 ```
861 """
863 coerce_numbers_to_str: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
864 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
865 If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
867 Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
869 ```py
870 from decimal import Decimal
872 from pydantic import BaseModel, ConfigDict, ValidationError
874 class Model(BaseModel):
875 value: str
877 try:
878 print(Model(value=42))
879 except ValidationError as e:
880 print(e)
881 '''
882 1 validation error for Model
883 value
884 Input should be a valid string [type=string_type, input_value=42, input_type=int]
885 '''
887 class Model(BaseModel):
888 model_config = ConfigDict(coerce_numbers_to_str=True)
890 value: str
892 repr(Model(value=42).value)
893 #> "42"
894 repr(Model(value=42.13).value)
895 #> "42.13"
896 repr(Model(value=Decimal('42.13')).value)
897 #> "42.13"
898 ```
899 """
901 regex_engine: Literal['rust-regex', 'python-re'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
902 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
903 The regex engine to be used for pattern validation.
904 Defaults to `'rust-regex'`.
906 - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
907 which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
908 - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
909 which supports all regex features, but may be slower.
911 !!! note
912 If you use a compiled regex pattern, the python-re engine will be used regardless of this setting.
913 This is so that flags such as `re.IGNORECASE` are respected.
915 ```py
916 from pydantic import BaseModel, ConfigDict, Field, ValidationError
918 class Model(BaseModel):
919 model_config = ConfigDict(regex_engine='python-re')
921 value: str = Field(pattern=r'^abc(?=def)')
923 print(Model(value='abcdef').value)
924 #> abcdef
926 try:
927 print(Model(value='abxyzcdef'))
928 except ValidationError as e:
929 print(e)
930 '''
931 1 validation error for Model
932 value
933 String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
934 '''
935 ```
936 """
938 validation_error_cause: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
939 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy
940 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`.
942 Note:
943 Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
945 Note:
946 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.
947 """
949 use_attribute_docstrings: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
950 ''' 1abcdefghijklmnopqzABCDEFGrstuvwxy
951 Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
952 should be used for field descriptions. Defaults to `False`.
954 Available in Pydantic v2.7+.
956 ```py
957 from pydantic import BaseModel, ConfigDict, Field
960 class Model(BaseModel):
961 model_config = ConfigDict(use_attribute_docstrings=True)
963 x: str
964 """
965 Example of an attribute docstring
966 """
968 y: int = Field(description="Description in Field")
969 """
970 Description in Field overrides attribute docstring
971 """
974 print(Model.model_fields["x"].description)
975 # > Example of an attribute docstring
976 print(Model.model_fields["y"].description)
977 # > Description in Field
978 ```
979 This requires the source code of the class to be available at runtime.
981 !!! warning "Usage with `TypedDict`"
982 Due to current limitations, attribute docstrings detection may not work as expected when using `TypedDict`
983 (in particular when multiple `TypedDict` classes have the same name in the same source file). The behavior
984 can be different depending on the Python version used.
985 '''
987 cache_strings: bool | Literal['all', 'keys', 'none'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
988 """ 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
989 Whether to cache strings to avoid constructing new Python objects. Defaults to True.
991 Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
993 - `True` or `'all'` (the default): cache all strings
994 - `'keys'`: cache only dictionary keys
995 - `False` or `'none'`: no caching
997 !!! note
998 `True` or `'all'` is required to cache strings during general validation because
999 validators don't know if they're in a key or a value.
1001 !!! tip
1002 If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
1003 as the performance difference is minimal if repeated strings are rare.
1004 """
1007_TypeT = TypeVar('_TypeT', bound=type) 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
1010def with_config(config: ConfigDict) -> Callable[[_TypeT], _TypeT]: 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy
1011 """Usage docs: https://docs.pydantic.dev/2.8/concepts/config/#configuration-with-dataclass-from-the-standard-library-or-typeddict
1013 A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
1015 Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
1016 especially with `TypedDict`.
1018 !!! example "Usage"
1020 ```py
1021 from typing_extensions import TypedDict
1023 from pydantic import ConfigDict, TypeAdapter, with_config
1025 @with_config(ConfigDict(str_to_lower=True))
1026 class Model(TypedDict):
1027 x: str
1029 ta = TypeAdapter(Model)
1031 print(ta.validate_python({'x': 'ABC'}))
1032 #> {'x': 'abc'}
1033 ```
1034 """
1036 def inner(class_: _TypeT, /) -> _TypeT: 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy
1037 # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
1038 # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
1039 # common mistakes, we at least check for `class_` to not be a Pydantic model.
1040 from ._internal._utils import is_model_class 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy
1042 if is_model_class(class_): 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy
1043 raise PydanticUserError( 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy
1044 f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
1045 code='with-config-on-model',
1046 )
1047 class_.__pydantic_config__ = config 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy
1048 return class_ 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy
1050 return inner 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy
1053__getattr__ = getattr_migration(__name__) 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy