Coverage for pydantic / config.py: 100.00%

120 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

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

2 

3from __future__ import annotations as _annotations 1abcdefghijklsmnopqr

4 

5from collections.abc import Callable 1abcdefghijklsmnopqr

6from re import Pattern 1abcdefghijklsmnopqr

7from typing import TYPE_CHECKING, Any, Literal, TypeAlias, TypeVar, Union, Unpack, cast, overload 1abcdefghijklsmnopqr

8 

9from typing_extensions import TypedDict 1abcdefghijklsmnopqr

10 

11from .aliases import AliasGenerator 1abcdefghijklsmnopqr

12from .errors import PydanticUserError 1abcdefghijklsmnopqr

13 

14if TYPE_CHECKING: 1abcdefghijklsmnopqr

15 from .fields import ComputedFieldInfo, FieldInfo 

16 

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

18 

19 

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

21JsonDict: TypeAlias = dict[str, JsonValue] 1abcdefghijklsmnopqr

22 

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

24 

25JsonSchemaExtraCallable: TypeAlias = Callable[[JsonDict], None] | Callable[[JsonDict, type[Any]], None] 1abcdefghijklsmnopqr

26 

27ExtraValues = Literal['allow', 'ignore', 'forbid'] 1abcdefghijklsmnopqr

28 

29 

30class ConfigDict(TypedDict, total=False): 1abcdefghijklsmnopqr

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

32 

33 title: str | None 1abcdefghijklsmnopqr

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

35 

36 model_title_generator: Callable[[type], str] | None 1abcdefghijklsmnopqr

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

38 

39 field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None 1abcdefghijklsmnopqr

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

41 

42 str_to_lower: bool 1abcdefghijklsmnopqr

43 """Whether to convert all characters to lowercase for str types. Defaults to `False`.""" 1abcdefghijklsmnopqr

44 

45 str_to_upper: bool 1abcdefghijklsmnopqr

46 """Whether to convert all characters to uppercase for str types. Defaults to `False`.""" 1abcdefghijklsmnopqr

47 

48 str_strip_whitespace: bool 1abcdefghijklsmnopqr

49 """Whether to strip leading and trailing whitespace for str types.""" 1abcdefghijklsmnopqr

50 

51 str_min_length: int 1abcdefghijklsmnopqr

52 """The minimum length for str types. Defaults to `0`.""" 1abcdefghijklsmnopqr

53 

54 str_max_length: int | None 1abcdefghijklsmnopqr

55 """The maximum length for str types. Defaults to `None`.""" 1abcdefghijklsmnopqr

56 

57 extra: ExtraValues | None 1abcdefghijklsmnopqr

58 ''' 1abcdefghijklsmnopqr

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

60 

61 Three configuration values are available: 

62 

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

64 ```python 

65 from pydantic import BaseModel, ConfigDict 

66 

67 class User(BaseModel): 

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

69 

70 name: str 

71 

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

73 print(user) 

74 #> name='John Doe' 

75 ``` 

76 

77 1. This is the default behaviour. 

78 2. The `age` argument is ignored. 

79 

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

81 will be raised if this is the case: 

82 ```python 

83 from pydantic import BaseModel, ConfigDict, ValidationError 

84 

85 

86 class Model(BaseModel): 

87 x: int 

88 

89 model_config = ConfigDict(extra='forbid') 

90 

91 

92 try: 

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

94 except ValidationError as exc: 

95 print(exc) 

96 """ 

97 1 validation error for Model 

98 y 

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

100 """ 

101 ``` 

102 

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

104 ```python 

105 from pydantic import BaseModel, ConfigDict 

106 

107 

108 class Model(BaseModel): 

109 x: int 

110 

111 model_config = ConfigDict(extra='allow') 

112 

113 

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

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

116 ``` 

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

118 the type annotation for `__pydantic_extra__`: 

119 ```python 

120 from pydantic import BaseModel, ConfigDict, Field, ValidationError 

121 

122 

123 class Model(BaseModel): 

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

125 

126 x: int 

127 

128 model_config = ConfigDict(extra='allow') 

129 

130 

131 try: 

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

133 except ValidationError as exc: 

134 print(exc) 

135 """ 

136 1 validation error for Model 

137 y 

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

139 """ 

140 

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

142 assert m.x == 1 

143 assert m.y == 2 

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

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

146 ``` 

147 

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

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

150 

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

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

153 ```python 

154 from pydantic import BaseModel, ConfigDict, ValidationError 

155 

156 class Model(BaseModel): 

157 x: int 

158 model_config = ConfigDict(extra="allow") 

159 

160 try: 

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

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

163 except ValidationError as exc: 

164 print(exc) 

165 """ 

166 1 validation error for Model 

167 y 

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

169 """ 

170 ``` 

171 ''' 

