Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic/config.py: 89%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

137 statements  

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

2 

3from __future__ import annotations as _annotations 

4 

5import warnings 

6from re import Pattern 

7from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, cast, overload 

8 

9from typing_extensions import TypeAlias, TypedDict, Unpack, deprecated 

10 

11from ._migration import getattr_migration 

12from .aliases import AliasGenerator 

13from .errors import PydanticUserError 

14from .warnings import PydanticDeprecatedSince211 

15 

16if TYPE_CHECKING: 

17 from ._internal._generate_schema import GenerateSchema as _GenerateSchema 

18 from .fields import ComputedFieldInfo, FieldInfo 

19 

20__all__ = ('ConfigDict', 'with_config') 

21 

22 

23JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict'] 

24JsonDict: TypeAlias = dict[str, JsonValue] 

25 

26JsonEncoder = Callable[[Any], Any] 

27 

28JsonSchemaExtraCallable: TypeAlias = Union[ 

29 Callable[[JsonDict], None], 

30 Callable[[JsonDict, type[Any]], None], 

31] 

32 

33ExtraValues = Literal['allow', 'ignore', 'forbid'] 

34 

35 

36class ConfigDict(TypedDict, total=False): 

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

38 

39 title: str | None 

40 """The title for the generated JSON schema, defaults to the model's name""" 

41 

42 model_title_generator: Callable[[type], str] | None 

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

44 

45 field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None 

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

47 

48 str_to_lower: bool 

49 """Whether to convert all characters to lowercase for str types. Defaults to `False`.""" 

50 

51 str_to_upper: bool 

52 """Whether to convert all characters to uppercase for str types. Defaults to `False`.""" 

53 

54 str_strip_whitespace: bool 

55 """Whether to strip leading and trailing whitespace for str types.""" 

56 

57 str_min_length: int 

58 """The minimum length for str types. Defaults to `None`.""" 

59 

60 str_max_length: int | None 

61 """The maximum length for str types. Defaults to `None`.""" 

62 

63 extra: ExtraValues | None 

64 ''' 

65 Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`. 

66 

67 Three configuration values are available: 

68 

69 - `'ignore'`: Providing extra data is ignored (the default): 

70 ```python 

71 from pydantic import BaseModel, ConfigDict 

72 

73 class User(BaseModel): 

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

75 

76 name: str 

77 

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

79 print(user) 

80 #> name='John Doe' 

81 ``` 

82 

83 1. This is the default behaviour. 

84 2. The `age` argument is ignored. 

85 

86 - `'forbid'`: Providing extra data is not permitted, and a [`ValidationError`][pydantic_core.ValidationError] 

87 will be raised if this is the case: 

88 ```python 

89 from pydantic import BaseModel, ConfigDict, ValidationError 

90 

91 

92 class Model(BaseModel): 

93 x: int 

94 

95 model_config = ConfigDict(extra='forbid') 

96 

97 

98 try: 

99 Model(x=1, y='a') 

100 except ValidationError as exc: 

101 print(exc) 

102 """ 

103 1 validation error for Model 

104 y 

105 Extra inputs are not permitted [type=extra_forbidden, input_value='a', input_type=str] 

106 """ 

107 ``` 

108 

109 - `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute: 

110 ```python 

111 from pydantic import BaseModel, ConfigDict 

112 

113 

114 class Model(BaseModel): 

115 x: int 

116 

117 model_config = ConfigDict(extra='allow') 

118 

119 

120 m = Model(x=1, y='a') 

121 assert m.__pydantic_extra__ == {'y': 'a'} 

122 ``` 

123 By default, no validation will be applied to these extra items, but you can set a type for the values by overriding 

124 the type annotation for `__pydantic_extra__`: 

125 ```python 

126 from pydantic import BaseModel, ConfigDict, Field, ValidationError 

127 

128 

129 class Model(BaseModel): 

130 __pydantic_extra__: dict[str, int] = Field(init=False) # (1)! 

131 

132 x: int 

133 

134 model_config = ConfigDict(extra='allow') 

135 

136 

137 try: 

138 Model(x=1, y='a') 

139 except ValidationError as exc: 

140 print(exc) 

141 """ 

142 1 validation error for Model 

143 y 

144 Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str] 

145 """ 

146 

147 m = Model(x=1, y='2') 

148 assert m.x == 1 

149 assert m.y == 2 

150 assert m.model_dump() == {'x': 1, 'y': 2} 

151 assert m.__pydantic_extra__ == {'y': 2} 

152 ``` 

153 

154 1. The `= Field(init=False)` does not have any effect at runtime, but prevents the `__pydantic_extra__` field from 

155 being included as a parameter to the model's `__init__` method by type checkers. 

156 

157 As well as specifying an `extra` configuration value on the model, you can also provide it as an argument to the validation methods. 

158 This will override any `extra` configuration value set on the model: 

159 ```python 

160 from pydantic import BaseModel, ConfigDict, ValidationError 

161 

162 class Model(BaseModel): 

163 x: int 

164 model_config = ConfigDict(extra="allow") 

165 

166 try: 

167 # Override model config and forbid extra fields just this time 

168 Model.model_validate({"x": 1, "y": 2}, extra="forbid") 

169 except ValidationError as exc: 

170 print(exc) 

171 """ 

172 1 validation error for Model 

173 y 

174 Extra inputs are not permitted [type=extra_forbidden, input_value=2, input_type=int] 

175 """ 

176 ``` 

177 ''' 

