Coverage for pydantic/config.py: 100.00%

105 statements  

« prev     ^ index     » next       coverage.py v7.5.4, created at 2024-07-03 19:29 +0000

1"""Configuration for Pydantic models.""" 

2 

3from __future__ import annotations as _annotations 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

4 

5from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, TypeVar, Union 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

6 

7from typing_extensions import Literal, TypeAlias, TypedDict 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

8 

9from ._migration import getattr_migration 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

10from .aliases import AliasGenerator 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

11from .errors import PydanticUserError 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

12 

13if TYPE_CHECKING: 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

14 from ._internal._generate_schema import GenerateSchema as _GenerateSchema 

15 from .fields import ComputedFieldInfo, FieldInfo 

16 

17__all__ = ('ConfigDict', 'with_config') 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

18 

19 

20JsonValue: TypeAlias = Union[int, float, str, bool, None, List['JsonValue'], 'JsonDict'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

21JsonDict: TypeAlias = Dict[str, JsonValue] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

22 

23JsonEncoder = Callable[[Any], Any] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

24 

25JsonSchemaExtraCallable: TypeAlias = Union[ 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

26 Callable[[JsonDict], None], 

27 Callable[[JsonDict, Type[Any]], None], 

28] 

29 

30ExtraValues = Literal['allow', 'ignore', 'forbid'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

31 

32 

33class ConfigDict(TypedDict, total=False): 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

34 """A TypedDict for configuring Pydantic behaviour.""" 

35 

36 title: str | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

37 """The title for the generated JSON schema, defaults to the model's name""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

38 

39 model_title_generator: Callable[[type], str] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

40 """A callable that takes a model class and returns the title for it. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

41 

42 field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

43 """A callable that takes a field's name and info and returns title for it. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

44 

45 str_to_lower: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

46 """Whether to convert all characters to lowercase for str types. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

47 

48 str_to_upper: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

49 """Whether to convert all characters to uppercase for str types. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

50 

51 str_strip_whitespace: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

52 """Whether to strip leading and trailing whitespace for str types.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

53 

54 str_min_length: int 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

55 """The minimum length for str types. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

56 

57 str_max_length: int | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

58 """The maximum length for str types. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

59 

60 extra: ExtraValues | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

61 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

62 Whether to ignore, allow, or forbid extra attributes during model initialization. Defaults to `'ignore'`. 

63 

64 You can configure how pydantic handles the attributes that are not defined in the model: 

65 

66 * `allow` - Allow any extra attributes. 

67 * `forbid` - Forbid any extra attributes. 

68 * `ignore` - Ignore any extra attributes. 

69 

70 ```py 

71 from pydantic import BaseModel, ConfigDict 

72 

73 

74 class User(BaseModel): 

75 model_config = ConfigDict(extra='ignore') # (1)! 

76 

77 name: str 

78 

79 

80 user = User(name='John Doe', age=20) # (2)! 

81 print(user) 

82 #> name='John Doe' 

83 ``` 

84 

85 1. This is the default behaviour. 

86 2. The `age` argument is ignored. 

87 

88 Instead, with `extra='allow'`, the `age` argument is included: 

89 

90 ```py 

91 from pydantic import BaseModel, ConfigDict 

92 

93 

94 class User(BaseModel): 

95 model_config = ConfigDict(extra='allow') 

96 

97 name: str 

98 

99 

100 user = User(name='John Doe', age=20) # (1)! 

101 print(user) 

102 #> name='John Doe' age=20 

103 ``` 

104 

105 1. The `age` argument is included. 

106 

107 With `extra='forbid'`, an error is raised: 

108 

109 ```py 

110 from pydantic import BaseModel, ConfigDict, ValidationError 

111 

112 

113 class User(BaseModel): 

114 model_config = ConfigDict(extra='forbid') 

115 

116 name: str 

117 

118 

119 try: 

120 User(name='John Doe', age=20) 

121 except ValidationError as e: 

122 print(e) 

123 ''' 

124 1 validation error for User 

125 age 

126 Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int] 

127 ''' 

128 ``` 

129 """ 

130 

131 frozen: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

132 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

133 Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates 

134 a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the 

135 attributes are hashable. Defaults to `False`. 

136 

137 Note: 

138 On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default. 

139 """ 

140 

141 populate_by_name: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

142 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

143 Whether an aliased field may be populated by its name as given by the model 

144 attribute, as well as the alias. Defaults to `False`. 

145 

146 Note: 

147 The name of this configuration setting was changed in **v2.0** from 

148 `allow_population_by_field_name` to `populate_by_name`. 

149 

150 ```py 

151 from pydantic import BaseModel, ConfigDict, Field 

152 

153 

154 class User(BaseModel): 

155 model_config = ConfigDict(populate_by_name=True) 

156 

157 name: str = Field(alias='full_name') # (1)! 

158 age: int 

159 

160 

161 user = User(full_name='John Doe', age=20) # (2)! 

162 print(user) 

163 #> name='John Doe' age=20 

164 user = User(name='John Doe', age=20) # (3)! 

165 print(user) 

166 #> name='John Doe' age=20 

167 ``` 

168 

169 1. The field `'name'` has an alias `'full_name'`. 

170 2. The model is populated by the alias `'full_name'`. 

171 3. The model is populated by the field name `'name'`. 

172 """ 

173 

174 use_enum_values: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

175 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

176 Whether to populate models with the `value` property of enums, rather than the raw enum. 

177 This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`. 

178 

179 !!! note 

180 If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True` 

181 for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an 

182 enum's value occurs during validation, not serialization. 

183 

184 ```py 

185 from enum import Enum 

186 from typing import Optional 

187 

188 from pydantic import BaseModel, ConfigDict, Field 

189 

190 

191 class SomeEnum(Enum): 

192 FOO = 'foo' 

193 BAR = 'bar' 

194 BAZ = 'baz' 

195 

196 

197 class SomeModel(BaseModel): 

198 model_config = ConfigDict(use_enum_values=True) 

199 

200 some_enum: SomeEnum 

201 another_enum: Optional[SomeEnum] = Field(default=SomeEnum.FOO, validate_default=True) 

202 

203 

204 model1 = SomeModel(some_enum=SomeEnum.BAR) 

205 print(model1.model_dump()) 

206 # {'some_enum': 'bar', 'another_enum': 'foo'} 

207 

208 model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ) 

209 print(model2.model_dump()) 

210 #> {'some_enum': 'bar', 'another_enum': 'baz'} 

211 ``` 

212 """ 

213 

214 validate_assignment: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

215 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

216 Whether to validate the data when the model is changed. Defaults to `False`. 

217 

218 The default behavior of Pydantic is to validate the data when the model is created. 

219 

220 In case the user changes the data after the model is created, the model is _not_ revalidated. 

221 

222 ```py 

223 from pydantic import BaseModel 

224 

225 class User(BaseModel): 

226 name: str 

227 

228 user = User(name='John Doe') # (1)! 

229 print(user) 

230 #> name='John Doe' 

231 user.name = 123 # (1)! 

232 print(user) 

233 #> name=123 

234 ``` 

235 

236 1. The validation happens only when the model is created. 

237 2. The validation does not happen when the data is changed. 

238 

239 In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`: 

240 

241 ```py 

242 from pydantic import BaseModel, ValidationError 

243 

244 class User(BaseModel, validate_assignment=True): # (1)! 

245 name: str 

246 

247 user = User(name='John Doe') # (2)! 

248 print(user) 

249 #> name='John Doe' 

250 try: 

251 user.name = 123 # (3)! 

252 except ValidationError as e: 

253 print(e) 

254 ''' 

255 1 validation error for User 

256 name 

257 Input should be a valid string [type=string_type, input_value=123, input_type=int] 

258 ''' 

259 ``` 

260 

261 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`. 

262 2. The validation happens when the model is created. 

263 3. The validation _also_ happens when the data is changed. 

264 """ 

265 

266 arbitrary_types_allowed: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

267 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

268 Whether arbitrary types are allowed for field types. Defaults to `False`. 

269 

270 ```py 

271 from pydantic import BaseModel, ConfigDict, ValidationError 

272 

273 # This is not a pydantic model, it's an arbitrary class 

274 class Pet: 

275 def __init__(self, name: str): 

276 self.name = name 

277 

278 class Model(BaseModel): 

279 model_config = ConfigDict(arbitrary_types_allowed=True) 

280 

281 pet: Pet 

282 owner: str 

283 

284 pet = Pet(name='Hedwig') 

285 # A simple check of instance type is used to validate the data 

286 model = Model(owner='Harry', pet=pet) 

287 print(model) 

288 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry' 

289 print(model.pet) 

290 #> <__main__.Pet object at 0x0123456789ab> 

291 print(model.pet.name) 

292 #> Hedwig 

293 print(type(model.pet)) 

294 #> <class '__main__.Pet'> 

295 try: 

296 # If the value is not an instance of the type, it's invalid 

297 Model(owner='Harry', pet='Hedwig') 

298 except ValidationError as e: 

299 print(e) 

300 ''' 

301 1 validation error for Model 

302 pet 

303 Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str] 

304 ''' 

305 

306 # Nothing in the instance of the arbitrary type is checked 

307 # Here name probably should have been a str, but it's not validated 

308 pet2 = Pet(name=42) 

309 model2 = Model(owner='Harry', pet=pet2) 

310 print(model2) 

311 #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry' 

312 print(model2.pet) 

313 #> <__main__.Pet object at 0x0123456789ab> 

314 print(model2.pet.name) 

315 #> 42 

316 print(type(model2.pet)) 

317 #> <class '__main__.Pet'> 

318 ``` 

319 """ 

320 

321 from_attributes: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

322 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

323 Whether to build models and look up discriminators of tagged unions using python object attributes. 

324 """ 

325 

326 loc_by_alias: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

327 """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`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

328 

329 alias_generator: Callable[[str], str] | AliasGenerator | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

330 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

331 A callable that takes a field name and returns an alias for it 

332 or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`. 

333 

334 When using a callable, the alias generator is used for both validation and serialization. 

335 If you want to use different alias generators for validation and serialization, you can use 

336 [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead. 

337 

338 If data source field names do not match your code style (e. g. CamelCase fields), 

339 you can automatically generate aliases using `alias_generator`. Here's an example with 

340 a basic callable: 

341 

342 ```py 

343 from pydantic import BaseModel, ConfigDict 

344 from pydantic.alias_generators import to_pascal 

345 

346 class Voice(BaseModel): 

347 model_config = ConfigDict(alias_generator=to_pascal) 

348 

349 name: str 

350 language_code: str 

351 

352 voice = Voice(Name='Filiz', LanguageCode='tr-TR') 

353 print(voice.language_code) 

354 #> tr-TR 

355 print(voice.model_dump(by_alias=True)) 

356 #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'} 

357 ``` 

358 

359 If you want to use different alias generators for validation and serialization, you can use 

360 [`AliasGenerator`][pydantic.aliases.AliasGenerator]. 

361 

362 ```py 

363 from pydantic import AliasGenerator, BaseModel, ConfigDict 

364 from pydantic.alias_generators import to_camel, to_pascal 

365 

366 class Athlete(BaseModel): 

367 first_name: str 

368 last_name: str 

369 sport: str 

370 

371 model_config = ConfigDict( 

372 alias_generator=AliasGenerator( 

373 validation_alias=to_camel, 

374 serialization_alias=to_pascal, 

375 ) 

376 ) 

377 

378 athlete = Athlete(firstName='John', lastName='Doe', sport='track') 

379 print(athlete.model_dump(by_alias=True)) 

380 #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'} 

381 ``` 

382 

383 Note: 

384 Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal], 

385 [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake]. 

386 """ 

387 

388 ignored_types: tuple[type, ...] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

389 """A tuple of types that may occur as values of class attributes without annotations. This is 1abcdefghijklmnopqzABCDEFGrstuvwxy

390 typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a 

391 class without an annotation and has a type that is not in this tuple (or otherwise recognized by 

392 _pydantic_), an error will be raised. Defaults to `()`. 

393 """ 

394 

395 allow_inf_nan: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

396 """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float fields. Defaults to `True`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

397 

398 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

399 """A dict or callable to provide extra JSON schema properties. Defaults to `None`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

400 

401 json_encoders: dict[type[object], JsonEncoder] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

402 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

403 A `dict` of custom JSON encoders for specific types. Defaults to `None`. 

404 

405 !!! warning "Deprecated" 

406 This config option is a carryover from v1. 

407 We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now. 

408 It is still deprecated and will likely be removed in the future. 

409 """ 

410 

411 # new in V2 

412 strict: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

413 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

414 _(new in V2)_ If `True`, strict validation is applied to all fields on the model. 

415 

416 By default, Pydantic attempts to coerce values to the correct type, when possible. 

417 

418 There are situations in which you may want to disable this behavior, and instead raise an error if a value's type 

419 does not match the field's type annotation. 

420 

421 To configure strict mode for all fields on a model, you can set `strict=True` on the model. 

422 

423 ```py 

424 from pydantic import BaseModel, ConfigDict 

425 

426 class Model(BaseModel): 

427 model_config = ConfigDict(strict=True) 

428 

429 name: str 

430 age: int 

431 ``` 

432 

433 See [Strict Mode](../concepts/strict_mode.md) for more details. 

434 

435 See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both 

436 strict and lax modes. 

437 """ 

438 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never' 

439 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

440 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

441 When and how to revalidate models and dataclasses during validation. Accepts the string 

442 values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`. 

443 

444 - `'never'` will not revalidate models and dataclasses during validation 

445 - `'always'` will revalidate models and dataclasses during validation 

446 - `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a 

447 subclass of the model or dataclass 

448 

449 By default, model and dataclass instances are not revalidated during validation. 

450 

451 ```py 

452 from typing import List 

453 

454 from pydantic import BaseModel 

455 

456 class User(BaseModel, revalidate_instances='never'): # (1)! 

457 hobbies: List[str] 

458 

459 class SubUser(User): 

460 sins: List[str] 

461 

462 class Transaction(BaseModel): 

463 user: User 

464 

465 my_user = User(hobbies=['reading']) 

466 t = Transaction(user=my_user) 

467 print(t) 

468 #> user=User(hobbies=['reading']) 

469 

470 my_user.hobbies = [1] # (2)! 

471 t = Transaction(user=my_user) # (3)! 

472 print(t) 

473 #> user=User(hobbies=[1]) 

474 

475 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying']) 

476 t = Transaction(user=my_sub_user) 

477 print(t) 

478 #> user=SubUser(hobbies=['scuba diving'], sins=['lying']) 

479 ``` 

480 

481 1. `revalidate_instances` is set to `'never'` by **default. 

482 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config. 

483 3. Since `revalidate_instances` is set to `never`, this is not revalidated. 

484 

485 If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'` 

486 in the model's config. 

487 

488 ```py 

489 from typing import List 

490 

491 from pydantic import BaseModel, ValidationError 

492 

493 class User(BaseModel, revalidate_instances='always'): # (1)! 

494 hobbies: List[str] 

495 

496 class SubUser(User): 

497 sins: List[str] 

498 

499 class Transaction(BaseModel): 

500 user: User 

501 

502 my_user = User(hobbies=['reading']) 

503 t = Transaction(user=my_user) 

504 print(t) 

505 #> user=User(hobbies=['reading']) 

506 

507 my_user.hobbies = [1] 

508 try: 

509 t = Transaction(user=my_user) # (2)! 

510 except ValidationError as e: 

511 print(e) 

512 ''' 

513 1 validation error for Transaction 

514 user.hobbies.0 

515 Input should be a valid string [type=string_type, input_value=1, input_type=int] 

516 ''' 

517 

518 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying']) 

519 t = Transaction(user=my_sub_user) 

520 print(t) # (3)! 

521 #> user=User(hobbies=['scuba diving']) 

522 ``` 

523 

524 1. `revalidate_instances` is set to `'always'`. 

525 2. The model is revalidated, since `revalidate_instances` is set to `'always'`. 

526 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`. 

527 

528 It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances 

529 of subclasses of the model. 

530 

531 ```py 

532 from typing import List 

533 

534 from pydantic import BaseModel 

535 

536 class User(BaseModel, revalidate_instances='subclass-instances'): # (1)! 

537 hobbies: List[str] 

538 

539 class SubUser(User): 

540 sins: List[str] 

541 

542 class Transaction(BaseModel): 

543 user: User 

544 

545 my_user = User(hobbies=['reading']) 

546 t = Transaction(user=my_user) 

547 print(t) 

548 #> user=User(hobbies=['reading']) 

549 

550 my_user.hobbies = [1] 

551 t = Transaction(user=my_user) # (2)! 

552 print(t) 

553 #> user=User(hobbies=[1]) 

554 

555 my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying']) 

556 t = Transaction(user=my_sub_user) 

557 print(t) # (3)! 

558 #> user=User(hobbies=['scuba diving']) 

559 ``` 

560 

561 1. `revalidate_instances` is set to `'subclass-instances'`. 

562 2. This is not revalidated, since `my_user` is not a subclass of `User`. 

563 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`. 

564 """ 

565 

566 ser_json_timedelta: Literal['iso8601', 'float'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

567 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

568 The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and 

569 `'float'`. Defaults to `'iso8601'`. 

570 

571 - `'iso8601'` will serialize timedeltas to ISO 8601 durations. 

572 - `'float'` will serialize timedeltas to the total number of seconds. 

573 """ 

574 

575 ser_json_bytes: Literal['utf8', 'base64'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

576 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

577 The encoding of JSON serialized bytes. Accepts the string values of `'utf8'` and `'base64'`. 

578 Defaults to `'utf8'`. 

579 

580 - `'utf8'` will serialize bytes to UTF-8 strings. 

581 - `'base64'` will serialize bytes to URL safe base64 strings. 

582 """ 

583 

584 ser_json_inf_nan: Literal['null', 'constants', 'strings'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

585 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

586 The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`. 

587 

588 - `'null'` will serialize infinity and NaN values as `null`. 

589 - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`. 

590 - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`. 

591 """ 

592 

593 # whether to validate default values during validation, default False 

594 validate_default: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

595 """Whether to validate default values during validation. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

596 

597 validate_return: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

598 """whether to validate the return value from call validators. Defaults to `False`.""" 1abcdefghijklmnopqzABCDEFGrstuvwxy

599 

600 protected_namespaces: tuple[str, ...] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

601 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

602 A `tuple` of strings that prevent model to have field which conflict with them. 

603 Defaults to `('model_', )`). 

604 

605 Pydantic prevents collisions between model attributes and `BaseModel`'s own methods by 

606 namespacing them with the prefix `model_`. 

607 

608 ```py 

609 import warnings 

610 

611 from pydantic import BaseModel 

612 

613 warnings.filterwarnings('error') # Raise warnings as errors 

614 

615 try: 

616 

617 class Model(BaseModel): 

618 model_prefixed_field: str 

619 

620 except UserWarning as e: 

621 print(e) 

622 ''' 

623 Field "model_prefixed_field" has conflict with protected namespace "model_". 

624 

625 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`. 

626 ''' 

627 ``` 

628 

629 You can customize this behavior using the `protected_namespaces` setting: 

630 

631 ```py 

632 import warnings 

633 

634 from pydantic import BaseModel, ConfigDict 

635 

636 warnings.filterwarnings('error') # Raise warnings as errors 

637 

638 try: 

639 

640 class Model(BaseModel): 

641 model_prefixed_field: str 

642 also_protect_field: str 

643 

644 model_config = ConfigDict( 

645 protected_namespaces=('protect_me_', 'also_protect_') 

646 ) 

647 

648 except UserWarning as e: 

649 print(e) 

650 ''' 

651 Field "also_protect_field" has conflict with protected namespace "also_protect_". 

652 

653 You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_',)`. 

654 ''' 

655 ``` 

656 

657 While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision, 

658 an error _is_ raised if there is an actual collision with an existing attribute: 

659 

660 ```py 

661 from pydantic import BaseModel 

662 

663 try: 

664 

665 class Model(BaseModel): 

666 model_validate: str 

667 

668 except NameError as e: 

669 print(e) 

670 ''' 

671 Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_". 

672 ''' 

673 ``` 

674 """ 

675 

676 hide_input_in_errors: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

677 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

678 Whether to hide inputs when printing errors. Defaults to `False`. 

679 

680 Pydantic shows the input value and type when it raises `ValidationError` during the validation. 

681 

682 ```py 

683 from pydantic import BaseModel, ValidationError 

684 

685 class Model(BaseModel): 

686 a: str 

687 

688 try: 

689 Model(a=123) 

690 except ValidationError as e: 

691 print(e) 

692 ''' 

693 1 validation error for Model 

694 a 

695 Input should be a valid string [type=string_type, input_value=123, input_type=int] 

696 ''' 

697 ``` 

698 

699 You can hide the input value and type by setting the `hide_input_in_errors` config to `True`. 

700 

701 ```py 

702 from pydantic import BaseModel, ConfigDict, ValidationError 

703 

704 class Model(BaseModel): 

705 a: str 

706 model_config = ConfigDict(hide_input_in_errors=True) 

707 

708 try: 

709 Model(a=123) 

710 except ValidationError as e: 

711 print(e) 

712 ''' 

713 1 validation error for Model 

714 a 

715 Input should be a valid string [type=string_type] 

716 ''' 

717 ``` 

718 """ 

719 

720 defer_build: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

721 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

722 Whether to defer model validator and serializer construction until the first model validation. Defaults to False. 

723 

724 This can be useful to avoid the overhead of building models which are only 

725 used nested within other models, or when you want to manually define type namespace via 

726 [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild]. 

727 

728 See also [`experimental_defer_build_mode`][pydantic.config.ConfigDict.experimental_defer_build_mode]. 

729 

730 !!! note 

731 `defer_build` does not work by default with FastAPI Pydantic models. By default, the validator and serializer 

732 for said models is constructed immediately for FastAPI routes. You also need to define 

733 [`experimental_defer_build_mode=('model', 'type_adapter')`][pydantic.config.ConfigDict.experimental_defer_build_mode] with FastAPI 

734 models in order for `defer_build=True` to take effect. This additional (experimental) parameter is required for 

735 the deferred building due to FastAPI relying on `TypeAdapter`s. 

736 """ 

737 

738 experimental_defer_build_mode: tuple[Literal['model', 'type_adapter'], ...] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

739 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

740 Controls when [`defer_build`][pydantic.config.ConfigDict.defer_build] is applicable. Defaults to `('model',)`. 

741 

742 Due to backwards compatibility reasons [`TypeAdapter`][pydantic.type_adapter.TypeAdapter] does not by default 

743 respect `defer_build`. Meaning when `defer_build` is `True` and `experimental_defer_build_mode` is the default `('model',)` 

744 then `TypeAdapter` immediately constructs its validator and serializer instead of postponing said construction until 

745 the first model validation. Set this to `('model', 'type_adapter')` to make `TypeAdapter` respect the `defer_build` 

746 so it postpones validator and serializer construction until the first validation or serialization. 

747 

748 !!! note 

749 The `experimental_defer_build_mode` parameter is named with an underscore to suggest this is an experimental feature. It may 

750 be removed or changed in the future in a minor release. 

751 """ 

752 

753 plugin_settings: dict[str, object] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

754 """A `dict` of settings for plugins. Defaults to `None`. 1abcdefghijklmnopqzABCDEFGrstuvwxy

755 

756 See [Pydantic Plugins](../concepts/plugins.md) for details. 

757 """ 

758 

759 schema_generator: type[_GenerateSchema] | None 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

760 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

761 A custom core schema generator class to use when generating JSON schemas. 

762 Useful if you want to change the way types are validated across an entire model/schema. Defaults to `None`. 

763 

764 The `GenerateSchema` interface is subject to change, currently only the `string_schema` method is public. 

765 

766 See [#6737](https://github.com/pydantic/pydantic/pull/6737) for details. 

767 """ 

768 

769 json_schema_serialization_defaults_required: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

770 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

771 Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`. 

772 

773 This ensures that the serialization schema will reflect the fact a field with a default will always be present 

774 when serializing the model, even though it is not required for validation. 

775 

776 However, there are scenarios where this may be undesirable — in particular, if you want to share the schema 

777 between validation and serialization, and don't mind fields with defaults being marked as not required during 

778 serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details. 

779 

780 ```py 

781 from pydantic import BaseModel, ConfigDict 

782 

783 class Model(BaseModel): 

784 a: str = 'a' 

785 

786 model_config = ConfigDict(json_schema_serialization_defaults_required=True) 

787 

788 print(Model.model_json_schema(mode='validation')) 

789 ''' 

790 { 

791 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}}, 

792 'title': 'Model', 

793 'type': 'object', 

794 } 

795 ''' 

796 print(Model.model_json_schema(mode='serialization')) 

797 ''' 

798 { 

799 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}}, 

800 'required': ['a'], 

801 'title': 'Model', 

802 'type': 'object', 

803 } 

804 ''' 

805 ``` 

806 """ 

807 

808 json_schema_mode_override: Literal['validation', 'serialization', None] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

809 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

810 If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to 

811 the function call. Defaults to `None`. 

812 

813 This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the 

814 validation schema. 

815 

816 It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation 

817 and serialization that must both be referenced from the same schema; when this happens, we automatically append 

818 `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the 

819 serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between 

820 the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes 

821 from being added to the definition references. 

822 

823 ```py 

824 from pydantic import BaseModel, ConfigDict, Json 

825 

826 class Model(BaseModel): 

827 a: Json[int] # requires a string to validate, but will dump an int 

828 

829 print(Model.model_json_schema(mode='serialization')) 

830 ''' 

831 { 

832 'properties': {'a': {'title': 'A', 'type': 'integer'}}, 

833 'required': ['a'], 

834 'title': 'Model', 

835 'type': 'object', 

836 } 

837 ''' 

838 

839 class ForceInputModel(Model): 

840 # the following ensures that even with mode='serialization', we 

841 # will get the schema that would be generated for validation. 

842 model_config = ConfigDict(json_schema_mode_override='validation') 

843 

844 print(ForceInputModel.model_json_schema(mode='serialization')) 

845 ''' 

846 { 

847 'properties': { 

848 'a': { 

849 'contentMediaType': 'application/json', 

850 'contentSchema': {'type': 'integer'}, 

851 'title': 'A', 

852 'type': 'string', 

853 } 

854 }, 

855 'required': ['a'], 

856 'title': 'ForceInputModel', 

857 'type': 'object', 

858 } 

859 ''' 

860 ``` 

861 """ 

862 

863 coerce_numbers_to_str: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

864 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

865 If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`. 

866 

867 Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default. 

868 

869 ```py 

870 from decimal import Decimal 

871 

872 from pydantic import BaseModel, ConfigDict, ValidationError 

873 

874 class Model(BaseModel): 

875 value: str 

876 

877 try: 

878 print(Model(value=42)) 

879 except ValidationError as e: 

880 print(e) 

881 ''' 

882 1 validation error for Model 

883 value 

884 Input should be a valid string [type=string_type, input_value=42, input_type=int] 

885 ''' 

886 

887 class Model(BaseModel): 

888 model_config = ConfigDict(coerce_numbers_to_str=True) 

889 

890 value: str 

891 

892 repr(Model(value=42).value) 

893 #> "42" 

894 repr(Model(value=42.13).value) 

895 #> "42.13" 

896 repr(Model(value=Decimal('42.13')).value) 

897 #> "42.13" 

898 ``` 

899 """ 

900 

901 regex_engine: Literal['rust-regex', 'python-re'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

902 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

903 The regex engine to be used for pattern validation. 

904 Defaults to `'rust-regex'`. 

905 

906 - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate, 

907 which is non-backtracking and therefore more DDoS resistant, but does not support all regex features. 

908 - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module, 

909 which supports all regex features, but may be slower. 

910 

911 !!! note 

912 If you use a compiled regex pattern, the python-re engine will be used regardless of this setting. 

913 This is so that flags such as `re.IGNORECASE` are respected. 

914 

915 ```py 

916 from pydantic import BaseModel, ConfigDict, Field, ValidationError 

917 

918 class Model(BaseModel): 

919 model_config = ConfigDict(regex_engine='python-re') 

920 

921 value: str = Field(pattern=r'^abc(?=def)') 

922 

923 print(Model(value='abcdef').value) 

924 #> abcdef 

925 

926 try: 

927 print(Model(value='abxyzcdef')) 

928 except ValidationError as e: 

929 print(e) 

930 ''' 

931 1 validation error for Model 

932 value 

933 String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str] 

934 ''' 

935 ``` 

936 """ 

937 

938 validation_error_cause: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

939 """ 1abcdefghijklmnopqzABCDEFGrstuvwxy

940 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`. 

941 

942 Note: 

943 Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`. 

944 

945 Note: 

946 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. 

947 """ 

948 

949 use_attribute_docstrings: bool 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

950 ''' 1abcdefghijklmnopqzABCDEFGrstuvwxy

951 Whether docstrings of attributes (bare string literals immediately following the attribute declaration) 

952 should be used for field descriptions. Defaults to `False`. 

953 

954 Available in Pydantic v2.7+. 

955 

956 ```py 

957 from pydantic import BaseModel, ConfigDict, Field 

958 

959 

960 class Model(BaseModel): 

961 model_config = ConfigDict(use_attribute_docstrings=True) 

962 

963 x: str 

964 """ 

965 Example of an attribute docstring 

966 """ 

967 

968 y: int = Field(description="Description in Field") 

969 """ 

970 Description in Field overrides attribute docstring 

971 """ 

972 

973 

974 print(Model.model_fields["x"].description) 

975 # > Example of an attribute docstring 

976 print(Model.model_fields["y"].description) 

977 # > Description in Field 

978 ``` 

979 This requires the source code of the class to be available at runtime. 

980 

981 !!! warning "Usage with `TypedDict`" 

982 Due to current limitations, attribute docstrings detection may not work as expected when using `TypedDict` 

983 (in particular when multiple `TypedDict` classes have the same name in the same source file). The behavior 

984 can be different depending on the Python version used. 

985 ''' 

986 

987 cache_strings: bool | Literal['all', 'keys', 'none'] 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

988 """ 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

989 Whether to cache strings to avoid constructing new Python objects. Defaults to True. 

990 

991 Enabling this setting should significantly improve validation performance while increasing memory usage slightly. 

992 

993 - `True` or `'all'` (the default): cache all strings 

994 - `'keys'`: cache only dictionary keys 

995 - `False` or `'none'`: no caching 

996 

997 !!! note 

998 `True` or `'all'` is required to cache strings during general validation because 

999 validators don't know if they're in a key or a value. 

1000 

1001 !!! tip 

1002 If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage, 

1003 as the performance difference is minimal if repeated strings are rare. 

1004 """ 

1005 

1006 

1007_TypeT = TypeVar('_TypeT', bound=type) 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

1008 

1009 

1010def with_config(config: ConfigDict) -> Callable[[_TypeT], _TypeT]: 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy

1011 """Usage docs: https://docs.pydantic.dev/2.8/concepts/config/#configuration-with-dataclass-from-the-standard-library-or-typeddict 

1012 

1013 A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library. 

1014 

1015 Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers, 

1016 especially with `TypedDict`. 

1017 

1018 !!! example "Usage" 

1019 

1020 ```py 

1021 from typing_extensions import TypedDict 

1022 

1023 from pydantic import ConfigDict, TypeAdapter, with_config 

1024 

1025 @with_config(ConfigDict(str_to_lower=True)) 

1026 class Model(TypedDict): 

1027 x: str 

1028 

1029 ta = TypeAdapter(Model) 

1030 

1031 print(ta.validate_python({'x': 'ABC'})) 

1032 #> {'x': 'abc'} 

1033 ``` 

1034 """ 

1035 

1036 def inner(class_: _TypeT, /) -> _TypeT: 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy

1037 # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass. 

1038 # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid 

1039 # common mistakes, we at least check for `class_` to not be a Pydantic model. 

1040 from ._internal._utils import is_model_class 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy

1041 

1042 if is_model_class(class_): 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy

1043 raise PydanticUserError( 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy

1044 f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model', 

1045 code='with-config-on-model', 

1046 ) 

1047 class_.__pydantic_config__ = config 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy

1048 return class_ 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy

1049 

1050 return inner 1HIJKabcdefghLiMNOPjklmnopqQRSTrstuvwxy

1051 

1052 

1053__getattr__ = getattr_migration(__name__) 1HIJKabcdefghLiMNOPjklmnopqUVzABCDEFGQRSTrstuvwxy