172 

173 frozen: bool 1abcdefghijklsmnopqr

174 """ 1abcdefghijklsmnopqr

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

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

177 attributes are hashable. Defaults to `False`. 

178 """ 

179 

180 populate_by_name: bool 1abcdefghijklsmnopqr

181 """ 1abcdefghijklsmnopqr

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

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

184 

185 !!! warning 

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

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

188 

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

190 previous behavior of `populate_by_name=True`. 

191 

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

193 control for validation behavior. 

194 

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

196 

197 ```python 

198 from pydantic import BaseModel, ConfigDict, Field 

199 

200 class Model(BaseModel): 

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

202 

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

204 

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

206 print(m) 

207 #> my_field='foo' 

208 

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

210 print(m) 

211 #> my_field='foo' 

212 ``` 

213 

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

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

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

217 """ 

218 

219 use_enum_values: bool 1abcdefghijklsmnopqr

220 """ 1abcdefghijklsmnopqr

221 Whether to populate models with the [`value`][enum.Enum.value] property of enums, rather than the raw enum. 

222 This may be useful if you want to serialize the value later. Defaults to `False`. 

223 

224 !!! note 

225 If you have a field typed as an enum with a default value, the [`validate_default`][pydantic.ConfigDict.validate_default] 

226 configuration needs to be set to ensure that the `use_enum_values` flag takes effect on the default, as extracting an 

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

228 

229 ```python 

230 from enum import Enum 

231 

232 from pydantic import BaseModel, ConfigDict, Field 

233 

234 class SomeEnum(Enum): 

235 FOO = 'foo' 

236 BAR = 'bar' 

237 BAZ = 'baz' 

238 

239 class SomeModel(BaseModel): 

240 model_config = ConfigDict(use_enum_values=True) 

241 

242 some_enum: SomeEnum 

243 another_enum: SomeEnum | None = Field( 

244 default=SomeEnum.FOO, validate_default=True 

245 ) 

246 

247 model1 = SomeModel(some_enum=SomeEnum.BAR) 

248 print(model1.model_dump()) 

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

250 

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

252 print(model2.model_dump()) 

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

254 ``` 

255 """ 

256 

257 validate_assignment: bool 1abcdefghijklsmnopqr

258 """ 1abcdefghijklsmnopqr

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

260 

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

262 

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

264 

265 ```python 

266 from pydantic import BaseModel 

267 

268 class User(BaseModel): 

269 name: str 

270 

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

272 print(user) 

273 #> name='John Doe' 

274 user.name = 123 # (1)! 

275 print(user) 

276 #> name=123 

277 ``` 

278 

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

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

281 

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

283 

284 ```python 

285 from pydantic import BaseModel, ValidationError 

286 

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

288 name: str 

289 

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

291 print(user) 

292 #> name='John Doe' 

293 try: 

294 user.name = 123 # (3)! 

295 except ValidationError as e: 

296 print(e) 

297 ''' 

298 1 validation error for User 

299 name 

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

301 ''' 

302 ``` 

303 

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

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

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

307 """ 

308 

