config.py 43 KB

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