178 

179 frozen: bool 

180 """ 

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

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

183 attributes are hashable. Defaults to `False`. 

184 

185 Note: 

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

187 """ 

188 

189 populate_by_name: bool 

190 """ 

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

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

193 

194 !!! warning 

195 `populate_by_name` usage is not recommended in v2.11+ and will be deprecated in v3. 

196 Instead, you should use the [`validate_by_name`][pydantic.config.ConfigDict.validate_by_name] configuration setting. 

197 

198 When `validate_by_name=True` and `validate_by_alias=True`, this is strictly equivalent to the 

199 previous behavior of `populate_by_name=True`. 

200 

201 In v2.11, we also introduced a [`validate_by_alias`][pydantic.config.ConfigDict.validate_by_alias] setting that introduces more fine grained 

202 control for validation behavior. 

203 

204 Here's how you might go about using the new settings to achieve the same behavior: 

205 

206 ```python 

207 from pydantic import BaseModel, ConfigDict, Field 

208 

209 class Model(BaseModel): 

210 model_config = ConfigDict(validate_by_name=True, validate_by_alias=True) 

211 

212 my_field: str = Field(alias='my_alias') # (1)! 

213 

214 m = Model(my_alias='foo') # (2)! 

215 print(m) 

216 #> my_field='foo' 

217 

218 m = Model(my_field='foo') # (3)! 

219 print(m) 

220 #> my_field='foo' 

221 ``` 

222 

223 1. The field `'my_field'` has an alias `'my_alias'`. 

224 2. The model is populated by the alias `'my_alias'`. 

225 3. The model is populated by the attribute name `'my_field'`. 

226 """ 

227 

228 use_enum_values: bool 

229 """ 

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

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

232 

233 !!! note 

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

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

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

237 

238 ```python 

239 from enum import Enum 

240 from typing import Optional 

241 

242 from pydantic import BaseModel, ConfigDict, Field 

243 

244 class SomeEnum(Enum): 

245 FOO = 'foo' 

246 BAR = 'bar' 

247 BAZ = 'baz' 

248 

249 class SomeModel(BaseModel): 

250 model_config = ConfigDict(use_enum_values=True) 

251 

252 some_enum: SomeEnum 

253 another_enum: Optional[SomeEnum] = Field( 

254 default=SomeEnum.FOO, validate_default=True 

255 ) 

256 

257 model1 = SomeModel(some_enum=SomeEnum.BAR) 

258 print(model1.model_dump()) 

259 #> {'some_enum': 'bar', 'another_enum': 'foo'} 

260 

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

262 print(model2.model_dump()) 

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

264 ``` 

265 """ 

266 

267 validate_assignment: bool 