309 arbitrary_types_allowed: bool 1abcdefghijklsmnopqr

310 """ 1abcdefghijklsmnopqr

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

312 

313 ```python 

314 from pydantic import BaseModel, ConfigDict, ValidationError 

315 

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

317 class Pet: 

318 def __init__(self, name: str): 

319 self.name = name 

320 

321 class Model(BaseModel): 

322 model_config = ConfigDict(arbitrary_types_allowed=True) 

323 

324 pet: Pet 

325 owner: str 

326 

327 pet = Pet(name='Hedwig') 

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

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

330 print(model) 

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

332 print(model.pet) 

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

334 print(model.pet.name) 

335 #> Hedwig 

336 print(type(model.pet)) 

337 #> <class '__main__.Pet'> 

338 try: 

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

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

341 except ValidationError as e: 

342 print(e) 

343 ''' 

344 1 validation error for Model 

345 pet 

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

347 ''' 

348 

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

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

351 pet2 = Pet(name=42) 

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

353 print(model2) 

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

355 print(model2.pet) 

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

357 print(model2.pet.name) 

358 #> 42 

359 print(type(model2.pet)) 

360 #> <class '__main__.Pet'> 

361 ``` 

362 """ 

363 

364 from_attributes: bool 1abcdefghijklsmnopqr

365 """ 1abcdefghijklsmnopqr

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

367 """ 

368 

369 loc_by_alias: bool 1abcdefghijklsmnopqr

370 """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`.""" 1abcdefghijklsmnopqr

371 

372 alias_generator: Callable[[str], str] | AliasGenerator | None 1abcdefghijklsmnopqr

373 """ 1abcdefghijklsmnopqr

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

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

376 

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

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

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

380 

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

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

383 a basic callable: 

384 

385 ```python 

386 from pydantic import BaseModel, ConfigDict 

387 from pydantic.alias_generators import to_pascal 

388 

389 class Voice(BaseModel): 

390 model_config = ConfigDict(alias_generator=to_pascal) 

391 

392 name: str 

393 language_code: str 

394 

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

396 print(voice.language_code) 

397 #> tr-TR 

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

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

400 ``` 

401 

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

403 [`AliasGenerator`][pydantic.aliases.AliasGenerator]. 

404 

405 ```python 

406 from pydantic import AliasGenerator, BaseModel, ConfigDict 

407 from pydantic.alias_generators import to_camel, to_pascal 

408 

409 class Athlete(BaseModel): 

410 first_name: str 

411 last_name: str 

412 sport: str 

413 

414 model_config = ConfigDict( 

415 alias_generator=AliasGenerator( 

416 validation_alias=to_camel, 

417 serialization_alias=to_pascal, 

418 ) 

419 ) 

420 

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

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

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

424 ``` 

425 

426 Note: 

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

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

429 """ 

430 

431 ignored_types: tuple[type, ...] 1abcdefghijklsmnopqr

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

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

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

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

436 """ 

437 

438 allow_inf_nan: bool 1abcdefghijklsmnopqr

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

440 

441 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None 1abcdefghijklsmnopqr

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

443 

444 json_encoders: dict[type[object], JsonEncoder] | None 1abcdefghijklsmnopqr

445 """ 1abcdefghijklsmnopqr

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

447 

448 /// version-deprecated | v2 

