config.py 24 KB

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