268 """ 

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

270 

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

272 

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

274 

275 ```python 

276 from pydantic import BaseModel 

277 

278 class User(BaseModel): 

279 name: str 

280 

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

282 print(user) 

283 #> name='John Doe' 

284 user.name = 123 # (1)! 

285 print(user) 

286 #> name=123 

287 ``` 

288 

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

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

291 

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

293 

294 ```python 

295 from pydantic import BaseModel, ValidationError 

296 

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

298 name: str 

299 

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

301 print(user) 

302 #> name='John Doe' 

303 try: 

304 user.name = 123 # (3)! 

305 except ValidationError as e: 

306 print(e) 

307 ''' 

308 1 validation error for User 

309 name 

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

311 ''' 

312 ``` 

313 

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

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

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

317 """ 

318 

319 arbitrary_types_allowed: bool 

320 """ 

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

322 

323 ```python 

324 from pydantic import BaseModel, ConfigDict, ValidationError 

325 

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

327 class Pet: 

328 def __init__(self, name: str): 

329 self.name = name 

330 

331 class Model(BaseModel): 

332 model_config = ConfigDict(arbitrary_types_allowed=True) 

333 

334 pet: Pet 

335 owner: str 

336 

337 pet = Pet(name='Hedwig') 

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

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

340 print(model) 

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

342 print(model.pet) 

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

344 print(model.pet.name) 

345 #> Hedwig 

346 print(type(model.pet)) 

347 #> <class '__main__.Pet'> 

348 try: 

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

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

351 except ValidationError as e: 

352 print(e) 

353 ''' 

354 1 validation error for Model 

355 pet 

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

357 ''' 

358 

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

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

361 pet2 = Pet(name=42) 

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

363 print(model2) 

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

365 print(model2.pet) 

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

367 print(model2.pet.name) 

368 #> 42 

369 print(type(model2.pet)) 

370 #> <class '__main__.Pet'> 

371 ``` 

372 """ 

373 

374 from_attributes: bool 

375 """ 

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

377 """ 

378 

379 loc_by_alias: bool 

380 """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`.""" 

381 

382 alias_generator: Callable[[str], str] | AliasGenerator | None 

383 """ 

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

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

386 

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

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

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

390 

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

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

393 a basic callable: 

394 

395 ```python 

396 from pydantic import BaseModel, ConfigDict 

397 from pydantic.alias_generators import to_pascal 

398 

399 class Voice(BaseModel): 

400 model_config = ConfigDict(alias_generator=to_pascal) 

401 

402 name: str 

403 language_code: str 

404 

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

406 print(voice.language_code) 

407 #> tr-TR 

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

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

410 ``` 

411 

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

413 [`AliasGenerator`][pydantic.aliases.AliasGenerator]. 

414 

415 ```python 

416 from pydantic import AliasGenerator, BaseModel, ConfigDict 

417 from pydantic.alias_generators import to_camel, to_pascal 

418 

419 class Athlete(BaseModel): 

420 first_name: str 

421 last_name: str 

422 sport: str 

423 

424 model_config = ConfigDict( 

425 alias_generator=AliasGenerator( 

426 validation_alias=to_camel, 

427 serialization_alias=to_pascal, 

428 ) 

429 ) 

430 

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

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

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

434 ``` 

435 

436 Note: 

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

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

439 """ 

440 

441 ignored_types: tuple[type, ...] 

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

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

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

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

446 """ 

447 

448 allow_inf_nan: bool 

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

450 

451 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None 

452 """A dict or callable to provide extra JSON schema properties. Defaults to `None`.""" 

453 

454 json_encoders: dict[type[object], JsonEncoder] | None 

455 """ 

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

457 

458 !!! warning "Deprecated" 

459 This config option is a carryover from v1. 

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

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

462 """ 

463 

464 # new in V2 

465 strict: bool 

466 """ 

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

468 

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

470 

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

472 does not match the field's type annotation. 

473 

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

475 

476 ```python 

477 from pydantic import BaseModel, ConfigDict 

478 

479 class Model(BaseModel): 

480 model_config = ConfigDict(strict=True) 

481 

482 name: str 

483 age: int 

484 ``` 

485 

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

487 

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

489 strict and lax modes. 

490 """ 

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

492 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 

493 """ 

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

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

496 

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

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

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

500 subclass of the model or dataclass 

501 

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

503 

504 ```python 

505 from pydantic import BaseModel 

506 

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

508 hobbies: list[str] 

509 

510 class SubUser(User): 

511 sins: list[str] 

512 

513 class Transaction(BaseModel): 

514 user: User 

515 

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

517 t = Transaction(user=my_user) 

518 print(t) 

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

520 

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

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

523 print(t) 

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

525 

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

527 t = Transaction(user=my_sub_user) 

528 print(t) 

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

530 ``` 