449 This configuration option is deprecated. Use [custom serializers](../concepts/serialization.md#custom-serializers) 

450 instead. 

451 /// 

452 """ 

453 

454 # new in V2 

455 strict: bool 1abcdefghijklsmnopqr

456 """ 1abcdefghijklsmnopqr

457 Whether strict validation is applied to all fields on the model. 

458 

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

460 

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

462 does not match the field's type annotation. 

463 

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

465 

466 ```python 

467 from pydantic import BaseModel, ConfigDict 

468 

469 class Model(BaseModel): 

470 model_config = ConfigDict(strict=True) 

471 

472 name: str 

473 age: int 

474 ``` 

475 

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

477 

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

479 strict and lax modes. 

480 

481 /// version-added | v2 

482 /// 

483 """ 

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

485 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 1abcdefghijklsmnopqr

486 """ 1abcdefghijklsmnopqr

487 When and how to revalidate models and dataclasses during validation. Can be one of: 

488 

489 - `'never'`: will *not* revalidate models and dataclasses during validation 

490 - `'always'`: will revalidate models and dataclasses during validation 

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

492 subclass of the model or dataclass 

493 

494 The default is `'never'` (no revalidation). 

495 

496 This configuration only affects *the current model* it is applied on, and does *not* propagate to the models 

497 referenced in fields. 

498 

499 ```python 

500 from pydantic import BaseModel 

501 

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

503 name: str 

504 

505 class Transaction(BaseModel): 

506 user: User 

507 

508 my_user = User(name='John') 

509 t = Transaction(user=my_user) 

510 

511 my_user.name = 1 # (2)! 

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

513 print(t) 

514 #> user=User(name=1) 

515 ``` 

516 

517 1. This is the default behavior. 

518 2. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.ConfigDict.validate_assignment] in the configuration. 

519 3. Since `revalidate_instances` is set to `'never'`, the user instance is not revalidated. 

520 

521 Here is an example demonstrating the behavior of `'subclass-instances'`: 

522 

523 ```python 

524 from pydantic import BaseModel 

525 

526 class User(BaseModel, revalidate_instances='subclass-instances'): 

527 name: str 

528 

529 class SubUser(User): 

530 age: int 

531 

532 class Transaction(BaseModel): 

533 user: User 

534 

535 my_user = User(name='John') 

536 my_user.name = 1 # (1)! 

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

538 print(t) 

539 #> user=User(name=1) 

540 

541 my_sub_user = SubUser(name='John', age=20) 

542 t = Transaction(user=my_sub_user) 

543 print(t) # (3)! 

544 #> user=User(name='John') 

545 ``` 

546 

547 1. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.ConfigDict.validate_assignment] in the configuration. 

548 2. Because `my_user` is a "direct" instance of `User`, it is *not* being revalidated. It would have been the case if 

549 `revalidate_instances` was set to `'always'`. 

550 3. Because `my_sub_user` is an instance of a `User` subclass, it is being revalidated. In this case, Pydantic coerces `my_sub_user` to the defined 

551 `User` class defined on `Transaction`. If one of its fields had an invalid value, a validation error would have been raised. 

552 

553 /// version-added | v2 

554 /// 

555 """ 

556 

557 ser_json_timedelta: Literal['iso8601', 'float'] 1abcdefghijklsmnopqr

558 """ 1abcdefghijklsmnopqr

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

560 `'float'`. Defaults to `'iso8601'`. 

561 

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

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

564 

565 /// version-changed | v2.12 

566 It is now recommended to use the [`ser_json_temporal`][pydantic.config.ConfigDict.ser_json_temporal] 

567 setting. `ser_json_timedelta` will be deprecated in v3. 

568 /// 

569 """ 

570 

571 ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds'] 1abcdefghijklsmnopqr

572 """ 1abcdefghijklsmnopqr

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

574 

575 - [`datetime.datetime`][] 

576 - [`datetime.date`][] 

577 - [`datetime.time`][] 

578 - [`datetime.timedelta`][] 

579 

580 Can be one of: 

581 

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

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

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

585 

586 Defaults to `'iso8601'`. 

587 

588 /// version-added | v2.12 

589 This setting replaces [`ser_json_timedelta`][pydantic.config.ConfigDict.ser_json_timedelta], 

590 which will be deprecated in v3. `ser_json_temporal` adds more configurability for the other temporal types. 

591 It takes precedence over `ser_json_timedelta`. 

592 /// 

593 """ 

594 

595 val_temporal_unit: Literal['seconds', 'milliseconds', 'infer'] 1abcdefghijklsmnopqr

596 """ 1abcdefghijklsmnopqr

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

