config.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. """Configuration for Pydantic models."""
  2. from __future__ import annotations as _annotations
  3. from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, Union
  4. from typing_extensions import Literal, TypeAlias, TypedDict
  5. from ._migration import getattr_migration
  6. if TYPE_CHECKING:
  7. from ._internal._generate_schema import GenerateSchema as _GenerateSchema
  8. __all__ = ('ConfigDict',)
  9. JsonValue: TypeAlias = Union[int, float, str, bool, None, List['JsonValue'], 'JsonDict']
  10. JsonDict: TypeAlias = Dict[str, JsonValue]
  11. JsonEncoder = Callable[[Any], Any]
  12. JsonSchemaExtraCallable: TypeAlias = Union[
  13. Callable[[JsonDict], None],
  14. Callable[[JsonDict, Type[Any]], None],
  15. ]
  16. ExtraValues = Literal['allow', 'ignore', 'forbid']
  17. class ConfigDict(TypedDict, total=False):
  18. """A TypedDict for configuring Pydantic behaviour."""
  19. title: str | None
  20. """The title for the generated JSON schema, defaults to the model's name"""
  21. str_to_lower: bool
  22. """Whether to convert all characters to lowercase for str types. Defaults to `False`."""
  23. str_to_upper: bool
  24. """Whether to convert all characters to uppercase for str types. Defaults to `False`."""
  25. str_strip_whitespace: bool
  26. """Whether to strip leading and trailing whitespace for str types."""
  27. str_min_length: int
  28. """The minimum length for str types. Defaults to `None`."""
  29. str_max_length: int | None
  30. """The maximum length for str types. Defaults to `None`."""
  31. extra: ExtraValues | None
  32. """
  33. Whether to ignore, allow, or forbid extra attributes during model initialization. Defaults to `'ignore'`.
  34. You can configure how pydantic handles the attributes that are not defined in the model:
  35. * `allow` - Allow any extra attributes.
  36. * `forbid` - Forbid any extra attributes.
  37. * `ignore` - Ignore any extra attributes.
  38. ```py
  39. from pydantic import BaseModel, ConfigDict
  40. class User(BaseModel):
  41. model_config = ConfigDict(extra='ignore') # (1)!
  42. name: str
  43. user = User(name='John Doe', age=20) # (2)!
  44. print(user)
  45. #> name='John Doe'
  46. ```
  47. 1. This is the default behaviour.
  48. 2. The `age` argument is ignored.
  49. Instead, with `extra='allow'`, the `age` argument is included:
  50. ```py
  51. from pydantic import BaseModel, ConfigDict
  52. class User(BaseModel):
  53. model_config = ConfigDict(extra='allow')
  54. name: str
  55. user = User(name='John Doe', age=20) # (1)!
  56. print(user)
  57. #> name='John Doe' age=20
  58. ```
  59. 1. The `age` argument is included.
  60. With `extra='forbid'`, an error is raised:
  61. ```py
  62. from pydantic import BaseModel, ConfigDict, ValidationError
  63. class User(BaseModel):
  64. model_config = ConfigDict(extra='forbid')
  65. name: str
  66. try:
  67. User(name='John Doe', age=20)
  68. except ValidationError as e:
  69. print(e)
  70. '''
  71. 1 validation error for User
  72. age
  73. Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int]
  74. '''
  75. ```
  76. """
  77. frozen: bool
  78. """
  79. Whether or not models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
  80. a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
  81. attributes are hashable. Defaults to `False`.
  82. Note:
  83. On V1, this setting was called `allow_mutation`, and was `True` by default.
  84. """
  85. populate_by_name: bool
  86. """
  87. Whether an aliased field may be populated by its name as given by the model
  88. attribute, as well as the alias. Defaults to `False`.
  89. Note:
  90. The name of this configuration setting was changed in **v2.0** from
  91. `allow_population_by_field_name` to `populate_by_name`.
  92. ```py
  93. from pydantic import BaseModel, ConfigDict, Field
  94. class User(BaseModel):
  95. model_config = ConfigDict(populate_by_name=True)
  96. name: str = Field(alias='full_name') # (1)!
  97. age: int
  98. user = User(full_name='John Doe', age=20) # (2)!
  99. print(user)
  100. #> name='John Doe' age=20
  101. user = User(name='John Doe', age=20) # (3)!
  102. print(user)
  103. #> name='John Doe' age=20
  104. ```
  105. 1. The field `'name'` has an alias `'full_name'`.
  106. 2. The model is populated by the alias `'full_name'`.
  107. 3. The model is populated by the field name `'name'`.
  108. """
  109. use_enum_values: bool
  110. """
  111. Whether to populate models with the `value` property of enums, rather than the raw enum.
  112. This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
  113. !!! note
  114. If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
  115. for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
  116. enum's value occurs during validation, not serialization.
  117. ```py
  118. from enum import Enum
  119. from typing import Optional
  120. from pydantic import BaseModel, ConfigDict, Field
  121. class SomeEnum(Enum):
  122. FOO = 'foo'
  123. BAR = 'bar'
  124. BAZ = 'baz'
  125. class SomeModel(BaseModel):
  126. model_config = ConfigDict(use_enum_values=True)
  127. some_enum: SomeEnum
  128. another_enum: Optional[SomeEnum] = Field(default=SomeEnum.FOO, validate_default=True)
  129. model1 = SomeModel(some_enum=SomeEnum.BAR)
  130. print(model1.model_dump())
  131. # {'some_enum': 'bar', 'another_enum': 'foo'}
  132. model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
  133. print(model2.model_dump())
  134. #> {'some_enum': 'bar', 'another_enum': 'baz'}
  135. ```
  136. """
  137. validate_assignment: bool
  138. """
  139. Whether to validate the data when the model is changed. Defaults to `False`.
  140. The default behavior of Pydantic is to validate the data when the model is created.
  141. In case the user changes the data after the model is created, the model is _not_ revalidated.
  142. ```py
  143. from pydantic import BaseModel
  144. class User(BaseModel):
  145. name: str
  146. user = User(name='John Doe') # (1)!
  147. print(user)
  148. #> name='John Doe'
  149. user.name = 123 # (1)!
  150. print(user)
  151. #> name=123
  152. ```
  153. 1. The validation happens only when the model is created.
  154. 2. The validation does not happen when the data is changed.
  155. In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
  156. ```py
  157. from pydantic import BaseModel, ValidationError
  158. class User(BaseModel, validate_assignment=True): # (1)!
  159. name: str
  160. user = User(name='John Doe') # (2)!
  161. print(user)
  162. #> name='John Doe'
  163. try:
  164. user.name = 123 # (3)!
  165. except ValidationError as e:
  166. print(e)
  167. '''
  168. 1 validation error for User
  169. name
  170. Input should be a valid string [type=string_type, input_value=123, input_type=int]
  171. '''
  172. ```
  173. 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
  174. 2. The validation happens when the model is created.
  175. 3. The validation _also_ happens when the data is changed.
  176. """
  177. arbitrary_types_allowed: bool
  178. """
  179. Whether arbitrary types are allowed for field types. Defaults to `False`.
  180. ```py
  181. from pydantic import BaseModel, ConfigDict, ValidationError
  182. # This is not a pydantic model, it's an arbitrary class
  183. class Pet:
  184. def __init__(self, name: str):
  185. self.name = name
  186. class Model(BaseModel):
  187. model_config = ConfigDict(arbitrary_types_allowed=True)
  188. pet: Pet
  189. owner: str
  190. pet = Pet(name='Hedwig')
  191. # A simple check of instance type is used to validate the data
  192. model = Model(owner='Harry', pet=pet)
  193. print(model)
  194. #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
  195. print(model.pet)
  196. #> <__main__.Pet object at 0x0123456789ab>
  197. print(model.pet.name)
  198. #> Hedwig
  199. print(type(model.pet))
  200. #> <class '__main__.Pet'>
  201. try:
  202. # If the value is not an instance of the type, it's invalid
  203. Model(owner='Harry', pet='Hedwig')
  204. except ValidationError as e:
  205. print(e)
  206. '''
  207. 1 validation error for Model
  208. pet
  209. Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
  210. '''
  211. # Nothing in the instance of the arbitrary type is checked
  212. # Here name probably should have been a str, but it's not validated
  213. pet2 = Pet(name=42)
  214. model2 = Model(owner='Harry', pet=pet2)
  215. print(model2)
  216. #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
  217. print(model2.pet)
  218. #> <__main__.Pet object at 0x0123456789ab>
  219. print(model2.pet.name)
  220. #> 42
  221. print(type(model2.pet))
  222. #> <class '__main__.Pet'>
  223. ```
  224. """
  225. from_attributes: bool
  226. """
  227. Whether to build models and look up discriminators of tagged unions using python object attributes.
  228. """
  229. loc_by_alias: bool
  230. """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`."""
  231. alias_generator: Callable[[str], str] | None
  232. """
  233. A callable that takes a field name and returns an alias for it.
  234. If data source field names do not match your code style (e. g. CamelCase fields),
  235. you can automatically generate aliases using `alias_generator`:
  236. ```py
  237. from pydantic import BaseModel, ConfigDict
  238. from pydantic.alias_generators import to_pascal
  239. class Voice(BaseModel):
  240. model_config = ConfigDict(alias_generator=to_pascal)
  241. name: str
  242. language_code: str
  243. voice = Voice(Name='Filiz', LanguageCode='tr-TR')
  244. print(voice.language_code)
  245. #> tr-TR
  246. print(voice.model_dump(by_alias=True))
  247. #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
  248. ```
  249. Note:
  250. Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
  251. [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
  252. """
  253. ignored_types: tuple[type, ...]
  254. """A tuple of types that may occur as values of class attributes without annotations. This is
  255. typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
  256. class without an annotation and has a type that is not in this tuple (or otherwise recognized by
  257. _pydantic_), an error will be raised. Defaults to `()`.
  258. """
  259. allow_inf_nan: bool
  260. """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float fields. Defaults to `True`."""
  261. json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
  262. """A dict or callable to provide extra JSON schema properties. Defaults to `None`."""
  263. json_encoders: dict[type[object], JsonEncoder] | None
  264. """
  265. A `dict` of custom JSON encoders for specific types. Defaults to `None`.
  266. !!! warning "Deprecated"
  267. This config option is a carryover from v1.
  268. We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
  269. It is still deprecated and will likely be removed in the future.
  270. """
  271. # new in V2
  272. strict: bool
  273. """
  274. _(new in V2)_ If `True`, strict validation is applied to all fields on the model.
  275. By default, Pydantic attempts to coerce values to the correct type, when possible.
  276. There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
  277. does not match the field's type annotation.
  278. To configure strict mode for all fields on a model, you can set `strict=True` on the model.
  279. ```py
  280. from pydantic import BaseModel, ConfigDict
  281. class Model(BaseModel):
  282. model_config = ConfigDict(strict=True)
  283. name: str
  284. age: int
  285. ```
  286. See [Strict Mode](../concepts/strict_mode.md) for more details.
  287. See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
  288. strict and lax modes.
  289. """
  290. # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
  291. revalidate_instances: Literal['always', 'never', 'subclass-instances']
  292. """
  293. When and how to revalidate models and dataclasses during validation. Accepts the string
  294. values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`.
  295. - `'never'` will not revalidate models and dataclasses during validation
  296. - `'always'` will revalidate models and dataclasses during validation
  297. - `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a
  298. subclass of the model or dataclass
  299. By default, model and dataclass instances are not revalidated during validation.
  300. ```py
  301. from typing import List
  302. from pydantic import BaseModel
  303. class User(BaseModel, revalidate_instances='never'): # (1)!
  304. hobbies: List[str]
  305. class SubUser(User):
  306. sins: List[str]
  307. class Transaction(BaseModel):
  308. user: User
  309. my_user = User(hobbies=['reading'])
  310. t = Transaction(user=my_user)
  311. print(t)
  312. #> user=User(hobbies=['reading'])
  313. my_user.hobbies = [1] # (2)!
  314. t = Transaction(user=my_user) # (3)!
  315. print(t)
  316. #> user=User(hobbies=[1])
  317. my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
  318. t = Transaction(user=my_sub_user)
  319. print(t)
  320. #> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
  321. ```
  322. 1. `revalidate_instances` is set to `'never'` by **default.
  323. 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config.
  324. 3. Since `revalidate_instances` is set to `never`, this is not revalidated.
  325. If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'`
  326. in the model's config.
  327. ```py
  328. from typing import List
  329. from pydantic import BaseModel, ValidationError
  330. class User(BaseModel, revalidate_instances='always'): # (1)!
  331. hobbies: List[str]
  332. class SubUser(User):
  333. sins: List[str]
  334. class Transaction(BaseModel):
  335. user: User
  336. my_user = User(hobbies=['reading'])
  337. t = Transaction(user=my_user)
  338. print(t)
  339. #> user=User(hobbies=['reading'])
  340. my_user.hobbies = [1]
  341. try:
  342. t = Transaction(user=my_user) # (2)!
  343. except ValidationError as e:
  344. print(e)
  345. '''
  346. 1 validation error for Transaction
  347. user.hobbies.0
  348. Input should be a valid string [type=string_type, input_value=1, input_type=int]
  349. '''
  350. my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
  351. t = Transaction(user=my_sub_user)
  352. print(t) # (3)!
  353. #> user=User(hobbies=['scuba diving'])
  354. ```
  355. 1. `revalidate_instances` is set to `'always'`.
  356. 2. The model is revalidated, since `revalidate_instances` is set to `'always'`.
  357. 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
  358. It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances
  359. of subclasses of the model.
  360. ```py
  361. from typing import List
  362. from pydantic import BaseModel
  363. class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
  364. hobbies: List[str]
  365. class SubUser(User):
  366. sins: List[str]
  367. class Transaction(BaseModel):
  368. user: User
  369. my_user = User(hobbies=['reading'])
  370. t = Transaction(user=my_user)
  371. print(t)
  372. #> user=User(hobbies=['reading'])
  373. my_user.hobbies = [1]
  374. t = Transaction(user=my_user) # (2)!
  375. print(t)
  376. #> user=User(hobbies=[1])
  377. my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
  378. t = Transaction(user=my_sub_user)
  379. print(t) # (3)!
  380. #> user=User(hobbies=['scuba diving'])
  381. ```
  382. 1. `revalidate_instances` is set to `'subclass-instances'`.
  383. 2. This is not revalidated, since `my_user` is not a subclass of `User`.
  384. 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
  385. """
  386. ser_json_timedelta: Literal['iso8601', 'float']
  387. """
  388. The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
  389. `'float'`. Defaults to `'iso8601'`.
  390. - `'iso8601'` will serialize timedeltas to ISO 8601 durations.
  391. - `'float'` will serialize timedeltas to the total number of seconds.
  392. """
  393. ser_json_bytes: Literal['utf8', 'base64']
  394. """
  395. The encoding of JSON serialized bytes. Accepts the string values of `'utf8'` and `'base64'`.
  396. Defaults to `'utf8'`.
  397. - `'utf8'` will serialize bytes to UTF-8 strings.
  398. - `'base64'` will serialize bytes to URL safe base64 strings.
  399. """
  400. ser_json_inf_nan: Literal['null', 'constants']
  401. """
  402. The encoding of JSON serialized infinity and NaN float values. Accepts the string values of `'null'` and `'constants'`.
  403. Defaults to `'null'`.
  404. - `'null'` will serialize infinity and NaN values as `null`.
  405. - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
  406. """
  407. # whether to validate default values during validation, default False
  408. validate_default: bool
  409. """Whether to validate default values during validation. Defaults to `False`."""
  410. validate_return: bool
  411. """whether to validate the return value from call validators. Defaults to `False`."""
  412. protected_namespaces: tuple[str, ...]
  413. """
  414. A `tuple` of strings that prevent model to have field which conflict with them.
  415. Defaults to `('model_', )`).
  416. Pydantic prevents collisions between model attributes and `BaseModel`'s own methods by
  417. namespacing them with the prefix `model_`.
  418. ```py
  419. import warnings
  420. from pydantic import BaseModel
  421. warnings.filterwarnings('error') # Raise warnings as errors
  422. try:
  423. class Model(BaseModel):
  424. model_prefixed_field: str
  425. except UserWarning as e:
  426. print(e)
  427. '''
  428. Field "model_prefixed_field" has conflict with protected namespace "model_".
  429. You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`.
  430. '''
  431. ```
  432. You can customize this behavior using the `protected_namespaces` setting:
  433. ```py
  434. import warnings
  435. from pydantic import BaseModel, ConfigDict
  436. warnings.filterwarnings('error') # Raise warnings as errors
  437. try:
  438. class Model(BaseModel):
  439. model_prefixed_field: str
  440. also_protect_field: str
  441. model_config = ConfigDict(
  442. protected_namespaces=('protect_me_', 'also_protect_')
  443. )
  444. except UserWarning as e:
  445. print(e)
  446. '''
  447. Field "also_protect_field" has conflict with protected namespace "also_protect_".
  448. You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_',)`.
  449. '''
  450. ```
  451. While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
  452. an error _is_ raised if there is an actual collision with an existing attribute:
  453. ```py
  454. from pydantic import BaseModel
  455. try:
  456. class Model(BaseModel):
  457. model_validate: str
  458. except NameError as e:
  459. print(e)
  460. '''
  461. Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
  462. '''
  463. ```
  464. """
  465. hide_input_in_errors: bool
  466. """
  467. Whether to hide inputs when printing errors. Defaults to `False`.
  468. Pydantic shows the input value and type when it raises `ValidationError` during the validation.
  469. ```py
  470. from pydantic import BaseModel, ValidationError
  471. class Model(BaseModel):
  472. a: str
  473. try:
  474. Model(a=123)
  475. except ValidationError as e:
  476. print(e)
  477. '''
  478. 1 validation error for Model
  479. a
  480. Input should be a valid string [type=string_type, input_value=123, input_type=int]
  481. '''
  482. ```
  483. You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
  484. ```py
  485. from pydantic import BaseModel, ConfigDict, ValidationError
  486. class Model(BaseModel):
  487. a: str
  488. model_config = ConfigDict(hide_input_in_errors=True)
  489. try:
  490. Model(a=123)
  491. except ValidationError as e:
  492. print(e)
  493. '''
  494. 1 validation error for Model
  495. a
  496. Input should be a valid string [type=string_type]
  497. '''
  498. ```
  499. """
  500. defer_build: bool
  501. """
  502. Whether to defer model validator and serializer construction until the first model validation.
  503. This can be useful to avoid the overhead of building models which are only
  504. used nested within other models, or when you want to manually define type namespace via
  505. [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild]. Defaults to False.
  506. """
  507. plugin_settings: dict[str, object] | None
  508. """A `dict` of settings for plugins. Defaults to `None`.
  509. See [Pydantic Plugins](../concepts/plugins.md) for details.
  510. """
  511. schema_generator: type[_GenerateSchema] | None
  512. """
  513. A custom core schema generator class to use when generating JSON schemas.
  514. Useful if you want to change the way types are validated across an entire model/schema. Defaults to `None`.
  515. The `GenerateSchema` interface is subject to change, currently only the `string_schema` method is public.
  516. See [#6737](https://github.com/pydantic/pydantic/pull/6737) for details.
  517. """
  518. json_schema_serialization_defaults_required: bool
  519. """
  520. Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
  521. This ensures that the serialization schema will reflect the fact a field with a default will always be present
  522. when serializing the model, even though it is not required for validation.
  523. However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
  524. between validation and serialization, and don't mind fields with defaults being marked as not required during
  525. serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
  526. ```py
  527. from pydantic import BaseModel, ConfigDict
  528. class Model(BaseModel):
  529. a: str = 'a'
  530. model_config = ConfigDict(json_schema_serialization_defaults_required=True)
  531. print(Model.model_json_schema(mode='validation'))
  532. '''
  533. {
  534. 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
  535. 'title': 'Model',
  536. 'type': 'object',
  537. }
  538. '''
  539. print(Model.model_json_schema(mode='serialization'))
  540. '''
  541. {
  542. 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
  543. 'required': ['a'],
  544. 'title': 'Model',
  545. 'type': 'object',
  546. }
  547. '''
  548. ```
  549. """
  550. json_schema_mode_override: Literal['validation', 'serialization', None]
  551. """
  552. If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
  553. the function call. Defaults to `None`.
  554. This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
  555. validation schema.
  556. It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
  557. and serialization that must both be referenced from the same schema; when this happens, we automatically append
  558. `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
  559. serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
  560. the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
  561. from being added to the definition references.
  562. ```py
  563. from pydantic import BaseModel, ConfigDict, Json
  564. class Model(BaseModel):
  565. a: Json[int] # requires a string to validate, but will dump an int
  566. print(Model.model_json_schema(mode='serialization'))
  567. '''
  568. {
  569. 'properties': {'a': {'title': 'A', 'type': 'integer'}},
  570. 'required': ['a'],
  571. 'title': 'Model',
  572. 'type': 'object',
  573. }
  574. '''
  575. class ForceInputModel(Model):
  576. # the following ensures that even with mode='serialization', we
  577. # will get the schema that would be generated for validation.
  578. model_config = ConfigDict(json_schema_mode_override='validation')
  579. print(ForceInputModel.model_json_schema(mode='serialization'))
  580. '''
  581. {
  582. 'properties': {
  583. 'a': {
  584. 'contentMediaType': 'application/json',
  585. 'contentSchema': {'type': 'integer'},
  586. 'title': 'A',
  587. 'type': 'string',
  588. }
  589. },
  590. 'required': ['a'],
  591. 'title': 'ForceInputModel',
  592. 'type': 'object',
  593. }
  594. '''
  595. ```
  596. """
  597. coerce_numbers_to_str: bool
  598. """
  599. If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
  600. Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
  601. ```py
  602. from decimal import Decimal
  603. from pydantic import BaseModel, ConfigDict, ValidationError
  604. class Model(BaseModel):
  605. value: str
  606. try:
  607. print(Model(value=42))
  608. except ValidationError as e:
  609. print(e)
  610. '''
  611. 1 validation error for Model
  612. value
  613. Input should be a valid string [type=string_type, input_value=42, input_type=int]
  614. '''
  615. class Model(BaseModel):
  616. model_config = ConfigDict(coerce_numbers_to_str=True)
  617. value: str
  618. repr(Model(value=42).value)
  619. #> "42"
  620. repr(Model(value=42.13).value)
  621. #> "42.13"
  622. repr(Model(value=Decimal('42.13')).value)
  623. #> "42.13"
  624. ```
  625. """
  626. regex_engine: Literal['rust-regex', 'python-re']
  627. """
  628. The regex engine to used for pattern validation
  629. Defaults to `'rust-regex'`.
  630. - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
  631. which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
  632. - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
  633. which supports all regex features, but may be slower.
  634. ```py
  635. from pydantic import BaseModel, ConfigDict, Field, ValidationError
  636. class Model(BaseModel):
  637. model_config = ConfigDict(regex_engine='python-re')
  638. value: str = Field(pattern=r'^abc(?=def)')
  639. print(Model(value='abcdef').value)
  640. #> abcdef
  641. try:
  642. print(Model(value='abxyzcdef'))
  643. except ValidationError as e:
  644. print(e)
  645. '''
  646. 1 validation error for Model
  647. value
  648. String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
  649. '''
  650. ```
  651. """
  652. validation_error_cause: bool
  653. """
  654. 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`.
  655. Note:
  656. Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
  657. Note:
  658. The structure of validation errors are likely to change in future pydantic versions. Pydantic offers no guarantees about the structure of validation errors. Should be used for visual traceback debugging only.
  659. """
  660. __getattr__ = getattr_migration(__name__)