531 

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

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

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

535 

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

537 in the model's config. 

538 

539 ```python 

540 from pydantic import BaseModel, ValidationError 

541 

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

543 hobbies: list[str] 

544 

545 class SubUser(User): 

546 sins: list[str] 

547 

548 class Transaction(BaseModel): 

549 user: User 

550 

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

552 t = Transaction(user=my_user) 

553 print(t) 

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

555 

556 my_user.hobbies = [1] 

557 try: 

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

559 except ValidationError as e: 

560 print(e) 

561 ''' 

562 1 validation error for Transaction 

563 user.hobbies.0 

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

565 ''' 

566 

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

568 t = Transaction(user=my_sub_user) 

569 print(t) # (3)! 

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

571 ``` 

572 

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

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

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

576 

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

578 of subclasses of the model. 

579 

580 ```python 

581 from pydantic import BaseModel 

582 

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

584 hobbies: list[str] 

585 

586 class SubUser(User): 

587 sins: list[str] 

588 

589 class Transaction(BaseModel): 

590 user: User 

591 

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

593 t = Transaction(user=my_user) 

594 print(t) 

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

596 

597 my_user.hobbies = [1] 

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

599 print(t) 

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

601 

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

603 t = Transaction(user=my_sub_user) 

604 print(t) # (3)! 

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

606 ``` 

607 

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

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

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

611 """ 

612 

613 ser_json_timedelta: Literal['iso8601', 'float'] 

614 """ 

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

616 `'float'`. Defaults to `'iso8601'`. 

617 

618 - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations). 

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

620 

621 !!! warning 

622 Starting in v2.12, it is recommended to use the [`ser_json_temporal`][pydantic.config.ConfigDict.ser_json_temporal] 

623 setting instead of `ser_json_timedelta`. This setting will be deprecated in v3. 

624 """ 

625 

626 ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds'] 

627 """ 

628 The format of JSON serialized temporal types from the [`datetime`][] module. This includes: 

629 

630 - [`datetime.datetime`][] 

631 - [`datetime.date`][] 

632 - [`datetime.time`][] 

633 - [`datetime.timedelta`][] 

634 

635 Can be one of: 

636 

637 - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations). 

638 - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch. 

639 - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch. 

640 

641 Defaults to `'iso8601'`. 

642 

643 !!! note 

644 This setting was introduced in v2.12. It overlaps with the [`ser_json_timedelta`][pydantic.config.ConfigDict.ser_json_timedelta] 

645 setting which will be deprecated in v3. It also adds more configurability for 

646 the other temporal types. 

647 """ 

648 

649 val_temporal_unit: Literal['seconds', 'milliseconds', 'infer'] 

650 """ 

651 The unit to assume for validating numeric input for datetime-like types ([`datetime.datetime`][] and [`datetime.date`][]). Can be one of: 

652 

653 - `'seconds'` will validate date or time numeric inputs as seconds since the [epoch]. 

654 - `'milliseconds'` will validate date or time numeric inputs as milliseconds since the [epoch]. 

655 - `'infer'` will infer the unit from the string numeric input on unix time as: 

656 

657 * seconds since the [epoch] if $-2^{10} <= v <= 2^{10}$ 

658 * milliseconds since the [epoch] (if $v < -2^{10}$ or $v > 2^{10}$). 

659 

660 Defaults to `'infer'`. 

661 

662 [epoch]: https://en.wikipedia.org/wiki/Unix_time 

663 """ 

664 

665 ser_json_bytes: Literal['utf8', 'base64', 'hex'] 

666 """ 

667 The encoding of JSON serialized bytes. Defaults to `'utf8'`. 

668 Set equal to `val_json_bytes` to get back an equal value after serialization round trip. 

669 

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

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

672 - `'hex'` will serialize bytes to hexadecimal strings. 

673 """ 

674 

675 val_json_bytes: Literal['utf8', 'base64', 'hex'] 

676 """ 