598 

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

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

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

602 

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

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

605 

606 Defaults to `'infer'`. 

607 

608 /// version-added | v2.12 

609 /// 

610 

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

612 """ 

613 

614 ser_json_bytes: Literal['utf8', 'base64', 'hex'] 1abcdefghijklsmnopqr

615 """ 1abcdefghijklsmnopqr

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

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

618 

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

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

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

622 """ 

623 

624 val_json_bytes: Literal['utf8', 'base64', 'hex'] 1abcdefghijklsmnopqr

625 """ 1abcdefghijklsmnopqr

626 /// version-added | v2.9 

627 /// 

628 

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

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

631 

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

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

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

635 """ 

636 

637 ser_json_inf_nan: Literal['null', 'constants', 'strings'] 1abcdefghijklsmnopqr

638 """ 1abcdefghijklsmnopqr

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

640 

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

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

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

644 """ 

645 

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

647 validate_default: bool 1abcdefghijklsmnopqr

648 """Whether to validate default values during validation. Defaults to `False`.""" 1abcdefghijklsmnopqr

649 

650 validate_return: bool 1abcdefghijklsmnopqr

651 """Whether to validate the return value from call validators. Defaults to `False`.""" 1abcdefghijklsmnopqr

652 

653 protected_namespaces: tuple[str | Pattern[str], ...] 1abcdefghijklsmnopqr

654 """ 1abcdefghijklsmnopqr

655 A tuple of strings and/or regex patterns that prevent models from having fields with names that conflict with its existing members/methods. 

656 

657 Strings are matched on a prefix basis. For instance, with `'dog'`, having a field named `'dog_name'` will be disallowed. 

658 

659 Regex patterns are matched on the entire field name. For instance, with the pattern `'^dog$'`, having a field named `'dog'` will be disallowed, 

660 but `'dog_name'` will be accepted. 

661 

662 Defaults to `('model_validate', 'model_dump')`. This default is used to prevent collisions with the existing (and possibly future) 

