You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1214 line
41 KiB

  1. """Configuration for Pydantic models."""
  2. from __future__ import annotations as _annotations
  3. import warnings
  4. from re import Pattern
  5. from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, cast, overload
  6. from typing_extensions import TypeAlias, TypedDict, Unpack, deprecated
  7. from ._migration import getattr_migration
  8. from .aliases import AliasGenerator
  9. from .errors import PydanticUserError
  10. from .warnings import PydanticDeprecatedSince211
  11. if TYPE_CHECKING:
  12. from ._internal._generate_schema import GenerateSchema as _GenerateSchema
  13. from .fields import ComputedFieldInfo, FieldInfo
  14. __all__ = ('ConfigDict', 'with_config')
  15. JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict']
  16. JsonDict: TypeAlias = dict[str, JsonValue]
  17. JsonEncoder = Callable[[Any], Any]
  18. JsonSchemaExtraCallable: TypeAlias = Union[
  19. Callable[[JsonDict], None],
  20. Callable[[JsonDict, type[Any]], None],
  21. ]
  22. ExtraValues = Literal['allow', 'ignore', 'forbid']
  23. class ConfigDict(TypedDict, total=False):
  24. """A TypedDict for configuring Pydantic behaviour."""
  25. title: str | None
  26. """The title for the generated JSON schema, defaults to the model's name"""
  27. model_title_generator: Callable[[type], str] | None
  28. """A callable that takes a model class and returns the title for it. Defaults to `None`."""
  29. field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
  30. """A callable that takes a field's name and info and returns title for it. Defaults to `None`."""
  31. str_to_lower: bool
  32. """Whether to convert all characters to lowercase for str types. Defaults to `False`."""
  33. str_to_upper: bool
  34. """Whether to convert all characters to uppercase for str types. Defaults to `False`."""
  35. str_strip_whitespace: bool
  36. """Whether to strip leading and trailing whitespace for str types."""
  37. str_min_length: int
  38. """The minimum length for str types. Defaults to `None`."""
  39. str_max_length: int | None
  40. """The maximum length for str types. Defaults to `None`."""
  41. extra: ExtraValues | None
  42. '''
  43. Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`.
  44. Three configuration values are available:
  45. - `'ignore'`: Providing extra data is ignored (the default):
  46. ```python
  47. from pydantic import BaseModel, ConfigDict
  48. class User(BaseModel):
  49. model_config = ConfigDict(extra='ignore') # (1)!
  50. name: str
  51. user = User(name='John Doe', age=20) # (2)!
  52. print(user)
  53. #> name='John Doe'
  54. ```
  55. 1. This is the default behaviour.
  56. 2. The `age` argument is ignored.
  57. - `'forbid'`: Providing extra data is not permitted, and a [`ValidationError`][pydantic_core.ValidationError]
  58. will be raised if this is the case:
  59. ```python
  60. from pydantic import BaseModel, ConfigDict, ValidationError
  61. class Model(BaseModel):
  62. x: int
  63. model_config = ConfigDict(extra='forbid')
  64. try:
  65. Model(x=1, y='a')
  66. except ValidationError as exc:
  67. print(exc)
  68. """
  69. 1 validation error for Model
  70. y
  71. Extra inputs are not permitted [type=extra_forbidden, input_value='a', input_type=str]
  72. """
  73. ```
  74. - `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute:
  75. ```python
  76. from pydantic import BaseModel, ConfigDict
  77. class Model(BaseModel):
  78. x: int
  79. model_config = ConfigDict(extra='allow')
  80. m = Model(x=1, y='a')
  81. assert m.__pydantic_extra__ == {'y': 'a'}
  82. ```
  83. By default, no validation will be applied to these extra items, but you can set a type for the values by overriding
  84. the type annotation for `__pydantic_extra__`:
  85. ```python
  86. from pydantic import BaseModel, ConfigDict, Field, ValidationError
  87. class Model(BaseModel):
  88. __pydantic_extra__: dict[str, int] = Field(init=False) # (1)!
  89. x: int
  90. model_config = ConfigDict(extra='allow')
  91. try:
  92. Model(x=1, y='a')
  93. except ValidationError as exc:
  94. print(exc)
  95. """
  96. 1 validation error for Model
  97. y
  98. Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
  99. """
  100. m = Model(x=1, y='2')
  101. assert m.x == 1
  102. assert m.y == 2
  103. assert m.model_dump() == {'x': 1, 'y': 2}
  104. assert m.__pydantic_extra__ == {'y': 2}
  105. ```
  106. 1. The `= Field(init=False)` does not have any effect at runtime, but prevents the `__pydantic_extra__` field from
  107. being included as a parameter to the model's `__init__` method by type checkers.
  108. '''
  109. frozen: bool
  110. """
  111. Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
  112. a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
  113. attributes are hashable. Defaults to `False`.
  114. Note:
  115. On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
  116. """
  117. populate_by_name: bool
  118. """
  119. Whether an aliased field may be populated by its name as given by the model
  120. attribute, as well as the alias. Defaults to `False`.
  121. !!! warning
  122. `populate_by_name` usage is not recommended in v2.11+ and will be deprecated in v3.
  123. Instead, you should use the [`validate_by_name`][pydantic.config.ConfigDict.validate_by_name] configuration setting.
  124. When `validate_by_name=True` and `validate_by_alias=True`, this is strictly equivalent to the
  125. previous behavior of `populate_by_name=True`.
  126. In v2.11, we also introduced a [`validate_by_alias`][pydantic.config.ConfigDict.validate_by_alias] setting that introduces more fine grained
  127. control for validation behavior.
  128. Here's how you might go about using the new settings to achieve the same behavior:
  129. ```python
  130. from pydantic import BaseModel, ConfigDict, Field
  131. class Model(BaseModel):
  132. model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
  133. my_field: str = Field(alias='my_alias') # (1)!
  134. m = Model(my_alias='foo') # (2)!
  135. print(m)
  136. #> my_field='foo'
  137. m = Model(my_alias='foo') # (3)!
  138. print(m)
  139. #> my_field='foo'
  140. ```
  141. 1. The field `'my_field'` has an alias `'my_alias'`.
  142. 2. The model is populated by the alias `'my_alias'`.
  143. 3. The model is populated by the attribute name `'my_field'`.
  144. """
  145. use_enum_values: bool
  146. """
  147. Whether to populate models with the `value` property of enums, rather than the raw enum.
  148. This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
  149. !!! note
  150. If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
  151. for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
  152. enum's value occurs during validation, not serialization.
  153. ```python
  154. from enum import Enum
  155. from typing import Optional
  156. from pydantic import BaseModel, ConfigDict, Field
  157. class SomeEnum(Enum):
  158. FOO = 'foo'
  159. BAR = 'bar'
  160. BAZ = 'baz'
  161. class SomeModel(BaseModel):
  162. model_config = ConfigDict(use_enum_values=True)
  163. some_enum: SomeEnum
  164. another_enum: Optional[SomeEnum] = Field(
  165. default=SomeEnum.FOO, validate_default=True
  166. )
  167. model1 = SomeModel(some_enum=SomeEnum.BAR)
  168. print(model1.model_dump())
  169. #> {'some_enum': 'bar', 'another_enum': 'foo'}
  170. model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
  171. print(model2.model_dump())
  172. #> {'some_enum': 'bar', 'another_enum': 'baz'}
  173. ```
  174. """
  175. validate_assignment: bool
  176. """
  177. Whether to validate the data when the model is changed. Defaults to `False`.
  178. The default behavior of Pydantic is to validate the data when the model is created.
  179. In case the user changes the data after the model is created, the model is _not_ revalidated.
  180. ```python
  181. from pydantic import BaseModel
  182. class User(BaseModel):
  183. name: str
  184. user = User(name='John Doe') # (1)!
  185. print(user)
  186. #> name='John Doe'
  187. user.name = 123 # (1)!
  188. print(user)
  189. #> name=123
  190. ```
  191. 1. The validation happens only when the model is created.
  192. 2. The validation does not happen when the data is changed.
  193. In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
  194. ```python
  195. from pydantic import BaseModel, ValidationError
  196. class User(BaseModel, validate_assignment=True): # (1)!
  197. name: str
  198. user = User(name='John Doe') # (2)!
  199. print(user)
  200. #> name='John Doe'
  201. try:
  202. user.name = 123 # (3)!
  203. except ValidationError as e:
  204. print(e)
  205. '''
  206. 1 validation error for User
  207. name
  208. Input should be a valid string [type=string_type, input_value=123, input_type=int]
  209. '''
  210. ```
  211. 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
  212. 2. The validation happens when the model is created.
  213. 3. The validation _also_ happens when the data is changed.
  214. """
  215. arbitrary_types_allowed: bool
  216. """
  217. Whether arbitrary types are allowed for field types. Defaults to `False`.
  218. ```python
  219. from pydantic import BaseModel, ConfigDict, ValidationError
  220. # This is not a pydantic model, it's an arbitrary class
  221. class Pet:
  222. def __init__(self, name: str):
  223. self.name = name
  224. class Model(BaseModel):
  225. model_config = ConfigDict(arbitrary_types_allowed=True)
  226. pet: Pet
  227. owner: str
  228. pet = Pet(name='Hedwig')
  229. # A simple check of instance type is used to validate the data
  230. model = Model(owner='Harry', pet=pet)
  231. print(model)
  232. #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
  233. print(model.pet)
  234. #> <__main__.Pet object at 0x0123456789ab>
  235. print(model.pet.name)
  236. #> Hedwig
  237. print(type(model.pet))
  238. #> <class '__main__.Pet'>
  239. try:
  240. # If the value is not an instance of the type, it's invalid
  241. Model(owner='Harry', pet='Hedwig')
  242. except ValidationError as e:
  243. print(e)
  244. '''
  245. 1 validation error for Model
  246. pet
  247. Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
  248. '''
  249. # Nothing in the instance of the arbitrary type is checked
  250. # Here name probably should have been a str, but it's not validated
  251. pet2 = Pet(name=42)
  252. model2 = Model(owner='Harry', pet=pet2)
  253. print(model2)
  254. #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
  255. print(model2.pet)
  256. #> <__main__.Pet object at 0x0123456789ab>
  257. print(model2.pet.name)
  258. #> 42
  259. print(type(model2.pet))
  260. #> <class '__main__.Pet'>
  261. ```
  262. """
  263. from_attributes: bool
  264. """
  265. Whether to build models and look up discriminators of tagged unions using python object attributes.
  266. """
  267. loc_by_alias: bool
  268. """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`."""
  269. alias_generator: Callable[[str], str] | AliasGenerator | None
  270. """
  271. A callable that takes a field name and returns an alias for it
  272. or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
  273. When using a callable, the alias generator is used for both validation and serialization.
  274. If you want to use different alias generators for validation and serialization, you can use
  275. [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.
  276. If data source field names do not match your code style (e. g. CamelCase fields),
  277. you can automatically generate aliases using `alias_generator`. Here's an example with
  278. a basic callable:
  279. ```python
  280. from pydantic import BaseModel, ConfigDict
  281. from pydantic.alias_generators import to_pascal
  282. class Voice(BaseModel):
  283. model_config = ConfigDict(alias_generator=to_pascal)
  284. name: str
  285. language_code: str
  286. voice = Voice(Name='Filiz', LanguageCode='tr-TR')
  287. print(voice.language_code)
  288. #> tr-TR
  289. print(voice.model_dump(by_alias=True))
  290. #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
  291. ```
  292. If you want to use different alias generators for validation and serialization, you can use
  293. [`AliasGenerator`][pydantic.aliases.AliasGenerator].
  294. ```python
  295. from pydantic import AliasGenerator, BaseModel, ConfigDict
  296. from pydantic.alias_generators import to_camel, to_pascal
  297. class Athlete(BaseModel):
  298. first_name: str
  299. last_name: str
  300. sport: str
  301. model_config = ConfigDict(
  302. alias_generator=AliasGenerator(
  303. validation_alias=to_camel,
  304. serialization_alias=to_pascal,
  305. )
  306. )
  307. athlete = Athlete(firstName='John', lastName='Doe', sport='track')
  308. print(athlete.model_dump(by_alias=True))
  309. #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
  310. ```
  311. Note:
  312. Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
  313. [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
  314. """
  315. ignored_types: tuple[type, ...]
  316. """A tuple of types that may occur as values of class attributes without annotations. This is
  317. typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
  318. class without an annotation and has a type that is not in this tuple (or otherwise recognized by
  319. _pydantic_), an error will be raised. Defaults to `()`.
  320. """
  321. allow_inf_nan: bool
  322. """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`."""
  323. json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
  324. """A dict or callable to provide extra JSON schema properties. Defaults to `None`."""
  325. json_encoders: dict[type[object], JsonEncoder] | None
  326. """
  327. A `dict` of custom JSON encoders for specific types. Defaults to `None`.
  328. !!! warning "Deprecated"
  329. This config option is a carryover from v1.
  330. We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
  331. It is still deprecated and will likely be removed in the future.
  332. """
  333. # new in V2
  334. strict: bool
  335. """
  336. _(new in V2)_ If `True`, strict validation is applied to all fields on the model.
  337. By default, Pydantic attempts to coerce values to the correct type, when possible.
  338. There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
  339. does not match the field's type annotation.
  340. To configure strict mode for all fields on a model, you can set `strict=True` on the model.
  341. ```python
  342. from pydantic import BaseModel, ConfigDict
  343. class Model(BaseModel):
  344. model_config = ConfigDict(strict=True)
  345. name: str
  346. age: int
  347. ```
  348. See [Strict Mode](../concepts/strict_mode.md) for more details.
  349. See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
  350. strict and lax modes.
  351. """
  352. # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
  353. revalidate_instances: Literal['always', 'never', 'subclass-instances']
  354. """
  355. When and how to revalidate models and dataclasses during validation. Accepts the string
  356. values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`.
  357. - `'never'` will not revalidate models and dataclasses during validation
  358. - `'always'` will revalidate models and dataclasses during validation
  359. - `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a
  360. subclass of the model or dataclass
  361. By default, model and dataclass instances are not revalidated during validation.
  362. ```python
  363. from pydantic import BaseModel
  364. class User(BaseModel, revalidate_instances='never'): # (1)!
  365. hobbies: list[str]
  366. class SubUser(User):
  367. sins: list[str]
  368. class Transaction(BaseModel):
  369. user: User
  370. my_user = User(hobbies=['reading'])
  371. t = Transaction(user=my_user)
  372. print(t)
  373. #> user=User(hobbies=['reading'])
  374. my_user.hobbies = [1] # (2)!
  375. t = Transaction(user=my_user) # (3)!
  376. print(t)
  377. #> user=User(hobbies=[1])
  378. my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
  379. t = Transaction(user=my_sub_user)
  380. print(t)
  381. #> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
  382. ```
  383. 1. `revalidate_instances` is set to `'never'` by **default.
  384. 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config.
  385. 3. Since `revalidate_instances` is set to `never`, this is not revalidated.
  386. If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'`
  387. in the model's config.
  388. ```python
  389. from pydantic import BaseModel, ValidationError
  390. class User(BaseModel, revalidate_instances='always'): # (1)!
  391. hobbies: list[str]
  392. class SubUser(User):
  393. sins: list[str]
  394. class Transaction(BaseModel):
  395. user: User
  396. my_user = User(hobbies=['reading'])
  397. t = Transaction(user=my_user)
  398. print(t)
  399. #> user=User(hobbies=['reading'])
  400. my_user.hobbies = [1]
  401. try:
  402. t = Transaction(user=my_user) # (2)!
  403. except ValidationError as e:
  404. print(e)
  405. '''
  406. 1 validation error for Transaction
  407. user.hobbies.0
  408. Input should be a valid string [type=string_type, input_value=1, input_type=int]
  409. '''
  410. my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
  411. t = Transaction(user=my_sub_user)
  412. print(t) # (3)!
  413. #> user=User(hobbies=['scuba diving'])
  414. ```
  415. 1. `revalidate_instances` is set to `'always'`.
  416. 2. The model is revalidated, since `revalidate_instances` is set to `'always'`.
  417. 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
  418. It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances
  419. of subclasses of the model.
  420. ```python
  421. from pydantic import BaseModel
  422. class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
  423. hobbies: list[str]
  424. class SubUser(User):
  425. sins: list[str]
  426. class Transaction(BaseModel):
  427. user: User
  428. my_user = User(hobbies=['reading'])
  429. t = Transaction(user=my_user)
  430. print(t)
  431. #> user=User(hobbies=['reading'])
  432. my_user.hobbies = [1]
  433. t = Transaction(user=my_user) # (2)!
  434. print(t)
  435. #> user=User(hobbies=[1])
  436. my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
  437. t = Transaction(user=my_sub_user)
  438. print(t) # (3)!
  439. #> user=User(hobbies=['scuba diving'])
  440. ```
  441. 1. `revalidate_instances` is set to `'subclass-instances'`.
  442. 2. This is not revalidated, since `my_user` is not a subclass of `User`.
  443. 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
  444. """
  445. ser_json_timedelta: Literal['iso8601', 'float']
  446. """
  447. The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
  448. `'float'`. Defaults to `'iso8601'`.
  449. - `'iso8601'` will serialize timedeltas to ISO 8601 durations.
  450. - `'float'` will serialize timedeltas to the total number of seconds.
  451. """
  452. ser_json_bytes: Literal['utf8', 'base64', 'hex']
  453. """
  454. The encoding of JSON serialized bytes. Defaults to `'utf8'`.
  455. Set equal to `val_json_bytes` to get back an equal value after serialization round trip.
  456. - `'utf8'` will serialize bytes to UTF-8 strings.
  457. - `'base64'` will serialize bytes to URL safe base64 strings.
  458. - `'hex'` will serialize bytes to hexadecimal strings.
  459. """
  460. val_json_bytes: Literal['utf8', 'base64', 'hex']
  461. """
  462. The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`.
  463. Set equal to `ser_json_bytes` to get back an equal value after serialization round trip.
  464. - `'utf8'` will deserialize UTF-8 strings to bytes.
  465. - `'base64'` will deserialize URL safe base64 strings to bytes.
  466. - `'hex'` will deserialize hexadecimal strings to bytes.
  467. """
  468. ser_json_inf_nan: Literal['null', 'constants', 'strings']
  469. """
  470. The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
  471. - `'null'` will serialize infinity and NaN values as `null`.
  472. - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
  473. - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.
  474. """
  475. # whether to validate default values during validation, default False
  476. validate_default: bool
  477. """Whether to validate default values during validation. Defaults to `False`."""
  478. validate_return: bool
  479. """Whether to validate the return value from call validators. Defaults to `False`."""
  480. protected_namespaces: tuple[str | Pattern[str], ...]
  481. """
  482. A `tuple` of strings and/or patterns that prevent models from having fields with names that conflict with them.
  483. For strings, we match on a prefix basis. Ex, if 'dog' is in the protected namespace, 'dog_name' will be protected.
  484. For patterns, we match on the entire field name. Ex, if `re.compile(r'^dog$')` is in the protected namespace, 'dog' will be protected, but 'dog_name' will not be.
  485. Defaults to `('model_validate', 'model_dump',)`.
  486. The reason we've selected these is to prevent collisions with other validation / dumping formats
  487. in the future - ex, `model_validate_{some_newly_supported_format}`.
  488. Before v2.10, Pydantic used `('model_',)` as the default value for this setting to
  489. prevent collisions between model attributes and `BaseModel`'s own methods. This was changed
  490. in v2.10 given feedback that this restriction was limiting in AI and data science contexts,
  491. where it is common to have fields with names like `model_id`, `model_input`, `model_output`, etc.
  492. For more details, see https://github.com/pydantic/pydantic/issues/10315.
  493. ```python
  494. import warnings
  495. from pydantic import BaseModel
  496. warnings.filterwarnings('error') # Raise warnings as errors
  497. try:
  498. class Model(BaseModel):
  499. model_dump_something: str
  500. except UserWarning as e:
  501. print(e)
  502. '''
  503. Field "model_dump_something" in Model has conflict with protected namespace "model_dump".
  504. You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('model_validate',)`.
  505. '''
  506. ```
  507. You can customize this behavior using the `protected_namespaces` setting:
  508. ```python {test="skip"}
  509. import re
  510. import warnings
  511. from pydantic import BaseModel, ConfigDict
  512. with warnings.catch_warnings(record=True) as caught_warnings:
  513. warnings.simplefilter('always') # Catch all warnings
  514. class Model(BaseModel):
  515. safe_field: str
  516. also_protect_field: str
  517. protect_this: str
  518. model_config = ConfigDict(
  519. protected_namespaces=(
  520. 'protect_me_',
  521. 'also_protect_',
  522. re.compile('^protect_this$'),
  523. )
  524. )
  525. for warning in caught_warnings:
  526. print(f'{warning.message}')
  527. '''
  528. Field "also_protect_field" in Model has conflict with protected namespace "also_protect_".
  529. You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', re.compile('^protect_this$'))`.
  530. Field "protect_this" in Model has conflict with protected namespace "re.compile('^protect_this$')".
  531. You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', 'also_protect_')`.
  532. '''
  533. ```
  534. While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
  535. an error _is_ raised if there is an actual collision with an existing attribute:
  536. ```python
  537. from pydantic import BaseModel, ConfigDict
  538. try:
  539. class Model(BaseModel):
  540. model_validate: str
  541. model_config = ConfigDict(protected_namespaces=('model_',))
  542. except NameError as e:
  543. print(e)
  544. '''
  545. Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
  546. '''
  547. ```
  548. """
  549. hide_input_in_errors: bool
  550. """
  551. Whether to hide inputs when printing errors. Defaults to `False`.
  552. Pydantic shows the input value and type when it raises `ValidationError` during the validation.
  553. ```python
  554. from pydantic import BaseModel, ValidationError
  555. class Model(BaseModel):
  556. a: str
  557. try:
  558. Model(a=123)
  559. except ValidationError as e:
  560. print(e)
  561. '''
  562. 1 validation error for Model
  563. a
  564. Input should be a valid string [type=string_type, input_value=123, input_type=int]
  565. '''
  566. ```
  567. You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
  568. ```python
  569. from pydantic import BaseModel, ConfigDict, ValidationError
  570. class Model(BaseModel):
  571. a: str
  572. model_config = ConfigDict(hide_input_in_errors=True)
  573. try:
  574. Model(a=123)
  575. except ValidationError as e:
  576. print(e)
  577. '''
  578. 1 validation error for Model
  579. a
  580. Input should be a valid string [type=string_type]
  581. '''
  582. ```
  583. """
  584. defer_build: bool
  585. """
  586. Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
  587. This can be useful to avoid the overhead of building models which are only
  588. used nested within other models, or when you want to manually define type namespace via
  589. [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
  590. Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances.
  591. """
  592. plugin_settings: dict[str, object] | None
  593. """A `dict` of settings for plugins. Defaults to `None`."""
  594. schema_generator: type[_GenerateSchema] | None
  595. """
  596. !!! warning
  597. `schema_generator` is deprecated in v2.10.
  598. Prior to v2.10, this setting was advertised as highly subject to change.
  599. It's possible that this interface may once again become public once the internal core schema generation
  600. API is more stable, but that will likely come after significant performance improvements have been made.
  601. """
  602. json_schema_serialization_defaults_required: bool
  603. """
  604. Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
  605. This ensures that the serialization schema will reflect the fact a field with a default will always be present
  606. when serializing the model, even though it is not required for validation.
  607. However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
  608. between validation and serialization, and don't mind fields with defaults being marked as not required during
  609. serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
  610. ```python
  611. from pydantic import BaseModel, ConfigDict
  612. class Model(BaseModel):
  613. a: str = 'a'
  614. model_config = ConfigDict(json_schema_serialization_defaults_required=True)
  615. print(Model.model_json_schema(mode='validation'))
  616. '''
  617. {
  618. 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
  619. 'title': 'Model',
  620. 'type': 'object',
  621. }
  622. '''
  623. print(Model.model_json_schema(mode='serialization'))
  624. '''
  625. {
  626. 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
  627. 'required': ['a'],
  628. 'title': 'Model',
  629. 'type': 'object',
  630. }
  631. '''
  632. ```
  633. """
  634. json_schema_mode_override: Literal['validation', 'serialization', None]
  635. """
  636. If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
  637. the function call. Defaults to `None`.
  638. This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
  639. validation schema.
  640. It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
  641. and serialization that must both be referenced from the same schema; when this happens, we automatically append
  642. `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
  643. serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
  644. the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
  645. from being added to the definition references.
  646. ```python
  647. from pydantic import BaseModel, ConfigDict, Json
  648. class Model(BaseModel):
  649. a: Json[int] # requires a string to validate, but will dump an int
  650. print(Model.model_json_schema(mode='serialization'))
  651. '''
  652. {
  653. 'properties': {'a': {'title': 'A', 'type': 'integer'}},
  654. 'required': ['a'],
  655. 'title': 'Model',
  656. 'type': 'object',
  657. }
  658. '''
  659. class ForceInputModel(Model):
  660. # the following ensures that even with mode='serialization', we
  661. # will get the schema that would be generated for validation.
  662. model_config = ConfigDict(json_schema_mode_override='validation')
  663. print(ForceInputModel.model_json_schema(mode='serialization'))
  664. '''
  665. {
  666. 'properties': {
  667. 'a': {
  668. 'contentMediaType': 'application/json',
  669. 'contentSchema': {'type': 'integer'},
  670. 'title': 'A',
  671. 'type': 'string',
  672. }
  673. },
  674. 'required': ['a'],
  675. 'title': 'ForceInputModel',
  676. 'type': 'object',
  677. }
  678. '''
  679. ```
  680. """
  681. coerce_numbers_to_str: bool
  682. """
  683. If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
  684. Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
  685. ```python
  686. from decimal import Decimal
  687. from pydantic import BaseModel, ConfigDict, ValidationError
  688. class Model(BaseModel):
  689. value: str
  690. try:
  691. print(Model(value=42))
  692. except ValidationError as e:
  693. print(e)
  694. '''
  695. 1 validation error for Model
  696. value
  697. Input should be a valid string [type=string_type, input_value=42, input_type=int]
  698. '''
  699. class Model(BaseModel):
  700. model_config = ConfigDict(coerce_numbers_to_str=True)
  701. value: str
  702. repr(Model(value=42).value)
  703. #> "42"
  704. repr(Model(value=42.13).value)
  705. #> "42.13"
  706. repr(Model(value=Decimal('42.13')).value)
  707. #> "42.13"
  708. ```
  709. """
  710. regex_engine: Literal['rust-regex', 'python-re']
  711. """
  712. The regex engine to be used for pattern validation.
  713. Defaults to `'rust-regex'`.
  714. - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
  715. which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
  716. - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
  717. which supports all regex features, but may be slower.
  718. !!! note
  719. If you use a compiled regex pattern, the python-re engine will be used regardless of this setting.
  720. This is so that flags such as `re.IGNORECASE` are respected.
  721. ```python
  722. from pydantic import BaseModel, ConfigDict, Field, ValidationError
  723. class Model(BaseModel):
  724. model_config = ConfigDict(regex_engine='python-re')
  725. value: str = Field(pattern=r'^abc(?=def)')
  726. print(Model(value='abcdef').value)
  727. #> abcdef
  728. try:
  729. print(Model(value='abxyzcdef'))
  730. except ValidationError as e:
  731. print(e)
  732. '''
  733. 1 validation error for Model
  734. value
  735. String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
  736. '''
  737. ```
  738. """
  739. validation_error_cause: bool
  740. """
  741. 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`.
  742. Note:
  743. Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
  744. Note:
  745. 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.
  746. """
  747. use_attribute_docstrings: bool
  748. '''
  749. Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
  750. should be used for field descriptions. Defaults to `False`.
  751. Available in Pydantic v2.7+.
  752. ```python
  753. from pydantic import BaseModel, ConfigDict, Field
  754. class Model(BaseModel):
  755. model_config = ConfigDict(use_attribute_docstrings=True)
  756. x: str
  757. """
  758. Example of an attribute docstring
  759. """
  760. y: int = Field(description="Description in Field")
  761. """
  762. Description in Field overrides attribute docstring
  763. """
  764. print(Model.model_fields["x"].description)
  765. # > Example of an attribute docstring
  766. print(Model.model_fields["y"].description)
  767. # > Description in Field
  768. ```
  769. This requires the source code of the class to be available at runtime.
  770. !!! warning "Usage with `TypedDict` and stdlib dataclasses"
  771. Due to current limitations, attribute docstrings detection may not work as expected when using
  772. [`TypedDict`][typing.TypedDict] and stdlib dataclasses, in particular when:
  773. - inheritance is being used.
  774. - multiple classes have the same name in the same source file.
  775. '''
  776. cache_strings: bool | Literal['all', 'keys', 'none']
  777. """
  778. Whether to cache strings to avoid constructing new Python objects. Defaults to True.
  779. Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
  780. - `True` or `'all'` (the default): cache all strings
  781. - `'keys'`: cache only dictionary keys
  782. - `False` or `'none'`: no caching
  783. !!! note
  784. `True` or `'all'` is required to cache strings during general validation because
  785. validators don't know if they're in a key or a value.
  786. !!! tip
  787. If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
  788. as the performance difference is minimal if repeated strings are rare.
  789. """
  790. validate_by_alias: bool
  791. """
  792. Whether an aliased field may be populated by its alias. Defaults to `True`.
  793. !!! note
  794. In v2.11, `validate_by_alias` was introduced in conjunction with [`validate_by_name`][pydantic.ConfigDict.validate_by_name]
  795. to empower users with more fine grained validation control. In <v2.11, disabling validation by alias was not possible.
  796. Here's an example of disabling validation by alias:
  797. ```py
  798. from pydantic import BaseModel, ConfigDict, Field
  799. class Model(BaseModel):
  800. model_config = ConfigDict(validate_by_name=True, validate_by_alias=False)
  801. my_field: str = Field(validation_alias='my_alias') # (1)!
  802. m = Model(my_field='foo') # (2)!
  803. print(m)
  804. #> my_field='foo'
  805. ```
  806. 1. The field `'my_field'` has an alias `'my_alias'`.
  807. 2. The model can only be populated by the attribute name `'my_field'`.
  808. !!! warning
  809. You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
  810. This would make it impossible to populate an attribute.
  811. See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
  812. If you set `validate_by_alias` to `False`, under the hood, Pydantic dynamically sets
  813. `validate_by_name` to `True` to ensure that validation can still occur.
  814. """
  815. validate_by_name: bool
  816. """
  817. Whether an aliased field may be populated by its name as given by the model
  818. attribute. Defaults to `False`.
  819. !!! note
  820. In v2.0-v2.10, the `populate_by_name` configuration setting was used to specify
  821. whether or not a field could be populated by its name **and** alias.
  822. In v2.11, `validate_by_name` was introduced in conjunction with [`validate_by_alias`][pydantic.ConfigDict.validate_by_alias]
  823. to empower users with more fine grained validation behavior control.
  824. ```python
  825. from pydantic import BaseModel, ConfigDict, Field
  826. class Model(BaseModel):
  827. model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
  828. my_field: str = Field(validation_alias='my_alias') # (1)!
  829. m = Model(my_alias='foo') # (2)!
  830. print(m)
  831. #> my_field='foo'
  832. m = Model(my_field='foo') # (3)!
  833. print(m)
  834. #> my_field='foo'
  835. ```
  836. 1. The field `'my_field'` has an alias `'my_alias'`.
  837. 2. The model is populated by the alias `'my_alias'`.
  838. 3. The model is populated by the attribute name `'my_field'`.
  839. !!! warning
  840. You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
  841. This would make it impossible to populate an attribute.
  842. See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
  843. """
  844. serialize_by_alias: bool
  845. """
  846. Whether an aliased field should be serialized by its alias. Defaults to `False`.
  847. Note: In v2.11, `serialize_by_alias` was introduced to address the
  848. [popular request](https://github.com/pydantic/pydantic/issues/8379)
  849. for consistency with alias behavior for validation and serialization settings.
  850. In v3, the default value is expected to change to `True` for consistency with the validation default.
  851. ```python
  852. from pydantic import BaseModel, ConfigDict, Field
  853. class Model(BaseModel):
  854. model_config = ConfigDict(serialize_by_alias=True)
  855. my_field: str = Field(serialization_alias='my_alias') # (1)!
  856. m = Model(my_field='foo')
  857. print(m.model_dump()) # (2)!
  858. #> {'my_alias': 'foo'}
  859. ```
  860. 1. The field `'my_field'` has an alias `'my_alias'`.
  861. 2. The model is serialized using the alias `'my_alias'` for the `'my_field'` attribute.
  862. """
  863. _TypeT = TypeVar('_TypeT', bound=type)
  864. @overload
  865. @deprecated('Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead.')
  866. def with_config(*, config: ConfigDict) -> Callable[[_TypeT], _TypeT]: ...
  867. @overload
  868. def with_config(config: ConfigDict, /) -> Callable[[_TypeT], _TypeT]: ...
  869. @overload
  870. def with_config(**config: Unpack[ConfigDict]) -> Callable[[_TypeT], _TypeT]: ...
  871. def with_config(config: ConfigDict | None = None, /, **kwargs: Any) -> Callable[[_TypeT], _TypeT]:
  872. """!!! abstract "Usage Documentation"
  873. [Configuration with other types](../concepts/config.md#configuration-on-other-supported-types)
  874. A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
  875. Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
  876. especially with `TypedDict`.
  877. !!! example "Usage"
  878. ```python
  879. from typing_extensions import TypedDict
  880. from pydantic import ConfigDict, TypeAdapter, with_config
  881. @with_config(ConfigDict(str_to_lower=True))
  882. class TD(TypedDict):
  883. x: str
  884. ta = TypeAdapter(TD)
  885. print(ta.validate_python({'x': 'ABC'}))
  886. #> {'x': 'abc'}
  887. ```
  888. """
  889. if config is not None and kwargs:
  890. raise ValueError('Cannot specify both `config` and keyword arguments')
  891. if len(kwargs) == 1 and (kwargs_conf := kwargs.get('config')) is not None:
  892. warnings.warn(
  893. 'Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead',
  894. category=PydanticDeprecatedSince211,
  895. stacklevel=2,
  896. )
  897. final_config = cast(ConfigDict, kwargs_conf)
  898. else:
  899. final_config = config if config is not None else cast(ConfigDict, kwargs)
  900. def inner(class_: _TypeT, /) -> _TypeT:
  901. # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
  902. # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
  903. # common mistakes, we at least check for `class_` to not be a Pydantic model.
  904. from ._internal._utils import is_model_class
  905. if is_model_class(class_):
  906. raise PydanticUserError(
  907. f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
  908. code='with-config-on-model',
  909. )
  910. class_.__pydantic_config__ = final_config
  911. return class_
  912. return inner
  913. __getattr__ = getattr_migration(__name__)