677 The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`. 

678 Set equal to `ser_json_bytes` to get back an equal value after serialization round trip. 

679 

680 - `'utf8'` will deserialize UTF-8 strings to bytes. 

681 - `'base64'` will deserialize URL safe base64 strings to bytes. 

682 - `'hex'` will deserialize hexadecimal strings to bytes. 

683 """ 

684 

685 ser_json_inf_nan: Literal['null', 'constants', 'strings'] 

686 """ 

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

688 

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

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

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

692 """ 

693 

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

695 validate_default: bool 

696 """Whether to validate default values during validation. Defaults to `False`.""" 

697 

698 validate_return: bool 

699 """Whether to validate the return value from call validators. Defaults to `False`.""" 

700 

701 protected_namespaces: tuple[str | Pattern[str], ...] 

702 """ 

703 A `tuple` of strings and/or patterns that prevent models from having fields with names that conflict with them. 

704 For strings, we match on a prefix basis. Ex, if 'dog' is in the protected namespace, 'dog_name' will be protected. 

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

706 Defaults to `('model_validate', 'model_dump',)`. 

707 

708 The reason we've selected these is to prevent collisions with other validation / dumping formats 

709 in the future - ex, `model_validate_{some_newly_supported_format}`. 

710 

711 Before v2.10, Pydantic used `('model_',)` as the default value for this setting to 

712 prevent collisions between model attributes and `BaseModel`'s own methods. This was changed 

713 in v2.10 given feedback that this restriction was limiting in AI and data science contexts, 

714 where it is common to have fields with names like `model_id`, `model_input`, `model_output`, etc. 

715 

716 For more details, see https://github.com/pydantic/pydantic/issues/10315. 

717 

718 ```python 

719 import warnings 

720 

721 from pydantic import BaseModel 

722 

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

724 

725 try: 

726 

727 class Model(BaseModel): 

728 model_dump_something: str 

729 

730 except UserWarning as e: 

731 print(e) 

732 ''' 

733 Field 'model_dump_something' in 'Model' conflicts with protected namespace 'model_dump'. 

734 

735 You may be able to solve this by setting the 'protected_namespaces' configuration to ('model_validate',). 

736 ''' 

737 ``` 

738 

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

740 

741 ```python {test="skip"} 

742 import re 

743 import warnings 

744 

745 from pydantic import BaseModel, ConfigDict 

746 

747 with warnings.catch_warnings(record=True) as caught_warnings: 

748 warnings.simplefilter('always') # Catch all warnings 

749 

750 class Model(BaseModel): 

751 safe_field: str 

752 also_protect_field: str 

753 protect_this: str 

754 

755 model_config = ConfigDict( 

756 protected_namespaces=( 

757 'protect_me_', 

758 'also_protect_', 

759 re.compile('^protect_this$'), 

760 ) 

761 ) 

762 

763 for warning in caught_warnings: 

764 print(f'{warning.message}') 

765 ''' 

766 Field 'also_protect_field' in 'Model' conflicts with protected namespace 'also_protect_'. 

767 You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', re.compile('^protect_this$'))`. 

768 

769 Field 'protect_this' in 'Model' conflicts with protected namespace 're.compile('^protect_this$')'. 

770 You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', 'also_protect_')`. 

771 ''' 

772 ``` 

773 

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

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

776 

777 ```python 

778 from pydantic import BaseModel, ConfigDict 

779 

780 try: 

781 

782 class Model(BaseModel): 

783 model_validate: str 

784 

785 model_config = ConfigDict(protected_namespaces=('model_',)) 

786 

787 except ValueError as e: 

788 print(e) 

789 ''' 

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

791 ''' 

792 ``` 

793 """ 

794 

795 hide_input_in_errors: bool 

796 """ 

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

798 

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

800 

801 ```python 

802 from pydantic import BaseModel, ValidationError 

803 

804 class Model(BaseModel): 

805 a: str 

806 

807 try: 

808 Model(a=123) 

809 except ValidationError as e: 

810 print(e) 

811 ''' 

812 1 validation error for Model 

813 a 

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

815 ''' 

816 ``` 

817 

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

819 

820 ```python 

821 from pydantic import BaseModel, ConfigDict, ValidationError 

822 

823 class Model(BaseModel): 

824 a: str 

825 model_config = ConfigDict(hide_input_in_errors=True) 

826 

827 try: 