663 [validation](../concepts/models.md#validating-data) and [serialization](../concepts/serialization.md#serializing-data) methods. 

664 

665 ```python 

666 import warnings 

667 

668 from pydantic import BaseModel 

669 

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

671 

672 try: 

673 

674 class Model(BaseModel): 

675 model_dump_something: str 

676 

677 except UserWarning as e: 

678 print(e) 

679 ''' 

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

681 

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

683 ''' 

684 ``` 

685 

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

687 

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

689 import re 

690 import warnings 

691 

692 from pydantic import BaseModel, ConfigDict 

693 

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

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

696 

697 class Model(BaseModel): 

698 safe_field: str 

699 also_protect_field: str 

700 protect_this: str 

701 

702 model_config = ConfigDict( 

703 protected_namespaces=( 

704 'protect_me_', 

705 'also_protect_', 

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

707 ) 

708 ) 

709 

710 for warning in caught_warnings: 

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

712 ''' 

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

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

715 

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

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

718 ''' 

719 ``` 

720 

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

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

723 

724 ```python 

725 from pydantic import BaseModel, ConfigDict 

726 

727 try: 

728 

729 class Model(BaseModel): 

730 model_validate: str 

731 

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

733 

734 except ValueError as e: 

735 print(e) 

736 ''' 

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

738 ''' 

739 ``` 

740 

741 /// version-changed | v2.10 

742 The default protected namespaces was changed from `('model_',)` to `('model_validate', 'model_dump')`, to allow 

743 for fields like `model_id`, `model_name` to be used. 

744 /// 

745 """ 

746 

747 hide_input_in_errors: bool 1abcdefghijklsmnopqr

748 """ 1abcdefghijklsmnopqr

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

750 

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

752 

753 ```python 

754 from pydantic import BaseModel, ValidationError 

755 

756 class Model(BaseModel): 

757 a: str 

758 

759 try: 

760 Model(a=123) 

761 except ValidationError as e: 

762 print(e) 

763 ''' 

764 1 validation error for Model 

765 a 

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

767 ''' 

768 ``` 

769 

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

771 

772 ```python 

773 from pydantic import BaseModel, ConfigDict, ValidationError 

774 

775 class Model(BaseModel): 

776 a: str 

777 model_config = ConfigDict(hide_input_in_errors=True) 

778 

779 try: 

780 Model(a=123) 

781 except ValidationError as e: 

782 print(e) 

783 ''' 

784 1 validation error for Model 

785 a 

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

787 ''' 

788 ``` 

789 """ 

790 

791 defer_build: bool 1abcdefghijklsmnopqr

792 """ 1abcdefghijklsmnopqr

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

794 

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

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

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

798 

799 /// version-changed | v2.10 

800 The setting also applies to [Pydantic dataclasses](../concepts/dataclasses.md) and [type adapters](../concepts/type_adapter.md). 

801 /// 

802 """ 

803 

804 plugin_settings: dict[str, object] | None 1abcdefghijklsmnopqr

805 """A `dict` of settings for plugins. Defaults to `None`.""" 1abcdefghijklsmnopqr

806 

807 json_schema_serialization_defaults_required: bool 1abcdefghijklsmnopqr

808 """ 1abcdefghijklsmnopqr

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

810 

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

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

813 

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

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

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

817 

818 ```python 

819 from pydantic import BaseModel, ConfigDict 

820 

821 class Model(BaseModel): 

822 a: str = 'a' 

823 

824 model_config = ConfigDict(json_schema_serialization_defaults_required=True) 

825 

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

827 ''' 

828 { 

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

830 'title': 'Model', 

831 'type': 'object', 

832 } 

833 ''' 

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

835 ''' 

836 { 

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

838 'required': ['a'], 

839 'title': 'Model', 

840 'type': 'object', 

841 } 

842 ''' 

843 ``` 

844 

845 /// version-added | v2.4 

846 /// 

847 """ 

848 

849 json_schema_mode_override: Literal['validation', 'serialization', None] 1abcdefghijklsmnopqr

850 """ 1abcdefghijklsmnopqr

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

852 the function call. Defaults to `None`. 

853 

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

855 validation schema. 

856 

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

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

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

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

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

862 from being added to the definition references. 

863 

864 ```python 

865 from pydantic import BaseModel, ConfigDict, Json 

866 

867 class Model(BaseModel): 

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

869 

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

871 ''' 

872 { 

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

874 'required': ['a'], 

875 'title': 'Model', 

876 'type': 'object', 

877 } 

878 ''' 

879 

880 class ForceInputModel(Model): 

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

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

883 model_config = ConfigDict(json_schema_mode_override='validation') 

884 

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

886 ''' 

887 { 

888 'properties': { 

889 'a': { 

890 'contentMediaType': 'application/json', 

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

892 'title': 'A', 

893 'type': 'string', 

894 } 

895 }, 

896 'required': ['a'], 

897 'title': 'ForceInputModel', 

898 'type': 'object', 

899 } 

900 ''' 

901 ``` 

902 

903 /// version-added | v2.4 

904 /// 

905 """ 

906 

907 coerce_numbers_to_str: bool 1abcdefghijklsmnopqr

908 """ 1abcdefghijklsmnopqr

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

910 

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

912 

913 ```python 

914 from decimal import Decimal 

915 

916 from pydantic import BaseModel, ConfigDict, ValidationError 

917 

918 class Model(BaseModel): 

919 value: str 

920 

921 try: 

922 print(Model(value=42)) 

923 except ValidationError as e: 

924 print(e) 

925 ''' 

926 1 validation error for Model 

927 value 

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

929 ''' 

930 

931 class Model(BaseModel): 

932 model_config = ConfigDict(coerce_numbers_to_str=True) 

933 

934 value: str 

935 

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

937 #> "42" 

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

939 #> "42.13" 

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

941 #> "42.13" 

942 ``` 

943 """ 

944 

945 regex_engine: Literal['rust-regex', 'python-re'] 1abcdefghijklsmnopqr

946 """ 1abcdefghijklsmnopqr

947 The regex engine to be used for pattern validation. 

948 Defaults to `'rust-regex'`. 

949 

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

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

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

953 

954 !!! note 

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

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

957 

958 ```python 

959 from pydantic import BaseModel, ConfigDict, Field, ValidationError 

960 

961 class Model(BaseModel): 

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

963 

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

965 

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

967 #> abcdef 

968 

969 try: 

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

971 except ValidationError as e: 

972 print(e) 

973 ''' 

974 1 validation error for Model 

975 value 

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

977 ''' 

978 ``` 

979 

980 /// version-added | v2.5 

981 /// 

982 """ 

983 

984 validation_error_cause: bool 1abcdefghijklsmnopqr

985 """ 1abcdefghijklsmnopqr

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

987 

988 Note: 

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

990 

991 /// version-added | v2.5 

992 /// 

993 """ 

994 

995 use_attribute_docstrings: bool 1abcdefghijklsmnopqr

996 ''' 1abcdefghijklsmnopqr

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

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

999 

1000 ```python 

1001 from pydantic import BaseModel, ConfigDict, Field 

1002 

1003 

1004 class Model(BaseModel): 

1005 model_config = ConfigDict(use_attribute_docstrings=True) 

1006 

1007 x: str 

1008 """ 

1009 Example of an attribute docstring 

1010 """ 

1011 

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

1013 """ 

1014 Description in Field overrides attribute docstring 

1015 """ 

1016 

1017 

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

1019 # > Example of an attribute docstring 

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

1021 # > Description in Field 

1022 ``` 

1023 This requires the source code of the class to be available at runtime (and so won't work in the interactive interpreter shell). 

1024 

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

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

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

1028 

1029 - inheritance is being used. 

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

1031 

1032 /// version-added | v2.7 

1033 /// 

1034 ''' 

1035 

1036 cache_strings: bool | Literal['all', 'keys', 'none'] 1abcdefghijklsmnopqr

1037 """ 1abcdefghijklsmnopqr

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

1039 

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

1041 

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

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

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

1045 

1046 !!! note 

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

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

1049 

1050 !!! tip 

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

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

1053 

1054 /// version-added | v2.7 

1055 /// 

1056 """ 

1057 

1058 validate_by_alias: bool 1abcdefghijklsmnopqr

1059 """ 1abcdefghijklsmnopqr

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

1061 

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

1063 

1064 ```py 

1065 from pydantic import BaseModel, ConfigDict, Field 

1066 

1067 class Model(BaseModel): 

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

1069 

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

1071 

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

1073 print(m) 

1074 #> my_field='foo' 

1075 ``` 

1076 

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

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

1079 

1080 !!! warning 

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

1082 This would make it impossible to populate an attribute. 

1083 

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

1085 

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

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

1088 

1089 /// version-added | v2.11 

1090 This setting was introduced in conjunction with [`validate_by_name`][pydantic.ConfigDict.validate_by_name] 

1091 to empower users with more fine grained validation control. 

1092 /// 

1093 """ 

1094 

1095 validate_by_name: bool 1abcdefghijklsmnopqr

1096 """ 1abcdefghijklsmnopqr

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

1098 attribute. Defaults to `False`. 

1099 

1100 ```python 

1101 from pydantic import BaseModel, ConfigDict, Field 

1102 

1103 class Model(BaseModel): 

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

1105 

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

1107 

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

1109 print(m) 

1110 #> my_field='foo' 

1111 

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

1113 print(m) 

1114 #> my_field='foo' 

1115 ``` 

1116 

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

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

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

1120 

1121 !!! warning 

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

1123 This would make it impossible to populate an attribute. 

1124 

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

1126 

1127 /// version-added | v2.11 

1128 This setting was introduced in conjunction with [`validate_by_alias`][pydantic.ConfigDict.validate_by_alias] 

1129 to empower users with more fine grained validation control. It is an alternative to [`populate_by_name`][pydantic.ConfigDict.populate_by_name], 

1130 that enables validation by name **and** by alias. 

1131 /// 

1132 """ 

1133 

1134 serialize_by_alias: bool 1abcdefghijklsmnopqr

1135 """ 1abcdefghijklsmnopqr

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

1137 

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

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

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

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

1142 

1143 ```python 

1144 from pydantic import BaseModel, ConfigDict, Field 

1145 

1146 class Model(BaseModel): 

1147 model_config = ConfigDict(serialize_by_alias=True) 

1148 

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

1150 

1151 m = Model(my_field='foo') 

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

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

1154 ``` 

1155 

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

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

1158 

1159 

1160 /// version-added | v2.11 

1161 This setting was introduced to address the [popular request](https://github.com/pydantic/pydantic/issues/8379) 

1162 for consistency with alias behavior for validation and serialization. 

1163 

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

1165 /// 

1166 """ 

1167 

1168 url_preserve_empty_path: bool 1abcdefghijklsmnopqr

1169 """ 1abcdefghijklsmnopqr

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

1171 

1172 ```python 

1173 from pydantic import AnyUrl, BaseModel, ConfigDict 

1174 

1175 class Model(BaseModel): 

1176 model_config = ConfigDict(url_preserve_empty_path=True) 

1177 

1178 url: AnyUrl 

1179 

1180 m = Model(url='https://example.com') 

1181 print(m.url) 

1182 #> https://example.com 

1183 ``` 

1184 

1185 /// version-added | v2.12 

1186 /// 

1187 """ 

1188 

1189 polymorphic_serialization: bool 1abcdefghijklsmnopqr

1190 """ 1abcdefghijklsmnopqr

1191 Whether to use polymorphic serialization for subclasses of the model or Pydantic dataclass. Defaults to `False`. 

1192 """ 

1193 

1194 

1195_TypeT = TypeVar('_TypeT', bound=type) 1abcdefghijklsmnopqr

1196 

1197 

1198@overload 1abcdefghijklsmnopqr

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

1200 

1201 

1202@overload 1abcdefghijklsmnopqr

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

1204 

1205 

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

1207 """!!! abstract "Usage Documentation" 

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

1209 

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

1211 

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

1213 especially with `TypedDict`. 

1214 

1215 !!! example "Usage" 

1216 

1217 ```python 

1218 from typing_extensions import TypedDict 

1219 

1220 from pydantic import ConfigDict, TypeAdapter, with_config 

1221 

1222 @with_config(ConfigDict(str_to_lower=True)) 

1223 class TD(TypedDict): 

1224 x: str 

1225 

1226 ta = TypeAdapter(TD) 

1227 

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

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

1230 ``` 

1231 

1232 /// version-changed | v2.11 

1233 Keyword arguments can be provided directly instead of a config dictionary. 

1234 /// 

1235 """ 

1236 if config is not None and kwargs: 1abcdefghijklmnopqr

1237 raise ValueError('Cannot specify both `config` and keyword arguments') 1abcdefghijklmnopqr

1238 

1239 final_config = config if config is not None else cast(ConfigDict, kwargs) 1abcdefghijklmnopqr

1240 

1241 def inner(class_: _TypeT, /) -> _TypeT: 1abcdefghijklmnopqr

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

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

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

1245 from ._internal._utils import is_model_class 1abcdefghijklmnopqr

1246 

1247 if is_model_class(class_): 1abcdefghijklmnopqr

1248 raise PydanticUserError( 1abcdefghijklmnopqr

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

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

1251 ) 

1252 class_.__pydantic_config__ = final_config 1abcdefghijklmnopqr

1253 return class_ 1abcdefghijklmnopqr

1254 

1255 return inner 1abcdefghijklmnopqr