config.py 35 KB

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