828 Model(a=123) 

829 except ValidationError as e: 

830 print(e) 

831 ''' 

832 1 validation error for Model 

833 a 

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

835 ''' 

836 ``` 

837 """ 

838 

839 defer_build: bool 

840 """ 

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

842 

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

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

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

846 

847 Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances. 

848 """ 

849 

850 plugin_settings: dict[str, object] | None 

851 """A `dict` of settings for plugins. Defaults to `None`.""" 

852 

853 schema_generator: type[_GenerateSchema] | None 

854 """ 

855 !!! warning 

856 `schema_generator` is deprecated in v2.10. 

857 

858 Prior to v2.10, this setting was advertised as highly subject to change. 

859 It's possible that this interface may once again become public once the internal core schema generation 

860 API is more stable, but that will likely come after significant performance improvements have been made. 

861 """ 

862 

863 json_schema_serialization_defaults_required: bool 

864 """ 

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

866 

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

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

869 

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

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

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

873 

874 ```python 

875 from pydantic import BaseModel, ConfigDict 

876 

877 class Model(BaseModel): 

878 a: str = 'a' 

879 

880 model_config = ConfigDict(json_schema_serialization_defaults_required=True) 

881 

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

883 ''' 

884 { 

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

886 'title': 'Model', 

887 'type': 'object', 

888 } 

889 ''' 

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

891 ''' 

892 { 

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

894 'required': ['a'], 

895 'title': 'Model', 

896 'type': 'object', 

897 } 

898 ''' 

899 ``` 

900 """ 

901 

902 json_schema_mode_override: Literal['validation', 'serialization', None] 

903 """ 

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

905 the function call. Defaults to `None`. 

906 

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

908 validation schema. 

909 

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

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

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

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

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

915 from being added to the definition references. 

916 

917 ```python 

918 from pydantic import BaseModel, ConfigDict, Json 

919 

920 class Model(BaseModel): 

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

922 

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

924 ''' 

925 { 

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

927 'required': ['a'], 

928 'title': 'Model', 

929 'type': 'object', 

930 } 

931 ''' 

932 

933 class ForceInputModel(Model): 

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

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

936 model_config = ConfigDict(json_schema_mode_override='validation') 

937 

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

939 ''' 

940 { 

941 'properties': { 

942 'a': { 

943 'contentMediaType': 'application/json', 

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

945 'title': 'A', 

946 'type': 'string', 

947 } 

948 }, 

949 'required': ['a'], 

950 'title': 'ForceInputModel', 

951 'type': 'object', 

952 } 

953 ''' 

954 ``` 

955 """ 

956 

957 coerce_numbers_to_str: bool 

958 """ 

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

960 

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

962 

963 ```python 

964 from decimal import Decimal 

965 

966 from pydantic import BaseModel, ConfigDict, ValidationError 

967 

968 class Model(BaseModel): 

969 value: str 

970 

971 try: 

972 print(Model(value=42)) 

973 except ValidationError as e: 

974 print(e) 

975 ''' 

976 1 validation error for Model 

977 value 

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

979 ''' 

980 

981 class Model(BaseModel): 

982 model_config = ConfigDict(coerce_numbers_to_str=True) 

983 

984 value: str 

985 

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

987 #> "42" 

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

989 #> "42.13" 

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

991 #> "42.13" 

992 ``` 

993 """ 

994 

995 regex_engine: Literal['rust-regex', 'python-re'] 

996 """ 

997 The regex engine to be used for pattern validation. 

998 Defaults to `'rust-regex'`. 

999 

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

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

1002 - `'python-re'` use the [`re`][] module, which supports all regex features, but may be slower. 

1003 

1004 !!! note 

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

1006 This is so that flags such as [`re.IGNORECASE`][] are respected. 

1007 

1008 ```python 

1009 from pydantic import BaseModel, ConfigDict, Field, ValidationError 

1010 

1011 class Model(BaseModel): 

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

1013 

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

1015 

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

1017 #> abcdef 

1018 

1019 try: 

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

1021 except ValidationError as e: 

1022 print(e) 

1023 ''' 

1024 1 validation error for Model 

1025 value 

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

1027 ''' 

1028 ``` 

1029 """ 

1030 

1031 validation_error_cause: bool 

1032 """ 

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

1034 

1035 Note: 

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

1037 

1038 Note: 

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

1040 """ 

1041 

1042 use_attribute_docstrings: bool 

1043 ''' 

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

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

1046 

1047 Available in Pydantic v2.7+. 

1048 

1049 ```python 

1050 from pydantic import BaseModel, ConfigDict, Field 

1051 

1052 

1053 class Model(BaseModel): 

1054 model_config = ConfigDict(use_attribute_docstrings=True) 

1055 

1056 x: str 

1057 """ 

1058 Example of an attribute docstring 

1059 """ 

1060 

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

1062 """ 

1063 Description in Field overrides attribute docstring 

1064 """ 

1065 

1066 

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

1068 # > Example of an attribute docstring 

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

1070 # > Description in Field 

1071 ``` 

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

1073 

1074 !!! warning "Usage with `TypedDict` and stdlib dataclasses" 

1075 Due to current limitations, attribute docstrings detection may not work as expected when using 

1076 [`TypedDict`][typing.TypedDict] and stdlib dataclasses, in particular when: 

1077 

1078 - inheritance is being used. 

1079 - multiple classes have the same name in the same source file (unless Python 3.13 or greater is used). 

1080 ''' 

1081 

1082 cache_strings: bool | Literal['all', 'keys', 'none'] 

1083 """ 

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

1085 

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

1087 

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

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

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

1091 

1092 !!! note 

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

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

1095 

1096 !!! tip 

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

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

1099 """ 

1100 

1101 validate_by_alias: bool 

1102 """ 

1103 Whether an aliased field may be populated by its alias. Defaults to `True`. 

1104 

1105 !!! note 

1106 In v2.11, `validate_by_alias` was introduced in conjunction with [`validate_by_name`][pydantic.ConfigDict.validate_by_name] 

1107 to empower users with more fine grained validation control. In <v2.11, disabling validation by alias was not possible. 

1108 

1109 Here's an example of disabling validation by alias: 

1110 

1111 ```py 

1112 from pydantic import BaseModel, ConfigDict, Field 

1113 

1114 class Model(BaseModel): 

1115 model_config = ConfigDict(validate_by_name=True, validate_by_alias=False) 

1116 

1117 my_field: str = Field(validation_alias='my_alias') # (1)! 

1118 

1119 m = Model(my_field='foo') # (2)! 

1120 print(m) 

1121 #> my_field='foo' 

1122 ``` 

1123 

1124 1. The field `'my_field'` has an alias `'my_alias'`. 

1125 2. The model can only be populated by the attribute name `'my_field'`. 

1126 

1127 !!! warning 

1128 You cannot set both `validate_by_alias` and `validate_by_name` to `False`. 

1129 This would make it impossible to populate an attribute. 

1130 

1131 See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example. 

1132 

1133 If you set `validate_by_alias` to `False`, under the hood, Pydantic dynamically sets 

1134 `validate_by_name` to `True` to ensure that validation can still occur. 

1135 """ 

1136 

1137 validate_by_name: bool 

1138 """ 

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

1140 attribute. Defaults to `False`. 

1141 

1142 !!! note 

1143 In v2.0-v2.10, the `populate_by_name` configuration setting was used to specify 

1144 whether or not a field could be populated by its name **and** alias. 

1145 

1146 In v2.11, `validate_by_name` was introduced in conjunction with [`validate_by_alias`][pydantic.ConfigDict.validate_by_alias] 

1147 to empower users with more fine grained validation behavior control. 

1148 

1149 ```python 

1150 from pydantic import BaseModel, ConfigDict, Field 

1151 

1152 class Model(BaseModel): 

1153 model_config = ConfigDict(validate_by_name=True, validate_by_alias=True) 

1154 

1155 my_field: str = Field(validation_alias='my_alias') # (1)! 

1156 

1157 m = Model(my_alias='foo') # (2)! 

1158 print(m) 

1159 #> my_field='foo' 

1160 

1161 m = Model(my_field='foo') # (3)! 

1162 print(m) 

1163 #> my_field='foo' 

1164 ``` 

1165 

1166 1. The field `'my_field'` has an alias `'my_alias'`. 

1167 2. The model is populated by the alias `'my_alias'`. 

1168 3. The model is populated by the attribute name `'my_field'`. 

1169 

1170 !!! warning 

1171 You cannot set both `validate_by_alias` and `validate_by_name` to `False`. 

1172 This would make it impossible to populate an attribute. 

1173 

1174 See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example. 

1175 """ 

1176 

1177 serialize_by_alias: bool 

1178 """ 

1179 Whether an aliased field should be serialized by its alias. Defaults to `False`. 

1180 

1181 Note: In v2.11, `serialize_by_alias` was introduced to address the 

1182 [popular request](https://github.com/pydantic/pydantic/issues/8379) 

1183 for consistency with alias behavior for validation and serialization settings. 

1184 In v3, the default value is expected to change to `True` for consistency with the validation default. 

1185 

1186 ```python 

1187 from pydantic import BaseModel, ConfigDict, Field 

1188 

1189 class Model(BaseModel): 

1190 model_config = ConfigDict(serialize_by_alias=True) 

1191 

1192 my_field: str = Field(serialization_alias='my_alias') # (1)! 

1193 

1194 m = Model(my_field='foo') 

1195 print(m.model_dump()) # (2)! 

1196 #> {'my_alias': 'foo'} 

1197 ``` 

1198 

1199 1. The field `'my_field'` has an alias `'my_alias'`. 

1200 2. The model is serialized using the alias `'my_alias'` for the `'my_field'` attribute. 

1201 """ 

1202 

1203 url_preserve_empty_path: bool 

1204 """ 

1205 Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`. 

1206 

1207 ```python 

1208 from pydantic import AnyUrl, BaseModel, ConfigDict 

1209 

1210 class Model(BaseModel): 

1211 model_config = ConfigDict(url_preserve_empty_path=True) 

1212 

1213 url: AnyUrl 

1214 

1215 m = Model(url='http://example.com') 

1216 print(m.url) 

1217 #> http://example.com 

1218 ``` 

1219 """ 

1220 

1221 

1222_TypeT = TypeVar('_TypeT', bound=type) 

1223 

1224 

1225@overload 

1226@deprecated('Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead.') 

1227def with_config(*, config: ConfigDict) -> Callable[[_TypeT], _TypeT]: ... 

1228 

1229 

1230@overload 

1231def with_config(config: ConfigDict, /) -> Callable[[_TypeT], _TypeT]: ... 

1232 

1233 

1234@overload 

1235def with_config(**config: Unpack[ConfigDict]) -> Callable[[_TypeT], _TypeT]: ... 

1236 

1237 

1238def with_config(config: ConfigDict | None = None, /, **kwargs: Any) -> Callable[[_TypeT], _TypeT]: 

1239 """!!! abstract "Usage Documentation" 

1240 [Configuration with other types](../concepts/config.md#configuration-on-other-supported-types) 

1241 

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

1243 

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

1245 especially with `TypedDict`. 

1246 

1247 !!! example "Usage" 

1248 

1249 ```python 

1250 from typing_extensions import TypedDict 

1251 

1252 from pydantic import ConfigDict, TypeAdapter, with_config 

1253 

1254 @with_config(ConfigDict(str_to_lower=True)) 

1255 class TD(TypedDict): 

1256 x: str 

1257 

1258 ta = TypeAdapter(TD) 

1259 

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

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

1262 ``` 

1263 """ 

1264 if config is not None and kwargs: 

1265 raise ValueError('Cannot specify both `config` and keyword arguments') 

1266 

1267 if len(kwargs) == 1 and (kwargs_conf := kwargs.get('config')) is not None: 

1268 warnings.warn( 

1269 'Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead', 

1270 category=PydanticDeprecatedSince211, 

1271 stacklevel=2, 

1272 ) 

1273 final_config = cast(ConfigDict, kwargs_conf) 

1274 else: 

1275 final_config = config if config is not None else cast(ConfigDict, kwargs) 

1276 

1277 def inner(class_: _TypeT, /) -> _TypeT: 

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

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

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

1281 from ._internal._utils import is_model_class 

1282 

1283 if is_model_class(class_): 

1284 raise PydanticUserError( 

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

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

1287 ) 

1288 class_.__pydantic_config__ = final_config 

1289 return class_ 

1290 

1291 return inner 

1292 

1293 

1294__getattr__ = getattr_migration(__name__)