Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic_core/core_schema.py: 88%

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

944 statements  

1""" 

2This module contains definitions to build schemas which `pydantic_core` can 

3validate and serialize. 

4""" 

5 

6from __future__ import annotations as _annotations 

7 

8import sys 

9import warnings 

10from collections.abc import Generator, Hashable, Mapping 

11from datetime import date, datetime, time, timedelta 

12from decimal import Decimal 

13from re import Pattern 

14from typing import TYPE_CHECKING, Any, Callable, Literal, Union 

15 

16from typing_extensions import TypeVar, deprecated 

17 

18if sys.version_info < (3, 12): 

19 from typing_extensions import TypedDict 

20else: 

21 from typing import TypedDict 

22 

23if sys.version_info < (3, 11): 

24 from typing_extensions import Protocol, Required, TypeAlias 

25else: 

26 from typing import Protocol, Required, TypeAlias 

27 

28if TYPE_CHECKING: 

29 from pydantic_core import PydanticUndefined 

30else: 

31 # The initial build of pydantic_core requires PydanticUndefined to generate 

32 # the core schema; so we need to conditionally skip it. mypy doesn't like 

33 # this at all, hence the TYPE_CHECKING branch above. 

34 try: 

35 from pydantic_core import PydanticUndefined 

36 except ImportError: 

37 PydanticUndefined = object() 

38 

39 

40ExtraBehavior = Literal['allow', 'forbid', 'ignore'] 

41 

42 

43class CoreConfig(TypedDict, total=False): 

44 """ 

45 Base class for schema configuration options. 

46 

47 Attributes: 

48 title: The name of the configuration. 

49 strict: Whether the configuration should strictly adhere to specified rules. 

50 extra_fields_behavior: The behavior for handling extra fields. 

51 typed_dict_total: Whether the TypedDict should be considered total. Default is `True`. 

52 from_attributes: Whether to use attributes for models, dataclasses, and tagged union keys. 

53 loc_by_alias: Whether to use the used alias (or first alias for "field required" errors) instead of 

54 `field_names` to construct error `loc`s. Default is `True`. 

55 revalidate_instances: Whether instances of models and dataclasses should re-validate. Default is 'never'. 

56 validate_default: Whether to validate default values during validation. Default is `False`. 

57 str_max_length: The maximum length for string fields. 

58 str_min_length: The minimum length for string fields. 

59 str_strip_whitespace: Whether to strip whitespace from string fields. 

60 str_to_lower: Whether to convert string fields to lowercase. 

61 str_to_upper: Whether to convert string fields to uppercase. 

62 allow_inf_nan: Whether to allow infinity and NaN values for float fields. Default is `True`. 

63 ser_json_timedelta: The serialization option for `timedelta` values. Default is 'iso8601'. 

64 Note that if ser_json_temporal is set, then this param will be ignored. 

65 ser_json_temporal: The serialization option for datetime like values. Default is 'iso8601'. 

66 The types this covers are datetime, date, time and timedelta. 

67 If this is set, it will take precedence over ser_json_timedelta 

68 ser_json_bytes: The serialization option for `bytes` values. Default is 'utf8'. 

69 ser_json_inf_nan: The serialization option for infinity and NaN values 

70 in float fields. Default is 'null'. 

71 val_json_bytes: The validation option for `bytes` values, complementing ser_json_bytes. Default is 'utf8'. 

72 hide_input_in_errors: Whether to hide input data from `ValidationError` representation. 

73 validation_error_cause: Whether to add user-python excs to the __cause__ of a ValidationError. 

74 Requires exceptiongroup backport pre Python 3.11. 

75 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). 

76 regex_engine: The regex engine to use for regex pattern validation. Default is 'rust-regex'. See `StringSchema`. 

77 cache_strings: Whether to cache strings. Default is `True`, `True` or `'all'` is required to cache strings 

78 during general validation since validators don't know if they're in a key or a value. 

79 validate_by_alias: Whether to use the field's alias when validating against the provided input data. Default is `True`. 

80 validate_by_name: Whether to use the field's name when validating against the provided input data. Default is `False`. Replacement for `populate_by_name`. 

81 serialize_by_alias: Whether to serialize by alias. Default is `False`, expected to change to `True` in V3. 

82 polymorphic_serialization: Whether to enable polymorphic serialization for models and dataclasses. Default is `False`. 

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

84 """ 

85 

86 title: str 

87 strict: bool 

88 # settings related to typed dicts, model fields, dataclass fields 

89 extra_fields_behavior: ExtraBehavior 

90 typed_dict_total: bool # default: True 

91 # used for models, dataclasses, and tagged union keys 

92 from_attributes: bool 

93 # whether to use the used alias (or first alias for "field required" errors) instead of field_names 

94 # to construct error `loc`s, default True 

95 loc_by_alias: bool 

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

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

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

99 validate_default: bool 

100 # used on typed-dicts and arguments 

101 # fields related to string fields only 

102 str_max_length: int 

103 str_min_length: int 

104 str_strip_whitespace: bool 

105 str_to_lower: bool 

106 str_to_upper: bool 

107 # fields related to float fields only 

108 allow_inf_nan: bool # default: True 

109 # the config options are used to customise serialization to JSON 

110 ser_json_timedelta: Literal['iso8601', 'float'] # default: 'iso8601' 

111 ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds'] # default: 'iso8601' 

112 ser_json_bytes: Literal['utf8', 'base64', 'hex'] # default: 'utf8' 

113 ser_json_inf_nan: Literal['null', 'constants', 'strings'] # default: 'null' 

114 val_json_bytes: Literal['utf8', 'base64', 'hex'] # default: 'utf8' 

115 # used to hide input data from ValidationError repr 

116 hide_input_in_errors: bool 

117 validation_error_cause: bool # default: False 

118 coerce_numbers_to_str: bool # default: False 

119 regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex' 

120 cache_strings: Union[bool, Literal['all', 'keys', 'none']] # default: 'True' 

121 validate_by_alias: bool # default: True 

122 validate_by_name: bool # default: False 

123 serialize_by_alias: bool # default: False 

124 polymorphic_serialization: bool # default: False 

125 url_preserve_empty_path: bool # default: False 

126 

127 

128IncExCall: TypeAlias = 'set[int | str] | dict[int | str, IncExCall] | None' 

129 

130ContextT = TypeVar('ContextT', covariant=True, default='Any | None') 

131 

132 

133class SerializationInfo(Protocol[ContextT]): 

134 """Extra data used during serialization.""" 

135 

136 @property 

137 def include(self) -> IncExCall: 

138 """The `include` argument set during serialization.""" 

139 ... 

140 

141 @property 

142 def exclude(self) -> IncExCall: 

143 """The `exclude` argument set during serialization.""" 

144 ... 

145 

146 @property 

147 def context(self) -> ContextT: 

148 """The current serialization context.""" 

149 ... 

150 

151 @property 

152 def mode(self) -> Literal['python', 'json'] | str: 

153 """The serialization mode set during serialization.""" 

154 ... 

155 

156 @property 

157 def by_alias(self) -> bool: 

158 """The `by_alias` argument set during serialization.""" 

159 ... 

160 

161 @property 

162 def exclude_unset(self) -> bool: 

163 """The `exclude_unset` argument set during serialization.""" 

164 ... 

165 

166 @property 

167 def exclude_defaults(self) -> bool: 

168 """The `exclude_defaults` argument set during serialization.""" 

169 ... 

170 

171 @property 

172 def exclude_none(self) -> bool: 

173 """The `exclude_none` argument set during serialization.""" 

174 ... 

175 

176 @property 

177 def exclude_computed_fields(self) -> bool: 

178 """The `exclude_computed_fields` argument set during serialization.""" 

179 ... 

180 

181 @property 

182 def serialize_as_any(self) -> bool: 

183 """The `serialize_as_any` argument set during serialization.""" 

184 ... 

185 

186 @property 

187 def polymorphic_serialization(self) -> bool | None: 

188 """The `polymorphic_serialization` argument set during serialization, if any.""" 

189 ... 

190 

191 @property 

192 def round_trip(self) -> bool: 

193 """The `round_trip` argument set during serialization.""" 

194 ... 

195 

196 def mode_is_json(self) -> bool: ... 

197 

198 def __str__(self) -> str: ... 

199 

200 def __repr__(self) -> str: ... 

201 

202 

203class FieldSerializationInfo(SerializationInfo[ContextT], Protocol): 

204 """Extra data used during field serialization.""" 

205 

206 @property 

207 def field_name(self) -> str: 

208 """The name of the current field being serialized.""" 

209 ... 

210 

211 

212class ValidationInfo(Protocol[ContextT]): 

213 """Extra data used during validation.""" 

214 

215 @property 

216 def context(self) -> ContextT: 

217 """The current validation context.""" 

218 ... 

219 

220 @property 

221 def config(self) -> CoreConfig | None: 

222 """The CoreConfig that applies to this validation.""" 

223 ... 

224 

225 @property 

226 def mode(self) -> Literal['python', 'json']: 

227 """The type of input data we are currently validating.""" 

228 ... 

229 

230 @property 

231 def data(self) -> dict[str, Any]: 

232 """The data being validated for this model.""" 

233 ... 

234 

235 @property 

236 def field_name(self) -> str | None: 

237 """ 

238 The name of the current field being validated if this validator is 

239 attached to a model field. 

240 """ 

241 ... 

242 

243 

244ExpectedSerializationTypes = Literal[ 

245 'none', 

246 'int', 

247 'bool', 

248 'float', 

249 'str', 

250 'bytes', 

251 'bytearray', 

252 'list', 

253 'tuple', 

254 'set', 

255 'frozenset', 

256 'generator', 

257 'dict', 

258 'datetime', 

259 'date', 

260 'time', 

261 'timedelta', 

262 'url', 

263 'multi-host-url', 

264 'json', 

265 'uuid', 

266 'any', 

267] 

268 

269 

270class SimpleSerSchema(TypedDict, total=False): 

271 type: Required[ExpectedSerializationTypes] 

272 

273 

274def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema: 

275 """ 

276 Returns a schema for serialization with a custom type. 

277 

278 Args: 

279 type: The type to use for serialization 

280 """ 

281 return SimpleSerSchema(type=type) 

282 

283 

284# (input_value: Any, /) -> Any 

285GeneralPlainNoInfoSerializerFunction = Callable[[Any], Any] 

286# (input_value: Any, info: FieldSerializationInfo, /) -> Any 

287GeneralPlainInfoSerializerFunction = Callable[[Any, SerializationInfo[Any]], Any] 

288# (model: Any, input_value: Any, /) -> Any 

289FieldPlainNoInfoSerializerFunction = Callable[[Any, Any], Any] 

290# (model: Any, input_value: Any, info: FieldSerializationInfo, /) -> Any 

291FieldPlainInfoSerializerFunction = Callable[[Any, Any, FieldSerializationInfo[Any]], Any] 

292SerializerFunction = Union[ 

293 GeneralPlainNoInfoSerializerFunction, 

294 GeneralPlainInfoSerializerFunction, 

295 FieldPlainNoInfoSerializerFunction, 

296 FieldPlainInfoSerializerFunction, 

297] 

298 

299WhenUsed = Literal['always', 'unless-none', 'json', 'json-unless-none'] 

300""" 

301Values have the following meanings: 

302 

303* `'always'` means always use 

304* `'unless-none'` means use unless the value is `None` 

305* `'json'` means use when serializing to JSON 

306* `'json-unless-none'` means use when serializing to JSON and the value is not `None` 

307""" 

308 

309 

310class PlainSerializerFunctionSerSchema(TypedDict, total=False): 

311 type: Required[Literal['function-plain']] 

312 function: Required[SerializerFunction] 

313 is_field_serializer: bool # default False 

314 info_arg: bool # default False 

315 return_schema: CoreSchema # if omitted, AnySchema is used 

316 when_used: WhenUsed # default: 'always' 

317 

318 

319def plain_serializer_function_ser_schema( 

320 function: SerializerFunction, 

321 *, 

322 is_field_serializer: bool | None = None, 

323 info_arg: bool | None = None, 

324 return_schema: CoreSchema | None = None, 

325 when_used: WhenUsed = 'always', 

326) -> PlainSerializerFunctionSerSchema: 

327 """ 

328 Returns a schema for serialization with a function, can be either a "general" or "field" function. 

329 

330 Args: 

331 function: The function to use for serialization 

332 is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument, 

333 and `info` includes `field_name` 

334 info_arg: Whether the function takes an `info` argument 

335 return_schema: Schema to use for serializing return value 

336 when_used: When the function should be called 

337 """ 

338 if when_used == 'always': 

339 # just to avoid extra elements in schema, and to use the actual default defined in rust 

340 when_used = None # type: ignore 

341 return _dict_not_none( 

342 type='function-plain', 

343 function=function, 

344 is_field_serializer=is_field_serializer, 

345 info_arg=info_arg, 

346 return_schema=return_schema, 

347 when_used=when_used, 

348 ) 

349 

350 

351class SerializerFunctionWrapHandler(Protocol): # pragma: no cover 

352 def __call__(self, input_value: Any, index_key: int | str | None = None, /) -> Any: ... 

353 

354 

355# (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any 

356GeneralWrapNoInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler], Any] 

357# (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any 

358GeneralWrapInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo[Any]], Any] 

359# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any 

360FieldWrapNoInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler], Any] 

361# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, info: FieldSerializationInfo, /) -> Any 

362FieldWrapInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo[Any]], Any] 

363WrapSerializerFunction = Union[ 

364 GeneralWrapNoInfoSerializerFunction, 

365 GeneralWrapInfoSerializerFunction, 

366 FieldWrapNoInfoSerializerFunction, 

367 FieldWrapInfoSerializerFunction, 

368] 

369 

370 

371class WrapSerializerFunctionSerSchema(TypedDict, total=False): 

372 type: Required[Literal['function-wrap']] 

373 function: Required[WrapSerializerFunction] 

374 is_field_serializer: bool # default False 

375 info_arg: bool # default False 

376 schema: CoreSchema # if omitted, the schema on which this serializer is defined is used 

377 return_schema: CoreSchema # if omitted, AnySchema is used 

378 when_used: WhenUsed # default: 'always' 

379 

380 

381def wrap_serializer_function_ser_schema( 

382 function: WrapSerializerFunction, 

383 *, 

384 is_field_serializer: bool | None = None, 

385 info_arg: bool | None = None, 

386 schema: CoreSchema | None = None, 

387 return_schema: CoreSchema | None = None, 

388 when_used: WhenUsed = 'always', 

389) -> WrapSerializerFunctionSerSchema: 

390 """ 

391 Returns a schema for serialization with a wrap function, can be either a "general" or "field" function. 

392 

393 Args: 

394 function: The function to use for serialization 

395 is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument, 

396 and `info` includes `field_name` 

397 info_arg: Whether the function takes an `info` argument 

398 schema: The schema to use for the inner serialization 

399 return_schema: Schema to use for serializing return value 

400 when_used: When the function should be called 

401 """ 

402 if when_used == 'always': 

403 # just to avoid extra elements in schema, and to use the actual default defined in rust 

404 when_used = None # type: ignore 

405 return _dict_not_none( 

406 type='function-wrap', 

407 function=function, 

408 is_field_serializer=is_field_serializer, 

409 info_arg=info_arg, 

410 schema=schema, 

411 return_schema=return_schema, 

412 when_used=when_used, 

413 ) 

414 

415 

416class FormatSerSchema(TypedDict, total=False): 

417 type: Required[Literal['format']] 

418 formatting_string: Required[str] 

419 when_used: WhenUsed # default: 'json-unless-none' 

420 

421 

422def format_ser_schema(formatting_string: str, *, when_used: WhenUsed = 'json-unless-none') -> FormatSerSchema: 

423 """ 

424 Returns a schema for serialization using python's `format` method. 

425 

426 Args: 

427 formatting_string: String defining the format to use 

428 when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default 

429 """ 

430 if when_used == 'json-unless-none': 

431 # just to avoid extra elements in schema, and to use the actual default defined in rust 

432 when_used = None # type: ignore 

433 return _dict_not_none(type='format', formatting_string=formatting_string, when_used=when_used) 

434 

435 

436class ToStringSerSchema(TypedDict, total=False): 

437 type: Required[Literal['to-string']] 

438 when_used: WhenUsed # default: 'json-unless-none' 

439 

440 

441def to_string_ser_schema(*, when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema: 

442 """ 

443 Returns a schema for serialization using python's `str()` / `__str__` method. 

444 

445 Args: 

446 when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default 

447 """ 

448 s = dict(type='to-string') 

449 if when_used != 'json-unless-none': 

450 # just to avoid extra elements in schema, and to use the actual default defined in rust 

451 s['when_used'] = when_used 

452 return s # type: ignore 

453 

454 

455class ModelSerSchema(TypedDict, total=False): 

456 type: Required[Literal['model']] 

457 cls: Required[type[Any]] 

458 schema: Required[CoreSchema] 

459 

460 

461def model_ser_schema(cls: type[Any], schema: CoreSchema) -> ModelSerSchema: 

462 """ 

463 Returns a schema for serialization using a model. 

464 

465 Args: 

466 cls: The expected class type, used to generate warnings if the wrong type is passed 

467 schema: Internal schema to use to serialize the model dict 

468 """ 

469 return ModelSerSchema(type='model', cls=cls, schema=schema) 

470 

471 

472SerSchema = Union[ 

473 SimpleSerSchema, 

474 PlainSerializerFunctionSerSchema, 

475 WrapSerializerFunctionSerSchema, 

476 FormatSerSchema, 

477 ToStringSerSchema, 

478 ModelSerSchema, 

479] 

480 

481 

482class InvalidSchema(TypedDict, total=False): 

483 type: Required[Literal['invalid']] 

484 ref: str 

485 metadata: dict[str, Any] 

486 # note, we never plan to use this, but include it for type checking purposes to match 

487 # all other CoreSchema union members 

488 serialization: SerSchema 

489 

490 

491def invalid_schema(ref: str | None = None, metadata: dict[str, Any] | None = None) -> InvalidSchema: 

492 """ 

493 Returns an invalid schema, used to indicate that a schema is invalid. 

494 

495 Args: 

496 ref: optional unique identifier of the schema, used to reference the schema in other places 

497 metadata: Any other information you want to include with the schema, not used by pydantic-core 

498 """ 

499 

500 return _dict_not_none(type='invalid', ref=ref, metadata=metadata) 

501 

502 

503class ComputedField(TypedDict, total=False): 

504 type: Required[Literal['computed-field']] 

505 property_name: Required[str] 

506 return_schema: Required[CoreSchema] 

507 alias: str 

508 serialization_exclude_if: Callable[[Any], bool] 

509 metadata: dict[str, Any] 

510 

511 

512def computed_field( 

513 property_name: str, 

514 return_schema: CoreSchema, 

515 *, 

516 alias: str | None = None, 

517 serialization_exclude_if: Callable[[Any], bool] | None = None, 

518 metadata: dict[str, Any] | None = None, 

519) -> ComputedField: 

520 """ 

521 ComputedFields are properties of a model or dataclass that are included in serialization. 

522 

523 Args: 

524 property_name: The name of the property on the model or dataclass 

525 return_schema: The schema used for the type returned by the computed field 

526 alias: The name to use in the serialized output 

527 metadata: Any other information you want to include with the schema, not used by pydantic-core 

528 """ 

529 return _dict_not_none( 

530 type='computed-field', 

531 property_name=property_name, 

532 return_schema=return_schema, 

533 alias=alias, 

534 serialization_exclude_if=serialization_exclude_if, 

535 metadata=metadata, 

536 ) 

537 

538 

539class AnySchema(TypedDict, total=False): 

540 type: Required[Literal['any']] 

541 ref: str 

542 metadata: dict[str, Any] 

543 serialization: SerSchema 

544 

545 

546def any_schema( 

547 *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None 

548) -> AnySchema: 

549 """ 

550 Returns a schema that matches any value, e.g.: 

551 

552 ```py 

553 from pydantic_core import SchemaValidator, core_schema 

554 

555 schema = core_schema.any_schema() 

556 v = SchemaValidator(schema) 

557 assert v.validate_python(1) == 1 

558 ``` 

559 

560 Args: 

561 ref: optional unique identifier of the schema, used to reference the schema in other places 

562 metadata: Any other information you want to include with the schema, not used by pydantic-core 

563 serialization: Custom serialization schema 

564 """ 

565 return _dict_not_none(type='any', ref=ref, metadata=metadata, serialization=serialization) 

566 

567 

568class NoneSchema(TypedDict, total=False): 

569 type: Required[Literal['none']] 

570 ref: str 

571 metadata: dict[str, Any] 

572 serialization: SerSchema 

573 

574 

575def none_schema( 

576 *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None 

577) -> NoneSchema: 

578 """ 

579 Returns a schema that matches a None value, e.g.: 

580 

581 ```py 

582 from pydantic_core import SchemaValidator, core_schema 

583 

584 schema = core_schema.none_schema() 

585 v = SchemaValidator(schema) 

586 assert v.validate_python(None) is None 

587 ``` 

588 

589 Args: 

590 ref: optional unique identifier of the schema, used to reference the schema in other places 

591 metadata: Any other information you want to include with the schema, not used by pydantic-core 

592 serialization: Custom serialization schema 

593 """ 

594 return _dict_not_none(type='none', ref=ref, metadata=metadata, serialization=serialization) 

595 

596 

597class BoolSchema(TypedDict, total=False): 

598 type: Required[Literal['bool']] 

599 strict: bool 

600 ref: str 

601 metadata: dict[str, Any] 

602 serialization: SerSchema 

603 

604 

605def bool_schema( 

606 strict: bool | None = None, 

607 ref: str | None = None, 

608 metadata: dict[str, Any] | None = None, 

609 serialization: SerSchema | None = None, 

610) -> BoolSchema: 

611 """ 

612 Returns a schema that matches a bool value, e.g.: 

613 

614 ```py 

615 from pydantic_core import SchemaValidator, core_schema 

616 

617 schema = core_schema.bool_schema() 

618 v = SchemaValidator(schema) 

619 assert v.validate_python('True') is True 

620 ``` 

621 

622 Args: 

623 strict: Whether the value should be a bool or a value that can be converted to a bool 

624 ref: optional unique identifier of the schema, used to reference the schema in other places 

625 metadata: Any other information you want to include with the schema, not used by pydantic-core 

626 serialization: Custom serialization schema 

627 """ 

628 return _dict_not_none(type='bool', strict=strict, ref=ref, metadata=metadata, serialization=serialization) 

629 

630 

631class IntSchema(TypedDict, total=False): 

632 type: Required[Literal['int']] 

633 multiple_of: int 

634 le: int 

635 ge: int 

636 lt: int 

637 gt: int 

638 strict: bool 

639 ref: str 

640 metadata: dict[str, Any] 

641 serialization: SerSchema 

642 

643 

644def int_schema( 

645 *, 

646 multiple_of: int | None = None, 

647 le: int | None = None, 

648 ge: int | None = None, 

649 lt: int | None = None, 

650 gt: int | None = None, 

651 strict: bool | None = None, 

652 ref: str | None = None, 

653 metadata: dict[str, Any] | None = None, 

654 serialization: SerSchema | None = None, 

655) -> IntSchema: 

656 """ 

657 Returns a schema that matches a int value, e.g.: 

658 

659 ```py 

660 from pydantic_core import SchemaValidator, core_schema 

661 

662 schema = core_schema.int_schema(multiple_of=2, le=6, ge=2) 

663 v = SchemaValidator(schema) 

664 assert v.validate_python('4') == 4 

665 ``` 

666 

667 Args: 

668 multiple_of: The value must be a multiple of this number 

669 le: The value must be less than or equal to this number 

670 ge: The value must be greater than or equal to this number 

671 lt: The value must be strictly less than this number 

672 gt: The value must be strictly greater than this number 

673 strict: Whether the value should be a int or a value that can be converted to a int 

674 ref: optional unique identifier of the schema, used to reference the schema in other places 

675 metadata: Any other information you want to include with the schema, not used by pydantic-core 

676 serialization: Custom serialization schema 

677 """ 

678 return _dict_not_none( 

679 type='int', 

680 multiple_of=multiple_of, 

681 le=le, 

682 ge=ge, 

683 lt=lt, 

684 gt=gt, 

685 strict=strict, 

686 ref=ref, 

687 metadata=metadata, 

688 serialization=serialization, 

689 ) 

690 

691 

692class FloatSchema(TypedDict, total=False): 

693 type: Required[Literal['float']] 

694 allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: True 

695 multiple_of: float 

696 le: float 

697 ge: float 

698 lt: float 

699 gt: float 

700 strict: bool 

701 ref: str 

702 metadata: dict[str, Any] 

703 serialization: SerSchema 

704 

705 

706def float_schema( 

707 *, 

708 allow_inf_nan: bool | None = None, 

709 multiple_of: float | None = None, 

710 le: float | None = None, 

711 ge: float | None = None, 

712 lt: float | None = None, 

713 gt: float | None = None, 

714 strict: bool | None = None, 

715 ref: str | None = None, 

716 metadata: dict[str, Any] | None = None, 

717 serialization: SerSchema | None = None, 

718) -> FloatSchema: 

719 """ 

720 Returns a schema that matches a float value, e.g.: 

721 

722 ```py 

723 from pydantic_core import SchemaValidator, core_schema 

724 

725 schema = core_schema.float_schema(le=0.8, ge=0.2) 

726 v = SchemaValidator(schema) 

727 assert v.validate_python('0.5') == 0.5 

728 ``` 

729 

730 Args: 

731 allow_inf_nan: Whether to allow inf and nan values 

732 multiple_of: The value must be a multiple of this number 

733 le: The value must be less than or equal to this number 

734 ge: The value must be greater than or equal to this number 

735 lt: The value must be strictly less than this number 

736 gt: The value must be strictly greater than this number 

737 strict: Whether the value should be a float or a value that can be converted to a float 

738 ref: optional unique identifier of the schema, used to reference the schema in other places 

739 metadata: Any other information you want to include with the schema, not used by pydantic-core 

740 serialization: Custom serialization schema 

741 """ 

742 return _dict_not_none( 

743 type='float', 

744 allow_inf_nan=allow_inf_nan, 

745 multiple_of=multiple_of, 

746 le=le, 

747 ge=ge, 

748 lt=lt, 

749 gt=gt, 

750 strict=strict, 

751 ref=ref, 

752 metadata=metadata, 

753 serialization=serialization, 

754 ) 

755 

756 

757class DecimalSchema(TypedDict, total=False): 

758 type: Required[Literal['decimal']] 

759 allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: False 

760 multiple_of: Decimal 

761 le: Decimal 

762 ge: Decimal 

763 lt: Decimal 

764 gt: Decimal 

765 max_digits: int 

766 decimal_places: int 

767 strict: bool 

768 ref: str 

769 metadata: dict[str, Any] 

770 serialization: SerSchema 

771 

772 

773def decimal_schema( 

774 *, 

775 allow_inf_nan: bool | None = None, 

776 multiple_of: Decimal | None = None, 

777 le: Decimal | None = None, 

778 ge: Decimal | None = None, 

779 lt: Decimal | None = None, 

780 gt: Decimal | None = None, 

781 max_digits: int | None = None, 

782 decimal_places: int | None = None, 

783 strict: bool | None = None, 

784 ref: str | None = None, 

785 metadata: dict[str, Any] | None = None, 

786 serialization: SerSchema | None = None, 

787) -> DecimalSchema: 

788 """ 

789 Returns a schema that matches a decimal value, e.g.: 

790 

791 ```py 

792 from decimal import Decimal 

793 from pydantic_core import SchemaValidator, core_schema 

794 

795 schema = core_schema.decimal_schema(le=0.8, ge=0.2) 

796 v = SchemaValidator(schema) 

797 assert v.validate_python('0.5') == Decimal('0.5') 

798 ``` 

799 

800 Args: 

801 allow_inf_nan: Whether to allow inf and nan values 

802 multiple_of: The value must be a multiple of this number 

803 le: The value must be less than or equal to this number 

804 ge: The value must be greater than or equal to this number 

805 lt: The value must be strictly less than this number 

806 gt: The value must be strictly greater than this number 

807 max_digits: The maximum number of decimal digits allowed 

808 decimal_places: The maximum number of decimal places allowed 

809 strict: Whether the value should be a float or a value that can be converted to a float 

810 ref: optional unique identifier of the schema, used to reference the schema in other places 

811 metadata: Any other information you want to include with the schema, not used by pydantic-core 

812 serialization: Custom serialization schema 

813 """ 

814 return _dict_not_none( 

815 type='decimal', 

816 gt=gt, 

817 ge=ge, 

818 lt=lt, 

819 le=le, 

820 max_digits=max_digits, 

821 decimal_places=decimal_places, 

822 multiple_of=multiple_of, 

823 allow_inf_nan=allow_inf_nan, 

824 strict=strict, 

825 ref=ref, 

826 metadata=metadata, 

827 serialization=serialization, 

828 ) 

829 

830 

831class ComplexSchema(TypedDict, total=False): 

832 type: Required[Literal['complex']] 

833 strict: bool 

834 ref: str 

835 metadata: dict[str, Any] 

836 serialization: SerSchema 

837 

838 

839def complex_schema( 

840 *, 

841 strict: bool | None = None, 

842 ref: str | None = None, 

843 metadata: dict[str, Any] | None = None, 

844 serialization: SerSchema | None = None, 

845) -> ComplexSchema: 

846 """ 

847 Returns a schema that matches a complex value, e.g.: 

848 

849 ```py 

850 from pydantic_core import SchemaValidator, core_schema 

851 

852 schema = core_schema.complex_schema() 

853 v = SchemaValidator(schema) 

854 assert v.validate_python('1+2j') == complex(1, 2) 

855 assert v.validate_python(complex(1, 2)) == complex(1, 2) 

856 ``` 

857 

858 Args: 

859 strict: Whether the value should be a complex object instance or a value that can be converted to a complex object 

860 ref: optional unique identifier of the schema, used to reference the schema in other places 

861 metadata: Any other information you want to include with the schema, not used by pydantic-core 

862 serialization: Custom serialization schema 

863 """ 

864 return _dict_not_none( 

865 type='complex', 

866 strict=strict, 

867 ref=ref, 

868 metadata=metadata, 

869 serialization=serialization, 

870 ) 

871 

872 

873class StringSchema(TypedDict, total=False): 

874 type: Required[Literal['str']] 

875 pattern: Union[str, Pattern[str]] 

876 max_length: int 

877 min_length: int 

878 strip_whitespace: bool 

879 to_lower: bool 

880 to_upper: bool 

881 regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex' 

882 strict: bool 

883 coerce_numbers_to_str: bool 

884 ref: str 

885 metadata: dict[str, Any] 

886 serialization: SerSchema 

887 

888 

889def str_schema( 

890 *, 

891 pattern: str | Pattern[str] | None = None, 

892 max_length: int | None = None, 

893 min_length: int | None = None, 

894 strip_whitespace: bool | None = None, 

895 to_lower: bool | None = None, 

896 to_upper: bool | None = None, 

897 regex_engine: Literal['rust-regex', 'python-re'] | None = None, 

898 strict: bool | None = None, 

899 coerce_numbers_to_str: bool | None = None, 

900 ref: str | None = None, 

901 metadata: dict[str, Any] | None = None, 

902 serialization: SerSchema | None = None, 

903) -> StringSchema: 

904 """ 

905 Returns a schema that matches a string value, e.g.: 

906 

907 ```py 

908 from pydantic_core import SchemaValidator, core_schema 

909 

910 schema = core_schema.str_schema(max_length=10, min_length=2) 

911 v = SchemaValidator(schema) 

912 assert v.validate_python('hello') == 'hello' 

913 ``` 

914 

915 Args: 

916 pattern: A regex pattern that the value must match 

917 max_length: The value must be at most this length 

918 min_length: The value must be at least this length 

919 strip_whitespace: Whether to strip whitespace from the value 

920 to_lower: Whether to convert the value to lowercase 

921 to_upper: Whether to convert the value to uppercase 

922 regex_engine: The regex engine to use for pattern validation. Default is 'rust-regex'. 

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

924 crate, which is non-backtracking and therefore more DDoS 

925 resistant, but does not support all regex features. 

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

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

928 strict: Whether the value should be a string or a value that can be converted to a string 

929 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). 

930 ref: optional unique identifier of the schema, used to reference the schema in other places 

931 metadata: Any other information you want to include with the schema, not used by pydantic-core 

932 serialization: Custom serialization schema 

933 """ 

934 return _dict_not_none( 

935 type='str', 

936 pattern=pattern, 

937 max_length=max_length, 

938 min_length=min_length, 

939 strip_whitespace=strip_whitespace, 

940 to_lower=to_lower, 

941 to_upper=to_upper, 

942 regex_engine=regex_engine, 

943 strict=strict, 

944 coerce_numbers_to_str=coerce_numbers_to_str, 

945 ref=ref, 

946 metadata=metadata, 

947 serialization=serialization, 

948 ) 

949 

950 

951class BytesSchema(TypedDict, total=False): 

952 type: Required[Literal['bytes']] 

953 max_length: int 

954 min_length: int 

955 strict: bool 

956 ref: str 

957 metadata: dict[str, Any] 

958 serialization: SerSchema 

959 

960 

961def bytes_schema( 

962 *, 

963 max_length: int | None = None, 

964 min_length: int | None = None, 

965 strict: bool | None = None, 

966 ref: str | None = None, 

967 metadata: dict[str, Any] | None = None, 

968 serialization: SerSchema | None = None, 

969) -> BytesSchema: 

970 """ 

971 Returns a schema that matches a bytes value, e.g.: 

972 

973 ```py 

974 from pydantic_core import SchemaValidator, core_schema 

975 

976 schema = core_schema.bytes_schema(max_length=10, min_length=2) 

977 v = SchemaValidator(schema) 

978 assert v.validate_python(b'hello') == b'hello' 

979 ``` 

980 

981 Args: 

982 max_length: The value must be at most this length 

983 min_length: The value must be at least this length 

984 strict: Whether the value should be a bytes or a value that can be converted to a bytes 

985 ref: optional unique identifier of the schema, used to reference the schema in other places 

986 metadata: Any other information you want to include with the schema, not used by pydantic-core 

987 serialization: Custom serialization schema 

988 """ 

989 return _dict_not_none( 

990 type='bytes', 

991 max_length=max_length, 

992 min_length=min_length, 

993 strict=strict, 

994 ref=ref, 

995 metadata=metadata, 

996 serialization=serialization, 

997 ) 

998 

999 

1000class DateSchema(TypedDict, total=False): 

1001 type: Required[Literal['date']] 

1002 strict: bool 

1003 le: date 

1004 ge: date 

1005 lt: date 

1006 gt: date 

1007 now_op: Literal['past', 'future'] 

1008 # defaults to current local utc offset from `time.localtime().tm_gmtoff` 

1009 # value is restricted to -86_400 < offset < 86_400: 

1010 now_utc_offset: int 

1011 ref: str 

1012 metadata: dict[str, Any] 

1013 serialization: SerSchema 

1014 

1015 

1016def date_schema( 

1017 *, 

1018 strict: bool | None = None, 

1019 le: date | None = None, 

1020 ge: date | None = None, 

1021 lt: date | None = None, 

1022 gt: date | None = None, 

1023 now_op: Literal['past', 'future'] | None = None, 

1024 now_utc_offset: int | None = None, 

1025 ref: str | None = None, 

1026 metadata: dict[str, Any] | None = None, 

1027 serialization: SerSchema | None = None, 

1028) -> DateSchema: 

1029 """ 

1030 Returns a schema that matches a date value, e.g.: 

1031 

1032 ```py 

1033 from datetime import date 

1034 from pydantic_core import SchemaValidator, core_schema 

1035 

1036 schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1)) 

1037 v = SchemaValidator(schema) 

1038 assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1) 

1039 ``` 

1040 

1041 Args: 

1042 strict: Whether the value should be a date or a value that can be converted to a date 

1043 le: The value must be less than or equal to this date 

1044 ge: The value must be greater than or equal to this date 

1045 lt: The value must be strictly less than this date 

1046 gt: The value must be strictly greater than this date 

1047 now_op: The value must be in the past or future relative to the current date 

1048 now_utc_offset: The value must be in the past or future relative to the current date with this utc offset 

1049 ref: optional unique identifier of the schema, used to reference the schema in other places 

1050 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1051 serialization: Custom serialization schema 

1052 """ 

1053 return _dict_not_none( 

1054 type='date', 

1055 strict=strict, 

1056 le=le, 

1057 ge=ge, 

1058 lt=lt, 

1059 gt=gt, 

1060 now_op=now_op, 

1061 now_utc_offset=now_utc_offset, 

1062 ref=ref, 

1063 metadata=metadata, 

1064 serialization=serialization, 

1065 ) 

1066 

1067 

1068class TimeSchema(TypedDict, total=False): 

1069 type: Required[Literal['time']] 

1070 strict: bool 

1071 le: time 

1072 ge: time 

1073 lt: time 

1074 gt: time 

1075 tz_constraint: Union[Literal['aware', 'naive'], int] 

1076 microseconds_precision: Literal['truncate', 'error'] 

1077 ref: str 

1078 metadata: dict[str, Any] 

1079 serialization: SerSchema 

1080 

1081 

1082def time_schema( 

1083 *, 

1084 strict: bool | None = None, 

1085 le: time | None = None, 

1086 ge: time | None = None, 

1087 lt: time | None = None, 

1088 gt: time | None = None, 

1089 tz_constraint: Literal['aware', 'naive'] | int | None = None, 

1090 microseconds_precision: Literal['truncate', 'error'] = 'truncate', 

1091 ref: str | None = None, 

1092 metadata: dict[str, Any] | None = None, 

1093 serialization: SerSchema | None = None, 

1094) -> TimeSchema: 

1095 """ 

1096 Returns a schema that matches a time value, e.g.: 

1097 

1098 ```py 

1099 from datetime import time 

1100 from pydantic_core import SchemaValidator, core_schema 

1101 

1102 schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0)) 

1103 v = SchemaValidator(schema) 

1104 assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0) 

1105 ``` 

1106 

1107 Args: 

1108 strict: Whether the value should be a time or a value that can be converted to a time 

1109 le: The value must be less than or equal to this time 

1110 ge: The value must be greater than or equal to this time 

1111 lt: The value must be strictly less than this time 

1112 gt: The value must be strictly greater than this time 

1113 tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset 

1114 microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large 

1115 ref: optional unique identifier of the schema, used to reference the schema in other places 

1116 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1117 serialization: Custom serialization schema 

1118 """ 

1119 return _dict_not_none( 

1120 type='time', 

1121 strict=strict, 

1122 le=le, 

1123 ge=ge, 

1124 lt=lt, 

1125 gt=gt, 

1126 tz_constraint=tz_constraint, 

1127 microseconds_precision=microseconds_precision, 

1128 ref=ref, 

1129 metadata=metadata, 

1130 serialization=serialization, 

1131 ) 

1132 

1133 

1134class DatetimeSchema(TypedDict, total=False): 

1135 type: Required[Literal['datetime']] 

1136 strict: bool 

1137 le: datetime 

1138 ge: datetime 

1139 lt: datetime 

1140 gt: datetime 

1141 now_op: Literal['past', 'future'] 

1142 tz_constraint: Union[Literal['aware', 'naive'], int] 

1143 # defaults to current local utc offset from `time.localtime().tm_gmtoff` 

1144 # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py 

1145 now_utc_offset: int 

1146 microseconds_precision: Literal['truncate', 'error'] # default: 'truncate' 

1147 ref: str 

1148 metadata: dict[str, Any] 

1149 serialization: SerSchema 

1150 

1151 

1152def datetime_schema( 

1153 *, 

1154 strict: bool | None = None, 

1155 le: datetime | None = None, 

1156 ge: datetime | None = None, 

1157 lt: datetime | None = None, 

1158 gt: datetime | None = None, 

1159 now_op: Literal['past', 'future'] | None = None, 

1160 tz_constraint: Literal['aware', 'naive'] | int | None = None, 

1161 now_utc_offset: int | None = None, 

1162 microseconds_precision: Literal['truncate', 'error'] = 'truncate', 

1163 ref: str | None = None, 

1164 metadata: dict[str, Any] | None = None, 

1165 serialization: SerSchema | None = None, 

1166) -> DatetimeSchema: 

1167 """ 

1168 Returns a schema that matches a datetime value, e.g.: 

1169 

1170 ```py 

1171 from datetime import datetime 

1172 from pydantic_core import SchemaValidator, core_schema 

1173 

1174 schema = core_schema.datetime_schema() 

1175 v = SchemaValidator(schema) 

1176 now = datetime.now() 

1177 assert v.validate_python(str(now)) == now 

1178 ``` 

1179 

1180 Args: 

1181 strict: Whether the value should be a datetime or a value that can be converted to a datetime 

1182 le: The value must be less than or equal to this datetime 

1183 ge: The value must be greater than or equal to this datetime 

1184 lt: The value must be strictly less than this datetime 

1185 gt: The value must be strictly greater than this datetime 

1186 now_op: The value must be in the past or future relative to the current datetime 

1187 tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset 

1188 TODO: use of a tzinfo where offset changes based on the datetime is not yet supported 

1189 now_utc_offset: The value must be in the past or future relative to the current datetime with this utc offset 

1190 microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large 

1191 ref: optional unique identifier of the schema, used to reference the schema in other places 

1192 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1193 serialization: Custom serialization schema 

1194 """ 

1195 return _dict_not_none( 

1196 type='datetime', 

1197 strict=strict, 

1198 le=le, 

1199 ge=ge, 

1200 lt=lt, 

1201 gt=gt, 

1202 now_op=now_op, 

1203 tz_constraint=tz_constraint, 

1204 now_utc_offset=now_utc_offset, 

1205 microseconds_precision=microseconds_precision, 

1206 ref=ref, 

1207 metadata=metadata, 

1208 serialization=serialization, 

1209 ) 

1210 

1211 

1212class TimedeltaSchema(TypedDict, total=False): 

1213 type: Required[Literal['timedelta']] 

1214 strict: bool 

1215 le: timedelta 

1216 ge: timedelta 

1217 lt: timedelta 

1218 gt: timedelta 

1219 microseconds_precision: Literal['truncate', 'error'] 

1220 ref: str 

1221 metadata: dict[str, Any] 

1222 serialization: SerSchema 

1223 

1224 

1225def timedelta_schema( 

1226 *, 

1227 strict: bool | None = None, 

1228 le: timedelta | None = None, 

1229 ge: timedelta | None = None, 

1230 lt: timedelta | None = None, 

1231 gt: timedelta | None = None, 

1232 microseconds_precision: Literal['truncate', 'error'] = 'truncate', 

1233 ref: str | None = None, 

1234 metadata: dict[str, Any] | None = None, 

1235 serialization: SerSchema | None = None, 

1236) -> TimedeltaSchema: 

1237 """ 

1238 Returns a schema that matches a timedelta value, e.g.: 

1239 

1240 ```py 

1241 from datetime import timedelta 

1242 from pydantic_core import SchemaValidator, core_schema 

1243 

1244 schema = core_schema.timedelta_schema(le=timedelta(days=1), ge=timedelta(days=0)) 

1245 v = SchemaValidator(schema) 

1246 assert v.validate_python(timedelta(hours=12)) == timedelta(hours=12) 

1247 ``` 

1248 

1249 Args: 

1250 strict: Whether the value should be a timedelta or a value that can be converted to a timedelta 

1251 le: The value must be less than or equal to this timedelta 

1252 ge: The value must be greater than or equal to this timedelta 

1253 lt: The value must be strictly less than this timedelta 

1254 gt: The value must be strictly greater than this timedelta 

1255 microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large 

1256 ref: optional unique identifier of the schema, used to reference the schema in other places 

1257 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1258 serialization: Custom serialization schema 

1259 """ 

1260 return _dict_not_none( 

1261 type='timedelta', 

1262 strict=strict, 

1263 le=le, 

1264 ge=ge, 

1265 lt=lt, 

1266 gt=gt, 

1267 microseconds_precision=microseconds_precision, 

1268 ref=ref, 

1269 metadata=metadata, 

1270 serialization=serialization, 

1271 ) 

1272 

1273 

1274class LiteralSchema(TypedDict, total=False): 

1275 type: Required[Literal['literal']] 

1276 expected: Required[list[Any]] 

1277 ref: str 

1278 metadata: dict[str, Any] 

1279 serialization: SerSchema 

1280 

1281 

1282def literal_schema( 

1283 expected: list[Any], 

1284 *, 

1285 ref: str | None = None, 

1286 metadata: dict[str, Any] | None = None, 

1287 serialization: SerSchema | None = None, 

1288) -> LiteralSchema: 

1289 """ 

1290 Returns a schema that matches a literal value, e.g.: 

1291 

1292 ```py 

1293 from pydantic_core import SchemaValidator, core_schema 

1294 

1295 schema = core_schema.literal_schema(['hello', 'world']) 

1296 v = SchemaValidator(schema) 

1297 assert v.validate_python('hello') == 'hello' 

1298 ``` 

1299 

1300 Args: 

1301 expected: The value must be one of these values 

1302 ref: optional unique identifier of the schema, used to reference the schema in other places 

1303 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1304 serialization: Custom serialization schema 

1305 """ 

1306 return _dict_not_none(type='literal', expected=expected, ref=ref, metadata=metadata, serialization=serialization) 

1307 

1308 

1309class EnumSchema(TypedDict, total=False): 

1310 type: Required[Literal['enum']] 

1311 cls: Required[Any] 

1312 members: Required[list[Any]] 

1313 sub_type: Literal['str', 'int', 'float'] 

1314 missing: Callable[[Any], Any] 

1315 strict: bool 

1316 ref: str 

1317 metadata: dict[str, Any] 

1318 serialization: SerSchema 

1319 

1320 

1321def enum_schema( 

1322 cls: Any, 

1323 members: list[Any], 

1324 *, 

1325 sub_type: Literal['str', 'int', 'float'] | None = None, 

1326 missing: Callable[[Any], Any] | None = None, 

1327 strict: bool | None = None, 

1328 ref: str | None = None, 

1329 metadata: dict[str, Any] | None = None, 

1330 serialization: SerSchema | None = None, 

1331) -> EnumSchema: 

1332 """ 

1333 Returns a schema that matches an enum value, e.g.: 

1334 

1335 ```py 

1336 from enum import Enum 

1337 from pydantic_core import SchemaValidator, core_schema 

1338 

1339 class Color(Enum): 

1340 RED = 1 

1341 GREEN = 2 

1342 BLUE = 3 

1343 

1344 schema = core_schema.enum_schema(Color, list(Color.__members__.values())) 

1345 v = SchemaValidator(schema) 

1346 assert v.validate_python(2) is Color.GREEN 

1347 ``` 

1348 

1349 Args: 

1350 cls: The enum class 

1351 members: The members of the enum, generally `list(MyEnum.__members__.values())` 

1352 sub_type: The type of the enum, either 'str' or 'int' or None for plain enums 

1353 missing: A function to use when the value is not found in the enum, from `_missing_` 

1354 strict: Whether to use strict mode, defaults to False 

1355 ref: optional unique identifier of the schema, used to reference the schema in other places 

1356 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1357 serialization: Custom serialization schema 

1358 """ 

1359 return _dict_not_none( 

1360 type='enum', 

1361 cls=cls, 

1362 members=members, 

1363 sub_type=sub_type, 

1364 missing=missing, 

1365 strict=strict, 

1366 ref=ref, 

1367 metadata=metadata, 

1368 serialization=serialization, 

1369 ) 

1370 

1371 

1372class MissingSentinelSchema(TypedDict, total=False): 

1373 type: Required[Literal['missing-sentinel']] 

1374 metadata: dict[str, Any] 

1375 serialization: SerSchema 

1376 

1377 

1378def missing_sentinel_schema( 

1379 metadata: dict[str, Any] | None = None, 

1380 serialization: SerSchema | None = None, 

1381) -> MissingSentinelSchema: 

1382 """Returns a schema for the `MISSING` sentinel.""" 

1383 

1384 return _dict_not_none( 

1385 type='missing-sentinel', 

1386 metadata=metadata, 

1387 serialization=serialization, 

1388 ) 

1389 

1390 

1391# must match input/parse_json.rs::JsonType::try_from 

1392JsonType = Literal['null', 'bool', 'int', 'float', 'str', 'list', 'dict'] 

1393 

1394 

1395class IsInstanceSchema(TypedDict, total=False): 

1396 type: Required[Literal['is-instance']] 

1397 cls: Required[Any] 

1398 cls_repr: str 

1399 ref: str 

1400 metadata: dict[str, Any] 

1401 serialization: SerSchema 

1402 

1403 

1404def is_instance_schema( 

1405 cls: Any, 

1406 *, 

1407 cls_repr: str | None = None, 

1408 ref: str | None = None, 

1409 metadata: dict[str, Any] | None = None, 

1410 serialization: SerSchema | None = None, 

1411) -> IsInstanceSchema: 

1412 """ 

1413 Returns a schema that checks if a value is an instance of a class, equivalent to python's `isinstance` method, e.g.: 

1414 

1415 ```py 

1416 from pydantic_core import SchemaValidator, core_schema 

1417 

1418 class A: 

1419 pass 

1420 

1421 schema = core_schema.is_instance_schema(cls=A) 

1422 v = SchemaValidator(schema) 

1423 v.validate_python(A()) 

1424 ``` 

1425 

1426 Args: 

1427 cls: The value must be an instance of this class 

1428 cls_repr: If provided this string is used in the validator name instead of `repr(cls)` 

1429 ref: optional unique identifier of the schema, used to reference the schema in other places 

1430 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1431 serialization: Custom serialization schema 

1432 """ 

1433 return _dict_not_none( 

1434 type='is-instance', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization 

1435 ) 

1436 

1437 

1438class IsSubclassSchema(TypedDict, total=False): 

1439 type: Required[Literal['is-subclass']] 

1440 cls: Required[type[Any]] 

1441 cls_repr: str 

1442 ref: str 

1443 metadata: dict[str, Any] 

1444 serialization: SerSchema 

1445 

1446 

1447def is_subclass_schema( 

1448 cls: type[Any], 

1449 *, 

1450 cls_repr: str | None = None, 

1451 ref: str | None = None, 

1452 metadata: dict[str, Any] | None = None, 

1453 serialization: SerSchema | None = None, 

1454) -> IsInstanceSchema: 

1455 """ 

1456 Returns a schema that checks if a value is a subtype of a class, equivalent to python's `issubclass` method, e.g.: 

1457 

1458 ```py 

1459 from pydantic_core import SchemaValidator, core_schema 

1460 

1461 class A: 

1462 pass 

1463 

1464 class B(A): 

1465 pass 

1466 

1467 schema = core_schema.is_subclass_schema(cls=A) 

1468 v = SchemaValidator(schema) 

1469 v.validate_python(B) 

1470 ``` 

1471 

1472 Args: 

1473 cls: The value must be a subclass of this class 

1474 cls_repr: If provided this string is used in the validator name instead of `repr(cls)` 

1475 ref: optional unique identifier of the schema, used to reference the schema in other places 

1476 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1477 serialization: Custom serialization schema 

1478 """ 

1479 return _dict_not_none( 

1480 type='is-subclass', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization 

1481 ) 

1482 

1483 

1484class CallableSchema(TypedDict, total=False): 

1485 type: Required[Literal['callable']] 

1486 ref: str 

1487 metadata: dict[str, Any] 

1488 serialization: SerSchema 

1489 

1490 

1491def callable_schema( 

1492 *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None 

1493) -> CallableSchema: 

1494 """ 

1495 Returns a schema that checks if a value is callable, equivalent to python's `callable` method, e.g.: 

1496 

1497 ```py 

1498 from pydantic_core import SchemaValidator, core_schema 

1499 

1500 schema = core_schema.callable_schema() 

1501 v = SchemaValidator(schema) 

1502 v.validate_python(min) 

1503 ``` 

1504 

1505 Args: 

1506 ref: optional unique identifier of the schema, used to reference the schema in other places 

1507 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1508 serialization: Custom serialization schema 

1509 """ 

1510 return _dict_not_none(type='callable', ref=ref, metadata=metadata, serialization=serialization) 

1511 

1512 

1513class UuidSchema(TypedDict, total=False): 

1514 type: Required[Literal['uuid']] 

1515 version: Literal[1, 3, 4, 5, 7] 

1516 strict: bool 

1517 ref: str 

1518 metadata: dict[str, Any] 

1519 serialization: SerSchema 

1520 

1521 

1522def uuid_schema( 

1523 *, 

1524 version: Literal[1, 3, 4, 5, 6, 7, 8] | None = None, 

1525 strict: bool | None = None, 

1526 ref: str | None = None, 

1527 metadata: dict[str, Any] | None = None, 

1528 serialization: SerSchema | None = None, 

1529) -> UuidSchema: 

1530 return _dict_not_none( 

1531 type='uuid', version=version, strict=strict, ref=ref, metadata=metadata, serialization=serialization 

1532 ) 

1533 

1534 

1535class IncExSeqSerSchema(TypedDict, total=False): 

1536 type: Required[Literal['include-exclude-sequence']] 

1537 include: set[int] 

1538 exclude: set[int] 

1539 

1540 

1541def filter_seq_schema(*, include: set[int] | None = None, exclude: set[int] | None = None) -> IncExSeqSerSchema: 

1542 return _dict_not_none(type='include-exclude-sequence', include=include, exclude=exclude) 

1543 

1544 

1545IncExSeqOrElseSerSchema = Union[IncExSeqSerSchema, SerSchema] 

1546 

1547 

1548class ListSchema(TypedDict, total=False): 

1549 type: Required[Literal['list']] 

1550 items_schema: CoreSchema 

1551 min_length: int 

1552 max_length: int 

1553 fail_fast: bool 

1554 strict: bool 

1555 ref: str 

1556 metadata: dict[str, Any] 

1557 serialization: IncExSeqOrElseSerSchema 

1558 

1559 

1560def list_schema( 

1561 items_schema: CoreSchema | None = None, 

1562 *, 

1563 min_length: int | None = None, 

1564 max_length: int | None = None, 

1565 fail_fast: bool | None = None, 

1566 strict: bool | None = None, 

1567 ref: str | None = None, 

1568 metadata: dict[str, Any] | None = None, 

1569 serialization: IncExSeqOrElseSerSchema | None = None, 

1570) -> ListSchema: 

1571 """ 

1572 Returns a schema that matches a list value, e.g.: 

1573 

1574 ```py 

1575 from pydantic_core import SchemaValidator, core_schema 

1576 

1577 schema = core_schema.list_schema(core_schema.int_schema(), min_length=0, max_length=10) 

1578 v = SchemaValidator(schema) 

1579 assert v.validate_python(['4']) == [4] 

1580 ``` 

1581 

1582 Args: 

1583 items_schema: The value must be a list of items that match this schema 

1584 min_length: The value must be a list with at least this many items 

1585 max_length: The value must be a list with at most this many items 

1586 fail_fast: Stop validation on the first error 

1587 strict: The value must be a list with exactly this many items 

1588 ref: optional unique identifier of the schema, used to reference the schema in other places 

1589 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1590 serialization: Custom serialization schema 

1591 """ 

1592 return _dict_not_none( 

1593 type='list', 

1594 items_schema=items_schema, 

1595 min_length=min_length, 

1596 max_length=max_length, 

1597 fail_fast=fail_fast, 

1598 strict=strict, 

1599 ref=ref, 

1600 metadata=metadata, 

1601 serialization=serialization, 

1602 ) 

1603 

1604 

1605# @deprecated('tuple_positional_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.') 

1606def tuple_positional_schema( 

1607 items_schema: list[CoreSchema], 

1608 *, 

1609 extras_schema: CoreSchema | None = None, 

1610 strict: bool | None = None, 

1611 ref: str | None = None, 

1612 metadata: dict[str, Any] | None = None, 

1613 serialization: IncExSeqOrElseSerSchema | None = None, 

1614) -> TupleSchema: 

1615 """ 

1616 Returns a schema that matches a tuple of schemas, e.g.: 

1617 

1618 ```py 

1619 from pydantic_core import SchemaValidator, core_schema 

1620 

1621 schema = core_schema.tuple_positional_schema( 

1622 [core_schema.int_schema(), core_schema.str_schema()] 

1623 ) 

1624 v = SchemaValidator(schema) 

1625 assert v.validate_python((1, 'hello')) == (1, 'hello') 

1626 ``` 

1627 

1628 Args: 

1629 items_schema: The value must be a tuple with items that match these schemas 

1630 extras_schema: The value must be a tuple with items that match this schema 

1631 This was inspired by JSON schema's `prefixItems` and `items` fields. 

1632 In python's `typing.Tuple`, you can't specify a type for "extra" items -- they must all be the same type 

1633 if the length is variable. So this field won't be set from a `typing.Tuple` annotation on a pydantic model. 

1634 strict: The value must be a tuple with exactly this many items 

1635 ref: optional unique identifier of the schema, used to reference the schema in other places 

1636 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1637 serialization: Custom serialization schema 

1638 """ 

1639 if extras_schema is not None: 

1640 variadic_item_index = len(items_schema) 

1641 items_schema = items_schema + [extras_schema] 

1642 else: 

1643 variadic_item_index = None 

1644 return tuple_schema( 

1645 items_schema=items_schema, 

1646 variadic_item_index=variadic_item_index, 

1647 strict=strict, 

1648 ref=ref, 

1649 metadata=metadata, 

1650 serialization=serialization, 

1651 ) 

1652 

1653 

1654# @deprecated('tuple_variable_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.') 

1655def tuple_variable_schema( 

1656 items_schema: CoreSchema | None = None, 

1657 *, 

1658 min_length: int | None = None, 

1659 max_length: int | None = None, 

1660 strict: bool | None = None, 

1661 ref: str | None = None, 

1662 metadata: dict[str, Any] | None = None, 

1663 serialization: IncExSeqOrElseSerSchema | None = None, 

1664) -> TupleSchema: 

1665 """ 

1666 Returns a schema that matches a tuple of a given schema, e.g.: 

1667 

1668 ```py 

1669 from pydantic_core import SchemaValidator, core_schema 

1670 

1671 schema = core_schema.tuple_variable_schema( 

1672 items_schema=core_schema.int_schema(), min_length=0, max_length=10 

1673 ) 

1674 v = SchemaValidator(schema) 

1675 assert v.validate_python(('1', 2, 3)) == (1, 2, 3) 

1676 ``` 

1677 

1678 Args: 

1679 items_schema: The value must be a tuple with items that match this schema 

1680 min_length: The value must be a tuple with at least this many items 

1681 max_length: The value must be a tuple with at most this many items 

1682 strict: The value must be a tuple with exactly this many items 

1683 ref: Optional unique identifier of the schema, used to reference the schema in other places 

1684 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1685 serialization: Custom serialization schema 

1686 """ 

1687 return tuple_schema( 

1688 items_schema=[items_schema or any_schema()], 

1689 variadic_item_index=0, 

1690 min_length=min_length, 

1691 max_length=max_length, 

1692 strict=strict, 

1693 ref=ref, 

1694 metadata=metadata, 

1695 serialization=serialization, 

1696 ) 

1697 

1698 

1699class TupleSchema(TypedDict, total=False): 

1700 type: Required[Literal['tuple']] 

1701 items_schema: Required[list[CoreSchema]] 

1702 variadic_item_index: int 

1703 min_length: int 

1704 max_length: int 

1705 fail_fast: bool 

1706 strict: bool 

1707 ref: str 

1708 metadata: dict[str, Any] 

1709 serialization: IncExSeqOrElseSerSchema 

1710 

1711 

1712def tuple_schema( 

1713 items_schema: list[CoreSchema], 

1714 *, 

1715 variadic_item_index: int | None = None, 

1716 min_length: int | None = None, 

1717 max_length: int | None = None, 

1718 fail_fast: bool | None = None, 

1719 strict: bool | None = None, 

1720 ref: str | None = None, 

1721 metadata: dict[str, Any] | None = None, 

1722 serialization: IncExSeqOrElseSerSchema | None = None, 

1723) -> TupleSchema: 

1724 """ 

1725 Returns a schema that matches a tuple of schemas, with an optional variadic item, e.g.: 

1726 

1727 ```py 

1728 from pydantic_core import SchemaValidator, core_schema 

1729 

1730 schema = core_schema.tuple_schema( 

1731 [core_schema.int_schema(), core_schema.str_schema(), core_schema.float_schema()], 

1732 variadic_item_index=1, 

1733 ) 

1734 v = SchemaValidator(schema) 

1735 assert v.validate_python((1, 'hello', 'world', 1.5)) == (1, 'hello', 'world', 1.5) 

1736 ``` 

1737 

1738 Args: 

1739 items_schema: The value must be a tuple with items that match these schemas 

1740 variadic_item_index: The index of the schema in `items_schema` to be treated as variadic (following PEP 646) 

1741 min_length: The value must be a tuple with at least this many items 

1742 max_length: The value must be a tuple with at most this many items 

1743 fail_fast: Stop validation on the first error 

1744 strict: The value must be a tuple with exactly this many items 

1745 ref: Optional unique identifier of the schema, used to reference the schema in other places 

1746 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1747 serialization: Custom serialization schema 

1748 """ 

1749 return _dict_not_none( 

1750 type='tuple', 

1751 items_schema=items_schema, 

1752 variadic_item_index=variadic_item_index, 

1753 min_length=min_length, 

1754 max_length=max_length, 

1755 fail_fast=fail_fast, 

1756 strict=strict, 

1757 ref=ref, 

1758 metadata=metadata, 

1759 serialization=serialization, 

1760 ) 

1761 

1762 

1763class SetSchema(TypedDict, total=False): 

1764 type: Required[Literal['set']] 

1765 items_schema: CoreSchema 

1766 min_length: int 

1767 max_length: int 

1768 fail_fast: bool 

1769 strict: bool 

1770 ref: str 

1771 metadata: dict[str, Any] 

1772 serialization: SerSchema 

1773 

1774 

1775def set_schema( 

1776 items_schema: CoreSchema | None = None, 

1777 *, 

1778 min_length: int | None = None, 

1779 max_length: int | None = None, 

1780 fail_fast: bool | None = None, 

1781 strict: bool | None = None, 

1782 ref: str | None = None, 

1783 metadata: dict[str, Any] | None = None, 

1784 serialization: SerSchema | None = None, 

1785) -> SetSchema: 

1786 """ 

1787 Returns a schema that matches a set of a given schema, e.g.: 

1788 

1789 ```py 

1790 from pydantic_core import SchemaValidator, core_schema 

1791 

1792 schema = core_schema.set_schema( 

1793 items_schema=core_schema.int_schema(), min_length=0, max_length=10 

1794 ) 

1795 v = SchemaValidator(schema) 

1796 assert v.validate_python({1, '2', 3}) == {1, 2, 3} 

1797 ``` 

1798 

1799 Args: 

1800 items_schema: The value must be a set with items that match this schema 

1801 min_length: The value must be a set with at least this many items 

1802 max_length: The value must be a set with at most this many items 

1803 fail_fast: Stop validation on the first error 

1804 strict: The value must be a set with exactly this many items 

1805 ref: optional unique identifier of the schema, used to reference the schema in other places 

1806 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1807 serialization: Custom serialization schema 

1808 """ 

1809 return _dict_not_none( 

1810 type='set', 

1811 items_schema=items_schema, 

1812 min_length=min_length, 

1813 max_length=max_length, 

1814 fail_fast=fail_fast, 

1815 strict=strict, 

1816 ref=ref, 

1817 metadata=metadata, 

1818 serialization=serialization, 

1819 ) 

1820 

1821 

1822class FrozenSetSchema(TypedDict, total=False): 

1823 type: Required[Literal['frozenset']] 

1824 items_schema: CoreSchema 

1825 min_length: int 

1826 max_length: int 

1827 fail_fast: bool 

1828 strict: bool 

1829 ref: str 

1830 metadata: dict[str, Any] 

1831 serialization: SerSchema 

1832 

1833 

1834def frozenset_schema( 

1835 items_schema: CoreSchema | None = None, 

1836 *, 

1837 min_length: int | None = None, 

1838 max_length: int | None = None, 

1839 fail_fast: bool | None = None, 

1840 strict: bool | None = None, 

1841 ref: str | None = None, 

1842 metadata: dict[str, Any] | None = None, 

1843 serialization: SerSchema | None = None, 

1844) -> FrozenSetSchema: 

1845 """ 

1846 Returns a schema that matches a frozenset of a given schema, e.g.: 

1847 

1848 ```py 

1849 from pydantic_core import SchemaValidator, core_schema 

1850 

1851 schema = core_schema.frozenset_schema( 

1852 items_schema=core_schema.int_schema(), min_length=0, max_length=10 

1853 ) 

1854 v = SchemaValidator(schema) 

1855 assert v.validate_python(frozenset(range(3))) == frozenset({0, 1, 2}) 

1856 ``` 

1857 

1858 Args: 

1859 items_schema: The value must be a frozenset with items that match this schema 

1860 min_length: The value must be a frozenset with at least this many items 

1861 max_length: The value must be a frozenset with at most this many items 

1862 fail_fast: Stop validation on the first error 

1863 strict: The value must be a frozenset with exactly this many items 

1864 ref: optional unique identifier of the schema, used to reference the schema in other places 

1865 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1866 serialization: Custom serialization schema 

1867 """ 

1868 return _dict_not_none( 

1869 type='frozenset', 

1870 items_schema=items_schema, 

1871 min_length=min_length, 

1872 max_length=max_length, 

1873 fail_fast=fail_fast, 

1874 strict=strict, 

1875 ref=ref, 

1876 metadata=metadata, 

1877 serialization=serialization, 

1878 ) 

1879 

1880 

1881class GeneratorSchema(TypedDict, total=False): 

1882 type: Required[Literal['generator']] 

1883 items_schema: CoreSchema 

1884 min_length: int 

1885 max_length: int 

1886 ref: str 

1887 metadata: dict[str, Any] 

1888 serialization: IncExSeqOrElseSerSchema 

1889 

1890 

1891def generator_schema( 

1892 items_schema: CoreSchema | None = None, 

1893 *, 

1894 min_length: int | None = None, 

1895 max_length: int | None = None, 

1896 ref: str | None = None, 

1897 metadata: dict[str, Any] | None = None, 

1898 serialization: IncExSeqOrElseSerSchema | None = None, 

1899) -> GeneratorSchema: 

1900 """ 

1901 Returns a schema that matches a generator value, e.g.: 

1902 

1903 ```py 

1904 from typing import Iterator 

1905 from pydantic_core import SchemaValidator, core_schema 

1906 

1907 def gen() -> Iterator[int]: 

1908 yield 1 

1909 

1910 schema = core_schema.generator_schema(items_schema=core_schema.int_schema()) 

1911 v = SchemaValidator(schema) 

1912 v.validate_python(gen()) 

1913 ``` 

1914 

1915 Unlike other types, validated generators do not raise ValidationErrors eagerly, 

1916 but instead will raise a ValidationError when a violating value is actually read from the generator. 

1917 This is to ensure that "validated" generators retain the benefit of lazy evaluation. 

1918 

1919 Args: 

1920 items_schema: The value must be a generator with items that match this schema 

1921 min_length: The value must be a generator that yields at least this many items 

1922 max_length: The value must be a generator that yields at most this many items 

1923 ref: optional unique identifier of the schema, used to reference the schema in other places 

1924 metadata: Any other information you want to include with the schema, not used by pydantic-core 

1925 serialization: Custom serialization schema 

1926 """ 

1927 return _dict_not_none( 

1928 type='generator', 

1929 items_schema=items_schema, 

1930 min_length=min_length, 

1931 max_length=max_length, 

1932 ref=ref, 

1933 metadata=metadata, 

1934 serialization=serialization, 

1935 ) 

1936 

1937 

1938IncExDict = set[Union[int, str]] 

1939 

1940 

1941class IncExDictSerSchema(TypedDict, total=False): 

1942 type: Required[Literal['include-exclude-dict']] 

1943 include: IncExDict 

1944 exclude: IncExDict 

1945 

1946 

1947def filter_dict_schema(*, include: IncExDict | None = None, exclude: IncExDict | None = None) -> IncExDictSerSchema: 

1948 return _dict_not_none(type='include-exclude-dict', include=include, exclude=exclude) 

1949 

1950 

1951IncExDictOrElseSerSchema = Union[IncExDictSerSchema, SerSchema] 

1952 

1953 

1954class DictSchema(TypedDict, total=False): 

1955 type: Required[Literal['dict']] 

1956 keys_schema: CoreSchema # default: AnySchema 

1957 values_schema: CoreSchema # default: AnySchema 

1958 min_length: int 

1959 max_length: int 

1960 fail_fast: bool 

1961 strict: bool 

1962 ref: str 

1963 metadata: dict[str, Any] 

1964 serialization: IncExDictOrElseSerSchema 

1965 

1966 

1967def dict_schema( 

1968 keys_schema: CoreSchema | None = None, 

1969 values_schema: CoreSchema | None = None, 

1970 *, 

1971 min_length: int | None = None, 

1972 max_length: int | None = None, 

1973 fail_fast: bool | None = None, 

1974 strict: bool | None = None, 

1975 ref: str | None = None, 

1976 metadata: dict[str, Any] | None = None, 

1977 serialization: SerSchema | None = None, 

1978) -> DictSchema: 

1979 """ 

1980 Returns a schema that matches a dict value, e.g.: 

1981 

1982 ```py 

1983 from pydantic_core import SchemaValidator, core_schema 

1984 

1985 schema = core_schema.dict_schema( 

1986 keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema() 

1987 ) 

1988 v = SchemaValidator(schema) 

1989 assert v.validate_python({'a': '1', 'b': 2}) == {'a': 1, 'b': 2} 

1990 ``` 

1991 

1992 Args: 

1993 keys_schema: The value must be a dict with keys that match this schema 

1994 values_schema: The value must be a dict with values that match this schema 

1995 min_length: The value must be a dict with at least this many items 

1996 max_length: The value must be a dict with at most this many items 

1997 fail_fast: Stop validation on the first error 

1998 strict: Whether the keys and values should be validated with strict mode 

1999 ref: optional unique identifier of the schema, used to reference the schema in other places 

2000 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2001 serialization: Custom serialization schema 

2002 """ 

2003 return _dict_not_none( 

2004 type='dict', 

2005 keys_schema=keys_schema, 

2006 values_schema=values_schema, 

2007 min_length=min_length, 

2008 max_length=max_length, 

2009 fail_fast=fail_fast, 

2010 strict=strict, 

2011 ref=ref, 

2012 metadata=metadata, 

2013 serialization=serialization, 

2014 ) 

2015 

2016 

2017# (input_value: Any, /) -> Any 

2018NoInfoValidatorFunction = Callable[[Any], Any] 

2019 

2020 

2021class NoInfoValidatorFunctionSchema(TypedDict): 

2022 type: Literal['no-info'] 

2023 function: NoInfoValidatorFunction 

2024 

2025 

2026# (input_value: Any, info: ValidationInfo, /) -> Any 

2027WithInfoValidatorFunction = Callable[[Any, ValidationInfo[Any]], Any] 

2028 

2029 

2030class WithInfoValidatorFunctionSchema(TypedDict, total=False): 

2031 type: Required[Literal['with-info']] 

2032 function: Required[WithInfoValidatorFunction] 

2033 field_name: str # deprecated 

2034 

2035 

2036ValidationFunction = Union[NoInfoValidatorFunctionSchema, WithInfoValidatorFunctionSchema] 

2037 

2038 

2039class _ValidatorFunctionSchema(TypedDict, total=False): 

2040 function: Required[ValidationFunction] 

2041 schema: Required[CoreSchema] 

2042 ref: str 

2043 metadata: dict[str, Any] 

2044 serialization: SerSchema 

2045 

2046 

2047class BeforeValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): 

2048 type: Required[Literal['function-before']] 

2049 json_schema_input_schema: CoreSchema 

2050 

2051 

2052def no_info_before_validator_function( 

2053 function: NoInfoValidatorFunction, 

2054 schema: CoreSchema, 

2055 *, 

2056 ref: str | None = None, 

2057 json_schema_input_schema: CoreSchema | None = None, 

2058 metadata: dict[str, Any] | None = None, 

2059 serialization: SerSchema | None = None, 

2060) -> BeforeValidatorFunctionSchema: 

2061 """ 

2062 Returns a schema that calls a validator function before validating, no `info` argument is provided, e.g.: 

2063 

2064 ```py 

2065 from pydantic_core import SchemaValidator, core_schema 

2066 

2067 def fn(v: bytes) -> str: 

2068 return v.decode() + 'world' 

2069 

2070 func_schema = core_schema.no_info_before_validator_function( 

2071 function=fn, schema=core_schema.str_schema() 

2072 ) 

2073 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) 

2074 

2075 v = SchemaValidator(schema) 

2076 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} 

2077 ``` 

2078 

2079 Args: 

2080 function: The validator function to call 

2081 schema: The schema to validate the output of the validator function 

2082 ref: optional unique identifier of the schema, used to reference the schema in other places 

2083 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type 

2084 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2085 serialization: Custom serialization schema 

2086 """ 

2087 return _dict_not_none( 

2088 type='function-before', 

2089 function={'type': 'no-info', 'function': function}, 

2090 schema=schema, 

2091 ref=ref, 

2092 json_schema_input_schema=json_schema_input_schema, 

2093 metadata=metadata, 

2094 serialization=serialization, 

2095 ) 

2096 

2097 

2098def with_info_before_validator_function( 

2099 function: WithInfoValidatorFunction, 

2100 schema: CoreSchema, 

2101 *, 

2102 field_name: str | None = None, 

2103 ref: str | None = None, 

2104 json_schema_input_schema: CoreSchema | None = None, 

2105 metadata: dict[str, Any] | None = None, 

2106 serialization: SerSchema | None = None, 

2107) -> BeforeValidatorFunctionSchema: 

2108 """ 

2109 Returns a schema that calls a validator function before validation, the function is called with 

2110 an `info` argument, e.g.: 

2111 

2112 ```py 

2113 from pydantic_core import SchemaValidator, core_schema 

2114 

2115 def fn(v: bytes, info: core_schema.ValidationInfo) -> str: 

2116 assert info.data is not None 

2117 assert info.field_name is not None 

2118 return v.decode() + 'world' 

2119 

2120 func_schema = core_schema.with_info_before_validator_function( 

2121 function=fn, schema=core_schema.str_schema() 

2122 ) 

2123 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) 

2124 

2125 v = SchemaValidator(schema) 

2126 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} 

2127 ``` 

2128 

2129 Args: 

2130 function: The validator function to call 

2131 field_name: The name of the field this validator is applied to, if any (deprecated) 

2132 schema: The schema to validate the output of the validator function 

2133 ref: optional unique identifier of the schema, used to reference the schema in other places 

2134 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type 

2135 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2136 serialization: Custom serialization schema 

2137 """ 

2138 if field_name is not None: 

2139 warnings.warn( 

2140 'The `field_name` argument on `with_info_before_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.', 

2141 DeprecationWarning, 

2142 stacklevel=2, 

2143 ) 

2144 

2145 return _dict_not_none( 

2146 type='function-before', 

2147 function=_dict_not_none(type='with-info', function=function, field_name=field_name), 

2148 schema=schema, 

2149 ref=ref, 

2150 json_schema_input_schema=json_schema_input_schema, 

2151 metadata=metadata, 

2152 serialization=serialization, 

2153 ) 

2154 

2155 

2156class AfterValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): 

2157 type: Required[Literal['function-after']] 

2158 

2159 

2160def no_info_after_validator_function( 

2161 function: NoInfoValidatorFunction, 

2162 schema: CoreSchema, 

2163 *, 

2164 ref: str | None = None, 

2165 json_schema_input_schema: CoreSchema | None = None, 

2166 metadata: dict[str, Any] | None = None, 

2167 serialization: SerSchema | None = None, 

2168) -> AfterValidatorFunctionSchema: 

2169 """ 

2170 Returns a schema that calls a validator function after validating, no `info` argument is provided, e.g.: 

2171 

2172 ```py 

2173 from pydantic_core import SchemaValidator, core_schema 

2174 

2175 def fn(v: str) -> str: 

2176 return v + 'world' 

2177 

2178 func_schema = core_schema.no_info_after_validator_function(fn, core_schema.str_schema()) 

2179 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) 

2180 

2181 v = SchemaValidator(schema) 

2182 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} 

2183 ``` 

2184 

2185 Args: 

2186 function: The validator function to call after the schema is validated 

2187 schema: The schema to validate before the validator function 

2188 ref: optional unique identifier of the schema, used to reference the schema in other places 

2189 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type 

2190 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2191 serialization: Custom serialization schema 

2192 """ 

2193 return _dict_not_none( 

2194 type='function-after', 

2195 function={'type': 'no-info', 'function': function}, 

2196 schema=schema, 

2197 ref=ref, 

2198 json_schema_input_schema=json_schema_input_schema, 

2199 metadata=metadata, 

2200 serialization=serialization, 

2201 ) 

2202 

2203 

2204def with_info_after_validator_function( 

2205 function: WithInfoValidatorFunction, 

2206 schema: CoreSchema, 

2207 *, 

2208 field_name: str | None = None, 

2209 ref: str | None = None, 

2210 metadata: dict[str, Any] | None = None, 

2211 serialization: SerSchema | None = None, 

2212) -> AfterValidatorFunctionSchema: 

2213 """ 

2214 Returns a schema that calls a validator function after validation, the function is called with 

2215 an `info` argument, e.g.: 

2216 

2217 ```py 

2218 from pydantic_core import SchemaValidator, core_schema 

2219 

2220 def fn(v: str, info: core_schema.ValidationInfo) -> str: 

2221 assert info.data is not None 

2222 assert info.field_name is not None 

2223 return v + 'world' 

2224 

2225 func_schema = core_schema.with_info_after_validator_function( 

2226 function=fn, schema=core_schema.str_schema() 

2227 ) 

2228 schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) 

2229 

2230 v = SchemaValidator(schema) 

2231 assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} 

2232 ``` 

2233 

2234 Args: 

2235 function: The validator function to call after the schema is validated 

2236 schema: The schema to validate before the validator function 

2237 field_name: The name of the field this validator is applied to, if any (deprecated) 

2238 ref: optional unique identifier of the schema, used to reference the schema in other places 

2239 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2240 serialization: Custom serialization schema 

2241 """ 

2242 if field_name is not None: 

2243 warnings.warn( 

2244 'The `field_name` argument on `with_info_after_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.', 

2245 DeprecationWarning, 

2246 stacklevel=2, 

2247 ) 

2248 

2249 return _dict_not_none( 

2250 type='function-after', 

2251 function=_dict_not_none(type='with-info', function=function, field_name=field_name), 

2252 schema=schema, 

2253 ref=ref, 

2254 metadata=metadata, 

2255 serialization=serialization, 

2256 ) 

2257 

2258 

2259class ValidatorFunctionWrapHandler(Protocol): 

2260 def __call__(self, input_value: Any, outer_location: str | int | None = None, /) -> Any: # pragma: no cover 

2261 ... 

2262 

2263 

2264# (input_value: Any, validator: ValidatorFunctionWrapHandler, /) -> Any 

2265NoInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler], Any] 

2266 

2267 

2268class NoInfoWrapValidatorFunctionSchema(TypedDict): 

2269 type: Literal['no-info'] 

2270 function: NoInfoWrapValidatorFunction 

2271 

2272 

2273# (input_value: Any, validator: ValidatorFunctionWrapHandler, info: ValidationInfo, /) -> Any 

2274WithInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler, ValidationInfo[Any]], Any] 

2275 

2276 

2277class WithInfoWrapValidatorFunctionSchema(TypedDict, total=False): 

2278 type: Required[Literal['with-info']] 

2279 function: Required[WithInfoWrapValidatorFunction] 

2280 field_name: str # deprecated 

2281 

2282 

2283WrapValidatorFunction = Union[NoInfoWrapValidatorFunctionSchema, WithInfoWrapValidatorFunctionSchema] 

2284 

2285 

2286class WrapValidatorFunctionSchema(TypedDict, total=False): 

2287 type: Required[Literal['function-wrap']] 

2288 function: Required[WrapValidatorFunction] 

2289 schema: Required[CoreSchema] 

2290 ref: str 

2291 json_schema_input_schema: CoreSchema 

2292 metadata: dict[str, Any] 

2293 serialization: SerSchema 

2294 

2295 

2296def no_info_wrap_validator_function( 

2297 function: NoInfoWrapValidatorFunction, 

2298 schema: CoreSchema, 

2299 *, 

2300 ref: str | None = None, 

2301 json_schema_input_schema: CoreSchema | None = None, 

2302 metadata: dict[str, Any] | None = None, 

2303 serialization: SerSchema | None = None, 

2304) -> WrapValidatorFunctionSchema: 

2305 """ 

2306 Returns a schema which calls a function with a `validator` callable argument which can 

2307 optionally be used to call inner validation with the function logic, this is much like the 

2308 "onion" implementation of middleware in many popular web frameworks, no `info` argument is passed, e.g.: 

2309 

2310 ```py 

2311 from pydantic_core import SchemaValidator, core_schema 

2312 

2313 def fn( 

2314 v: str, 

2315 validator: core_schema.ValidatorFunctionWrapHandler, 

2316 ) -> str: 

2317 return validator(input_value=v) + 'world' 

2318 

2319 schema = core_schema.no_info_wrap_validator_function( 

2320 function=fn, schema=core_schema.str_schema() 

2321 ) 

2322 v = SchemaValidator(schema) 

2323 assert v.validate_python('hello ') == 'hello world' 

2324 ``` 

2325 

2326 Args: 

2327 function: The validator function to call 

2328 schema: The schema to validate the output of the validator function 

2329 ref: optional unique identifier of the schema, used to reference the schema in other places 

2330 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type 

2331 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2332 serialization: Custom serialization schema 

2333 """ 

2334 return _dict_not_none( 

2335 type='function-wrap', 

2336 function={'type': 'no-info', 'function': function}, 

2337 schema=schema, 

2338 json_schema_input_schema=json_schema_input_schema, 

2339 ref=ref, 

2340 metadata=metadata, 

2341 serialization=serialization, 

2342 ) 

2343 

2344 

2345def with_info_wrap_validator_function( 

2346 function: WithInfoWrapValidatorFunction, 

2347 schema: CoreSchema, 

2348 *, 

2349 field_name: str | None = None, 

2350 json_schema_input_schema: CoreSchema | None = None, 

2351 ref: str | None = None, 

2352 metadata: dict[str, Any] | None = None, 

2353 serialization: SerSchema | None = None, 

2354) -> WrapValidatorFunctionSchema: 

2355 """ 

2356 Returns a schema which calls a function with a `validator` callable argument which can 

2357 optionally be used to call inner validation with the function logic, this is much like the 

2358 "onion" implementation of middleware in many popular web frameworks, an `info` argument is also passed, e.g.: 

2359 

2360 ```py 

2361 from pydantic_core import SchemaValidator, core_schema 

2362 

2363 def fn( 

2364 v: str, 

2365 validator: core_schema.ValidatorFunctionWrapHandler, 

2366 info: core_schema.ValidationInfo, 

2367 ) -> str: 

2368 return validator(input_value=v) + 'world' 

2369 

2370 schema = core_schema.with_info_wrap_validator_function( 

2371 function=fn, schema=core_schema.str_schema() 

2372 ) 

2373 v = SchemaValidator(schema) 

2374 assert v.validate_python('hello ') == 'hello world' 

2375 ``` 

2376 

2377 Args: 

2378 function: The validator function to call 

2379 schema: The schema to validate the output of the validator function 

2380 field_name: The name of the field this validator is applied to, if any (deprecated) 

2381 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type 

2382 ref: optional unique identifier of the schema, used to reference the schema in other places 

2383 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2384 serialization: Custom serialization schema 

2385 """ 

2386 if field_name is not None: 

2387 warnings.warn( 

2388 'The `field_name` argument on `with_info_wrap_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.', 

2389 DeprecationWarning, 

2390 stacklevel=2, 

2391 ) 

2392 

2393 return _dict_not_none( 

2394 type='function-wrap', 

2395 function=_dict_not_none(type='with-info', function=function, field_name=field_name), 

2396 schema=schema, 

2397 json_schema_input_schema=json_schema_input_schema, 

2398 ref=ref, 

2399 metadata=metadata, 

2400 serialization=serialization, 

2401 ) 

2402 

2403 

2404class PlainValidatorFunctionSchema(TypedDict, total=False): 

2405 type: Required[Literal['function-plain']] 

2406 function: Required[ValidationFunction] 

2407 ref: str 

2408 json_schema_input_schema: CoreSchema 

2409 metadata: dict[str, Any] 

2410 serialization: SerSchema 

2411 

2412 

2413def no_info_plain_validator_function( 

2414 function: NoInfoValidatorFunction, 

2415 *, 

2416 ref: str | None = None, 

2417 json_schema_input_schema: CoreSchema | None = None, 

2418 metadata: dict[str, Any] | None = None, 

2419 serialization: SerSchema | None = None, 

2420) -> PlainValidatorFunctionSchema: 

2421 """ 

2422 Returns a schema that uses the provided function for validation, no `info` argument is passed, e.g.: 

2423 

2424 ```py 

2425 from pydantic_core import SchemaValidator, core_schema 

2426 

2427 def fn(v: str) -> str: 

2428 assert 'hello' in v 

2429 return v + 'world' 

2430 

2431 schema = core_schema.no_info_plain_validator_function(function=fn) 

2432 v = SchemaValidator(schema) 

2433 assert v.validate_python('hello ') == 'hello world' 

2434 ``` 

2435 

2436 Args: 

2437 function: The validator function to call 

2438 ref: optional unique identifier of the schema, used to reference the schema in other places 

2439 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type 

2440 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2441 serialization: Custom serialization schema 

2442 """ 

2443 return _dict_not_none( 

2444 type='function-plain', 

2445 function={'type': 'no-info', 'function': function}, 

2446 ref=ref, 

2447 json_schema_input_schema=json_schema_input_schema, 

2448 metadata=metadata, 

2449 serialization=serialization, 

2450 ) 

2451 

2452 

2453def with_info_plain_validator_function( 

2454 function: WithInfoValidatorFunction, 

2455 *, 

2456 field_name: str | None = None, 

2457 ref: str | None = None, 

2458 json_schema_input_schema: CoreSchema | None = None, 

2459 metadata: dict[str, Any] | None = None, 

2460 serialization: SerSchema | None = None, 

2461) -> PlainValidatorFunctionSchema: 

2462 """ 

2463 Returns a schema that uses the provided function for validation, an `info` argument is passed, e.g.: 

2464 

2465 ```py 

2466 from pydantic_core import SchemaValidator, core_schema 

2467 

2468 def fn(v: str, info: core_schema.ValidationInfo) -> str: 

2469 assert 'hello' in v 

2470 return v + 'world' 

2471 

2472 schema = core_schema.with_info_plain_validator_function(function=fn) 

2473 v = SchemaValidator(schema) 

2474 assert v.validate_python('hello ') == 'hello world' 

2475 ``` 

2476 

2477 Args: 

2478 function: The validator function to call 

2479 field_name: The name of the field this validator is applied to, if any (deprecated) 

2480 ref: optional unique identifier of the schema, used to reference the schema in other places 

2481 json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type 

2482 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2483 serialization: Custom serialization schema 

2484 """ 

2485 if field_name is not None: 

2486 warnings.warn( 

2487 'The `field_name` argument on `with_info_plain_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.', 

2488 DeprecationWarning, 

2489 stacklevel=2, 

2490 ) 

2491 

2492 return _dict_not_none( 

2493 type='function-plain', 

2494 function=_dict_not_none(type='with-info', function=function, field_name=field_name), 

2495 ref=ref, 

2496 json_schema_input_schema=json_schema_input_schema, 

2497 metadata=metadata, 

2498 serialization=serialization, 

2499 ) 

2500 

2501 

2502class WithDefaultSchema(TypedDict, total=False): 

2503 type: Required[Literal['default']] 

2504 schema: Required[CoreSchema] 

2505 default: Any 

2506 default_factory: Union[Callable[[], Any], Callable[[dict[str, Any]], Any]] 

2507 default_factory_takes_data: bool 

2508 on_error: Literal['raise', 'omit', 'default'] # default: 'raise' 

2509 validate_default: bool # default: False 

2510 strict: bool 

2511 ref: str 

2512 metadata: dict[str, Any] 

2513 serialization: SerSchema 

2514 

2515 

2516def with_default_schema( 

2517 schema: CoreSchema, 

2518 *, 

2519 default: Any = PydanticUndefined, 

2520 default_factory: Union[Callable[[], Any], Callable[[dict[str, Any]], Any], None] = None, 

2521 default_factory_takes_data: bool | None = None, 

2522 on_error: Literal['raise', 'omit', 'default'] | None = None, 

2523 validate_default: bool | None = None, 

2524 strict: bool | None = None, 

2525 ref: str | None = None, 

2526 metadata: dict[str, Any] | None = None, 

2527 serialization: SerSchema | None = None, 

2528) -> WithDefaultSchema: 

2529 """ 

2530 Returns a schema that adds a default value to the given schema, e.g.: 

2531 

2532 ```py 

2533 from pydantic_core import SchemaValidator, core_schema 

2534 

2535 schema = core_schema.with_default_schema(core_schema.str_schema(), default='hello') 

2536 wrapper_schema = core_schema.typed_dict_schema( 

2537 {'a': core_schema.typed_dict_field(schema)} 

2538 ) 

2539 v = SchemaValidator(wrapper_schema) 

2540 assert v.validate_python({}) == v.validate_python({'a': 'hello'}) 

2541 ``` 

2542 

2543 Args: 

2544 schema: The schema to add a default value to 

2545 default: The default value to use 

2546 default_factory: A callable that returns the default value to use 

2547 default_factory_takes_data: Whether the default factory takes a validated data argument 

2548 on_error: What to do if the schema validation fails. One of 'raise', 'omit', 'default' 

2549 validate_default: Whether the default value should be validated 

2550 strict: Whether the underlying schema should be validated with strict mode 

2551 ref: optional unique identifier of the schema, used to reference the schema in other places 

2552 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2553 serialization: Custom serialization schema 

2554 """ 

2555 s = _dict_not_none( 

2556 type='default', 

2557 schema=schema, 

2558 default_factory=default_factory, 

2559 default_factory_takes_data=default_factory_takes_data, 

2560 on_error=on_error, 

2561 validate_default=validate_default, 

2562 strict=strict, 

2563 ref=ref, 

2564 metadata=metadata, 

2565 serialization=serialization, 

2566 ) 

2567 if default is not PydanticUndefined: 

2568 s['default'] = default 

2569 return s 

2570 

2571 

2572class NullableSchema(TypedDict, total=False): 

2573 type: Required[Literal['nullable']] 

2574 schema: Required[CoreSchema] 

2575 strict: bool 

2576 ref: str 

2577 metadata: dict[str, Any] 

2578 serialization: SerSchema 

2579 

2580 

2581def nullable_schema( 

2582 schema: CoreSchema, 

2583 *, 

2584 strict: bool | None = None, 

2585 ref: str | None = None, 

2586 metadata: dict[str, Any] | None = None, 

2587 serialization: SerSchema | None = None, 

2588) -> NullableSchema: 

2589 """ 

2590 Returns a schema that matches a nullable value, e.g.: 

2591 

2592 ```py 

2593 from pydantic_core import SchemaValidator, core_schema 

2594 

2595 schema = core_schema.nullable_schema(core_schema.str_schema()) 

2596 v = SchemaValidator(schema) 

2597 assert v.validate_python(None) is None 

2598 ``` 

2599 

2600 Args: 

2601 schema: The schema to wrap 

2602 strict: Whether the underlying schema should be validated with strict mode 

2603 ref: optional unique identifier of the schema, used to reference the schema in other places 

2604 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2605 serialization: Custom serialization schema 

2606 """ 

2607 return _dict_not_none( 

2608 type='nullable', schema=schema, strict=strict, ref=ref, metadata=metadata, serialization=serialization 

2609 ) 

2610 

2611 

2612class UnionSchema(TypedDict, total=False): 

2613 type: Required[Literal['union']] 

2614 choices: Required[list[Union[CoreSchema, tuple[CoreSchema, str]]]] 

2615 # default true, whether to automatically collapse unions with one element to the inner validator 

2616 auto_collapse: bool 

2617 custom_error_type: str 

2618 custom_error_message: str 

2619 custom_error_context: dict[str, Union[str, int, float]] 

2620 mode: Literal['smart', 'left_to_right'] # default: 'smart' 

2621 strict: bool 

2622 ref: str 

2623 metadata: dict[str, Any] 

2624 serialization: SerSchema 

2625 

2626 

2627def union_schema( 

2628 choices: list[CoreSchema | tuple[CoreSchema, str]], 

2629 *, 

2630 auto_collapse: bool | None = None, 

2631 custom_error_type: str | None = None, 

2632 custom_error_message: str | None = None, 

2633 custom_error_context: dict[str, str | int] | None = None, 

2634 mode: Literal['smart', 'left_to_right'] | None = None, 

2635 ref: str | None = None, 

2636 metadata: dict[str, Any] | None = None, 

2637 serialization: SerSchema | None = None, 

2638) -> UnionSchema: 

2639 """ 

2640 Returns a schema that matches a union value, e.g.: 

2641 

2642 ```py 

2643 from pydantic_core import SchemaValidator, core_schema 

2644 

2645 schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()]) 

2646 v = SchemaValidator(schema) 

2647 assert v.validate_python('hello') == 'hello' 

2648 assert v.validate_python(1) == 1 

2649 ``` 

2650 

2651 Args: 

2652 choices: The schemas to match. If a tuple, the second item is used as the label for the case. 

2653 auto_collapse: whether to automatically collapse unions with one element to the inner validator, default true 

2654 custom_error_type: The custom error type to use if the validation fails 

2655 custom_error_message: The custom error message to use if the validation fails 

2656 custom_error_context: The custom error context to use if the validation fails 

2657 mode: How to select which choice to return 

2658 * `smart` (default) will try to return the choice which is the closest match to the input value 

2659 * `left_to_right` will return the first choice in `choices` which succeeds validation 

2660 ref: optional unique identifier of the schema, used to reference the schema in other places 

2661 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2662 serialization: Custom serialization schema 

2663 """ 

2664 return _dict_not_none( 

2665 type='union', 

2666 choices=choices, 

2667 auto_collapse=auto_collapse, 

2668 custom_error_type=custom_error_type, 

2669 custom_error_message=custom_error_message, 

2670 custom_error_context=custom_error_context, 

2671 mode=mode, 

2672 ref=ref, 

2673 metadata=metadata, 

2674 serialization=serialization, 

2675 ) 

2676 

2677 

2678class TaggedUnionSchema(TypedDict, total=False): 

2679 type: Required[Literal['tagged-union']] 

2680 choices: Required[dict[Hashable, CoreSchema]] 

2681 discriminator: Required[Union[str, list[Union[str, int]], list[list[Union[str, int]]], Callable[[Any], Hashable]]] 

2682 custom_error_type: str 

2683 custom_error_message: str 

2684 custom_error_context: dict[str, Union[str, int, float]] 

2685 strict: bool 

2686 from_attributes: bool # default: True 

2687 ref: str 

2688 metadata: dict[str, Any] 

2689 serialization: SerSchema 

2690 

2691 

2692def tagged_union_schema( 

2693 choices: dict[Any, CoreSchema], 

2694 discriminator: str | list[str | int] | list[list[str | int]] | Callable[[Any], Any], 

2695 *, 

2696 custom_error_type: str | None = None, 

2697 custom_error_message: str | None = None, 

2698 custom_error_context: dict[str, int | str | float] | None = None, 

2699 strict: bool | None = None, 

2700 from_attributes: bool | None = None, 

2701 ref: str | None = None, 

2702 metadata: dict[str, Any] | None = None, 

2703 serialization: SerSchema | None = None, 

2704) -> TaggedUnionSchema: 

2705 """ 

2706 Returns a schema that matches a tagged union value, e.g.: 

2707 

2708 ```py 

2709 from pydantic_core import SchemaValidator, core_schema 

2710 

2711 apple_schema = core_schema.typed_dict_schema( 

2712 { 

2713 'foo': core_schema.typed_dict_field(core_schema.str_schema()), 

2714 'bar': core_schema.typed_dict_field(core_schema.int_schema()), 

2715 } 

2716 ) 

2717 banana_schema = core_schema.typed_dict_schema( 

2718 { 

2719 'foo': core_schema.typed_dict_field(core_schema.str_schema()), 

2720 'spam': core_schema.typed_dict_field( 

2721 core_schema.list_schema(items_schema=core_schema.int_schema()) 

2722 ), 

2723 } 

2724 ) 

2725 schema = core_schema.tagged_union_schema( 

2726 choices={ 

2727 'apple': apple_schema, 

2728 'banana': banana_schema, 

2729 }, 

2730 discriminator='foo', 

2731 ) 

2732 v = SchemaValidator(schema) 

2733 assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123} 

2734 assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == { 

2735 'foo': 'banana', 

2736 'spam': [1, 2, 3], 

2737 } 

2738 ``` 

2739 

2740 Args: 

2741 choices: The schemas to match 

2742 When retrieving a schema from `choices` using the discriminator value, if the value is a str, 

2743 it should be fed back into the `choices` map until a schema is obtained 

2744 (This approach is to prevent multiple ownership of a single schema in Rust) 

2745 discriminator: The discriminator to use to determine the schema to use 

2746 * If `discriminator` is a str, it is the name of the attribute to use as the discriminator 

2747 * If `discriminator` is a list of int/str, it should be used as a "path" to access the discriminator 

2748 * If `discriminator` is a list of lists, each inner list is a path, and the first path that exists is used 

2749 * If `discriminator` is a callable, it should return the discriminator when called on the value to validate; 

2750 the callable can return `None` to indicate that there is no matching discriminator present on the input 

2751 custom_error_type: The custom error type to use if the validation fails 

2752 custom_error_message: The custom error message to use if the validation fails 

2753 custom_error_context: The custom error context to use if the validation fails 

2754 strict: Whether the underlying schemas should be validated with strict mode 

2755 from_attributes: Whether to use the attributes of the object to retrieve the discriminator value 

2756 ref: optional unique identifier of the schema, used to reference the schema in other places 

2757 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2758 serialization: Custom serialization schema 

2759 """ 

2760 return _dict_not_none( 

2761 type='tagged-union', 

2762 choices=choices, 

2763 discriminator=discriminator, 

2764 custom_error_type=custom_error_type, 

2765 custom_error_message=custom_error_message, 

2766 custom_error_context=custom_error_context, 

2767 strict=strict, 

2768 from_attributes=from_attributes, 

2769 ref=ref, 

2770 metadata=metadata, 

2771 serialization=serialization, 

2772 ) 

2773 

2774 

2775class ChainSchema(TypedDict, total=False): 

2776 type: Required[Literal['chain']] 

2777 steps: Required[list[CoreSchema]] 

2778 ref: str 

2779 metadata: dict[str, Any] 

2780 serialization: SerSchema 

2781 

2782 

2783def chain_schema( 

2784 steps: list[CoreSchema], 

2785 *, 

2786 ref: str | None = None, 

2787 metadata: dict[str, Any] | None = None, 

2788 serialization: SerSchema | None = None, 

2789) -> ChainSchema: 

2790 """ 

2791 Returns a schema that chains the provided validation schemas, e.g.: 

2792 

2793 ```py 

2794 from pydantic_core import SchemaValidator, core_schema 

2795 

2796 def fn(v: str, info: core_schema.ValidationInfo) -> str: 

2797 assert 'hello' in v 

2798 return v + ' world' 

2799 

2800 fn_schema = core_schema.with_info_plain_validator_function(function=fn) 

2801 schema = core_schema.chain_schema( 

2802 [fn_schema, fn_schema, fn_schema, core_schema.str_schema()] 

2803 ) 

2804 v = SchemaValidator(schema) 

2805 assert v.validate_python('hello') == 'hello world world world' 

2806 ``` 

2807 

2808 Args: 

2809 steps: The schemas to chain 

2810 ref: optional unique identifier of the schema, used to reference the schema in other places 

2811 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2812 serialization: Custom serialization schema 

2813 """ 

2814 return _dict_not_none(type='chain', steps=steps, ref=ref, metadata=metadata, serialization=serialization) 

2815 

2816 

2817class LaxOrStrictSchema(TypedDict, total=False): 

2818 type: Required[Literal['lax-or-strict']] 

2819 lax_schema: Required[CoreSchema] 

2820 strict_schema: Required[CoreSchema] 

2821 strict: bool 

2822 ref: str 

2823 metadata: dict[str, Any] 

2824 serialization: SerSchema 

2825 

2826 

2827def lax_or_strict_schema( 

2828 lax_schema: CoreSchema, 

2829 strict_schema: CoreSchema, 

2830 *, 

2831 strict: bool | None = None, 

2832 ref: str | None = None, 

2833 metadata: dict[str, Any] | None = None, 

2834 serialization: SerSchema | None = None, 

2835) -> LaxOrStrictSchema: 

2836 """ 

2837 Returns a schema that uses the lax or strict schema, e.g.: 

2838 

2839 ```py 

2840 from pydantic_core import SchemaValidator, core_schema 

2841 

2842 def fn(v: str, info: core_schema.ValidationInfo) -> str: 

2843 assert 'hello' in v 

2844 return v + ' world' 

2845 

2846 lax_schema = core_schema.int_schema(strict=False) 

2847 strict_schema = core_schema.int_schema(strict=True) 

2848 

2849 schema = core_schema.lax_or_strict_schema( 

2850 lax_schema=lax_schema, strict_schema=strict_schema, strict=True 

2851 ) 

2852 v = SchemaValidator(schema) 

2853 assert v.validate_python(123) == 123 

2854 

2855 schema = core_schema.lax_or_strict_schema( 

2856 lax_schema=lax_schema, strict_schema=strict_schema, strict=False 

2857 ) 

2858 v = SchemaValidator(schema) 

2859 assert v.validate_python('123') == 123 

2860 ``` 

2861 

2862 Args: 

2863 lax_schema: The lax schema to use 

2864 strict_schema: The strict schema to use 

2865 strict: Whether the strict schema should be used 

2866 ref: optional unique identifier of the schema, used to reference the schema in other places 

2867 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2868 serialization: Custom serialization schema 

2869 """ 

2870 return _dict_not_none( 

2871 type='lax-or-strict', 

2872 lax_schema=lax_schema, 

2873 strict_schema=strict_schema, 

2874 strict=strict, 

2875 ref=ref, 

2876 metadata=metadata, 

2877 serialization=serialization, 

2878 ) 

2879 

2880 

2881class JsonOrPythonSchema(TypedDict, total=False): 

2882 type: Required[Literal['json-or-python']] 

2883 json_schema: Required[CoreSchema] 

2884 python_schema: Required[CoreSchema] 

2885 ref: str 

2886 metadata: dict[str, Any] 

2887 serialization: SerSchema 

2888 

2889 

2890def json_or_python_schema( 

2891 json_schema: CoreSchema, 

2892 python_schema: CoreSchema, 

2893 *, 

2894 ref: str | None = None, 

2895 metadata: dict[str, Any] | None = None, 

2896 serialization: SerSchema | None = None, 

2897) -> JsonOrPythonSchema: 

2898 """ 

2899 Returns a schema that uses the Json or Python schema depending on the input: 

2900 

2901 ```py 

2902 from pydantic_core import SchemaValidator, ValidationError, core_schema 

2903 

2904 v = SchemaValidator( 

2905 core_schema.json_or_python_schema( 

2906 json_schema=core_schema.int_schema(), 

2907 python_schema=core_schema.int_schema(strict=True), 

2908 ) 

2909 ) 

2910 

2911 assert v.validate_json('"123"') == 123 

2912 

2913 try: 

2914 v.validate_python('123') 

2915 except ValidationError: 

2916 pass 

2917 else: 

2918 raise AssertionError('Validation should have failed') 

2919 ``` 

2920 

2921 Args: 

2922 json_schema: The schema to use for Json inputs 

2923 python_schema: The schema to use for Python inputs 

2924 ref: optional unique identifier of the schema, used to reference the schema in other places 

2925 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2926 serialization: Custom serialization schema 

2927 """ 

2928 return _dict_not_none( 

2929 type='json-or-python', 

2930 json_schema=json_schema, 

2931 python_schema=python_schema, 

2932 ref=ref, 

2933 metadata=metadata, 

2934 serialization=serialization, 

2935 ) 

2936 

2937 

2938class TypedDictField(TypedDict, total=False): 

2939 type: Required[Literal['typed-dict-field']] 

2940 schema: Required[CoreSchema] 

2941 required: bool 

2942 validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]] 

2943 serialization_alias: str 

2944 serialization_exclude: bool # default: False 

2945 metadata: dict[str, Any] 

2946 serialization_exclude_if: Callable[[Any], bool] # default None 

2947 

2948 

2949def typed_dict_field( 

2950 schema: CoreSchema, 

2951 *, 

2952 required: bool | None = None, 

2953 validation_alias: str | list[str | int] | list[list[str | int]] | None = None, 

2954 serialization_alias: str | None = None, 

2955 serialization_exclude: bool | None = None, 

2956 metadata: dict[str, Any] | None = None, 

2957 serialization_exclude_if: Callable[[Any], bool] | None = None, 

2958) -> TypedDictField: 

2959 """ 

2960 Returns a schema that matches a typed dict field, e.g.: 

2961 

2962 ```py 

2963 from pydantic_core import core_schema 

2964 

2965 field = core_schema.typed_dict_field(schema=core_schema.int_schema(), required=True) 

2966 ``` 

2967 

2968 Args: 

2969 schema: The schema to use for the field 

2970 required: Whether the field is required, otherwise uses the value from `total` on the typed dict 

2971 validation_alias: The alias(es) to use to find the field in the validation data 

2972 serialization_alias: The alias to use as a key when serializing 

2973 serialization_exclude: Whether to exclude the field when serializing 

2974 serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value. 

2975 metadata: Any other information you want to include with the schema, not used by pydantic-core 

2976 """ 

2977 return _dict_not_none( 

2978 type='typed-dict-field', 

2979 schema=schema, 

2980 required=required, 

2981 validation_alias=validation_alias, 

2982 serialization_alias=serialization_alias, 

2983 serialization_exclude=serialization_exclude, 

2984 serialization_exclude_if=serialization_exclude_if, 

2985 metadata=metadata, 

2986 ) 

2987 

2988 

2989class TypedDictSchema(TypedDict, total=False): 

2990 type: Required[Literal['typed-dict']] 

2991 fields: Required[dict[str, TypedDictField]] 

2992 cls: type[Any] 

2993 cls_name: str 

2994 computed_fields: list[ComputedField] 

2995 strict: bool 

2996 extras_schema: CoreSchema 

2997 # all these values can be set via config, equivalent fields have `typed_dict_` prefix 

2998 extra_behavior: ExtraBehavior 

2999 total: bool # default: True 

3000 ref: str 

3001 metadata: dict[str, Any] 

3002 serialization: SerSchema 

3003 config: CoreConfig 

3004 

3005 

3006def typed_dict_schema( 

3007 fields: dict[str, TypedDictField], 

3008 *, 

3009 cls: type[Any] | None = None, 

3010 cls_name: str | None = None, 

3011 computed_fields: list[ComputedField] | None = None, 

3012 strict: bool | None = None, 

3013 extras_schema: CoreSchema | None = None, 

3014 extra_behavior: ExtraBehavior | None = None, 

3015 total: bool | None = None, 

3016 ref: str | None = None, 

3017 metadata: dict[str, Any] | None = None, 

3018 serialization: SerSchema | None = None, 

3019 config: CoreConfig | None = None, 

3020) -> TypedDictSchema: 

3021 """ 

3022 Returns a schema that matches a typed dict, e.g.: 

3023 

3024 ```py 

3025 from typing_extensions import TypedDict 

3026 

3027 from pydantic_core import SchemaValidator, core_schema 

3028 

3029 class MyTypedDict(TypedDict): 

3030 a: str 

3031 

3032 wrapper_schema = core_schema.typed_dict_schema( 

3033 {'a': core_schema.typed_dict_field(core_schema.str_schema())}, cls=MyTypedDict 

3034 ) 

3035 v = SchemaValidator(wrapper_schema) 

3036 assert v.validate_python({'a': 'hello'}) == {'a': 'hello'} 

3037 ``` 

3038 

3039 Args: 

3040 fields: The fields to use for the typed dict 

3041 cls: The class to use for the typed dict 

3042 cls_name: The name to use in error locations. Falls back to `cls.__name__`, or the validator name if no class 

3043 is provided. 

3044 computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model 

3045 strict: Whether the typed dict is strict 

3046 extras_schema: The extra validator to use for the typed dict 

3047 ref: optional unique identifier of the schema, used to reference the schema in other places 

3048 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3049 extra_behavior: The extra behavior to use for the typed dict 

3050 total: Whether the typed dict is total, otherwise uses `typed_dict_total` from config 

3051 serialization: Custom serialization schema 

3052 """ 

3053 return _dict_not_none( 

3054 type='typed-dict', 

3055 fields=fields, 

3056 cls=cls, 

3057 cls_name=cls_name, 

3058 computed_fields=computed_fields, 

3059 strict=strict, 

3060 extras_schema=extras_schema, 

3061 extra_behavior=extra_behavior, 

3062 total=total, 

3063 ref=ref, 

3064 metadata=metadata, 

3065 serialization=serialization, 

3066 config=config, 

3067 ) 

3068 

3069 

3070class ModelField(TypedDict, total=False): 

3071 type: Required[Literal['model-field']] 

3072 schema: Required[CoreSchema] 

3073 validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]] 

3074 serialization_alias: str 

3075 serialization_exclude: bool # default: False 

3076 serialization_exclude_if: Callable[[Any], bool] # default: None 

3077 frozen: bool 

3078 metadata: dict[str, Any] 

3079 

3080 

3081def model_field( 

3082 schema: CoreSchema, 

3083 *, 

3084 validation_alias: str | list[str | int] | list[list[str | int]] | None = None, 

3085 serialization_alias: str | None = None, 

3086 serialization_exclude: bool | None = None, 

3087 serialization_exclude_if: Callable[[Any], bool] | None = None, 

3088 frozen: bool | None = None, 

3089 metadata: dict[str, Any] | None = None, 

3090) -> ModelField: 

3091 """ 

3092 Returns a schema for a model field, e.g.: 

3093 

3094 ```py 

3095 from pydantic_core import core_schema 

3096 

3097 field = core_schema.model_field(schema=core_schema.int_schema()) 

3098 ``` 

3099 

3100 Args: 

3101 schema: The schema to use for the field 

3102 validation_alias: The alias(es) to use to find the field in the validation data 

3103 serialization_alias: The alias to use as a key when serializing 

3104 serialization_exclude: Whether to exclude the field when serializing 

3105 serialization_exclude_if: A Callable that determines whether to exclude a field during serialization based on its value. 

3106 frozen: Whether the field is frozen 

3107 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3108 """ 

3109 return _dict_not_none( 

3110 type='model-field', 

3111 schema=schema, 

3112 validation_alias=validation_alias, 

3113 serialization_alias=serialization_alias, 

3114 serialization_exclude=serialization_exclude, 

3115 serialization_exclude_if=serialization_exclude_if, 

3116 frozen=frozen, 

3117 metadata=metadata, 

3118 ) 

3119 

3120 

3121class ModelFieldsSchema(TypedDict, total=False): 

3122 type: Required[Literal['model-fields']] 

3123 fields: Required[dict[str, ModelField]] 

3124 model_name: str 

3125 computed_fields: list[ComputedField] 

3126 strict: bool 

3127 extras_schema: CoreSchema 

3128 extras_keys_schema: CoreSchema 

3129 extra_behavior: ExtraBehavior 

3130 from_attributes: bool 

3131 ref: str 

3132 metadata: dict[str, Any] 

3133 serialization: SerSchema 

3134 

3135 

3136def model_fields_schema( 

3137 fields: dict[str, ModelField], 

3138 *, 

3139 model_name: str | None = None, 

3140 computed_fields: list[ComputedField] | None = None, 

3141 strict: bool | None = None, 

3142 extras_schema: CoreSchema | None = None, 

3143 extras_keys_schema: CoreSchema | None = None, 

3144 extra_behavior: ExtraBehavior | None = None, 

3145 from_attributes: bool | None = None, 

3146 ref: str | None = None, 

3147 metadata: dict[str, Any] | None = None, 

3148 serialization: SerSchema | None = None, 

3149) -> ModelFieldsSchema: 

3150 """ 

3151 Returns a schema that matches the fields of a Pydantic model, e.g.: 

3152 

3153 ```py 

3154 from pydantic_core import SchemaValidator, core_schema 

3155 

3156 wrapper_schema = core_schema.model_fields_schema( 

3157 {'a': core_schema.model_field(core_schema.str_schema())} 

3158 ) 

3159 v = SchemaValidator(wrapper_schema) 

3160 print(v.validate_python({'a': 'hello'})) 

3161 #> ({'a': 'hello'}, None, {'a'}) 

3162 ``` 

3163 

3164 Args: 

3165 fields: The fields of the model 

3166 model_name: The name of the model, used for error messages, defaults to "Model" 

3167 computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model 

3168 strict: Whether the model is strict 

3169 extras_schema: The schema to use when validating extra input data 

3170 extras_keys_schema: The schema to use when validating the keys of extra input data 

3171 ref: optional unique identifier of the schema, used to reference the schema in other places 

3172 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3173 extra_behavior: The extra behavior to use for the model fields 

3174 from_attributes: Whether the model fields should be populated from attributes 

3175 serialization: Custom serialization schema 

3176 """ 

3177 return _dict_not_none( 

3178 type='model-fields', 

3179 fields=fields, 

3180 model_name=model_name, 

3181 computed_fields=computed_fields, 

3182 strict=strict, 

3183 extras_schema=extras_schema, 

3184 extras_keys_schema=extras_keys_schema, 

3185 extra_behavior=extra_behavior, 

3186 from_attributes=from_attributes, 

3187 ref=ref, 

3188 metadata=metadata, 

3189 serialization=serialization, 

3190 ) 

3191 

3192 

3193class ModelSchema(TypedDict, total=False): 

3194 type: Required[Literal['model']] 

3195 cls: Required[type[Any]] 

3196 generic_origin: type[Any] 

3197 schema: Required[CoreSchema] 

3198 custom_init: bool 

3199 root_model: bool 

3200 post_init: str 

3201 revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never' 

3202 strict: bool 

3203 frozen: bool 

3204 extra_behavior: ExtraBehavior 

3205 config: CoreConfig 

3206 ref: str 

3207 metadata: dict[str, Any] 

3208 serialization: SerSchema 

3209 

3210 

3211def model_schema( 

3212 cls: type[Any], 

3213 schema: CoreSchema, 

3214 *, 

3215 generic_origin: type[Any] | None = None, 

3216 custom_init: bool | None = None, 

3217 root_model: bool | None = None, 

3218 post_init: str | None = None, 

3219 revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None, 

3220 strict: bool | None = None, 

3221 frozen: bool | None = None, 

3222 extra_behavior: ExtraBehavior | None = None, 

3223 config: CoreConfig | None = None, 

3224 ref: str | None = None, 

3225 metadata: dict[str, Any] | None = None, 

3226 serialization: SerSchema | None = None, 

3227) -> ModelSchema: 

3228 """ 

3229 A model schema generally contains a typed-dict schema. 

3230 It will run the typed dict validator, then create a new class 

3231 and set the dict and fields set returned from the typed dict validator 

3232 to `__dict__` and `__pydantic_fields_set__` respectively. 

3233 

3234 Example: 

3235 

3236 ```py 

3237 from pydantic_core import CoreConfig, SchemaValidator, core_schema 

3238 

3239 class MyModel: 

3240 __slots__ = ( 

3241 '__dict__', 

3242 '__pydantic_fields_set__', 

3243 '__pydantic_extra__', 

3244 '__pydantic_private__', 

3245 ) 

3246 

3247 schema = core_schema.model_schema( 

3248 cls=MyModel, 

3249 config=CoreConfig(str_max_length=5), 

3250 schema=core_schema.model_fields_schema( 

3251 fields={'a': core_schema.model_field(core_schema.str_schema())}, 

3252 ), 

3253 ) 

3254 v = SchemaValidator(schema) 

3255 assert v.isinstance_python({'a': 'hello'}) is True 

3256 assert v.isinstance_python({'a': 'too long'}) is False 

3257 ``` 

3258 

3259 Args: 

3260 cls: The class to use for the model 

3261 schema: The schema to use for the model 

3262 generic_origin: The origin type used for this model, if it's a parametrized generic. Ex, 

3263 if this model schema represents `SomeModel[int]`, generic_origin is `SomeModel` 

3264 custom_init: Whether the model has a custom init method 

3265 root_model: Whether the model is a `RootModel` 

3266 post_init: The call after init to use for the model 

3267 revalidate_instances: whether instances of models and dataclasses (including subclass instances) 

3268 should re-validate defaults to config.revalidate_instances, else 'never' 

3269 strict: Whether the model is strict 

3270 frozen: Whether the model is frozen 

3271 extra_behavior: The extra behavior to use for the model, used in serialization 

3272 config: The config to use for the model 

3273 ref: optional unique identifier of the schema, used to reference the schema in other places 

3274 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3275 serialization: Custom serialization schema 

3276 """ 

3277 return _dict_not_none( 

3278 type='model', 

3279 cls=cls, 

3280 generic_origin=generic_origin, 

3281 schema=schema, 

3282 custom_init=custom_init, 

3283 root_model=root_model, 

3284 post_init=post_init, 

3285 revalidate_instances=revalidate_instances, 

3286 strict=strict, 

3287 frozen=frozen, 

3288 extra_behavior=extra_behavior, 

3289 config=config, 

3290 ref=ref, 

3291 metadata=metadata, 

3292 serialization=serialization, 

3293 ) 

3294 

3295 

3296class DataclassField(TypedDict, total=False): 

3297 type: Required[Literal['dataclass-field']] 

3298 name: Required[str] 

3299 schema: Required[CoreSchema] 

3300 kw_only: bool # default: True 

3301 init: bool # default: True 

3302 init_only: bool # default: False 

3303 frozen: bool # default: False 

3304 validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]] 

3305 serialization_alias: str 

3306 serialization_exclude: bool # default: False 

3307 metadata: dict[str, Any] 

3308 serialization_exclude_if: Callable[[Any], bool] # default: None 

3309 

3310 

3311def dataclass_field( 

3312 name: str, 

3313 schema: CoreSchema, 

3314 *, 

3315 kw_only: bool | None = None, 

3316 init: bool | None = None, 

3317 init_only: bool | None = None, 

3318 validation_alias: str | list[str | int] | list[list[str | int]] | None = None, 

3319 serialization_alias: str | None = None, 

3320 serialization_exclude: bool | None = None, 

3321 metadata: dict[str, Any] | None = None, 

3322 serialization_exclude_if: Callable[[Any], bool] | None = None, 

3323 frozen: bool | None = None, 

3324) -> DataclassField: 

3325 """ 

3326 Returns a schema for a dataclass field, e.g.: 

3327 

3328 ```py 

3329 from pydantic_core import SchemaValidator, core_schema 

3330 

3331 field = core_schema.dataclass_field( 

3332 name='a', schema=core_schema.str_schema(), kw_only=False 

3333 ) 

3334 schema = core_schema.dataclass_args_schema('Foobar', [field]) 

3335 v = SchemaValidator(schema) 

3336 assert v.validate_python({'a': 'hello'}) == ({'a': 'hello'}, None) 

3337 ``` 

3338 

3339 Args: 

3340 name: The name to use for the argument parameter 

3341 schema: The schema to use for the argument parameter 

3342 kw_only: Whether the field can be set with a positional argument as well as a keyword argument 

3343 init: Whether the field should be validated during initialization 

3344 init_only: Whether the field should be omitted from `__dict__` and passed to `__post_init__` 

3345 validation_alias: The alias(es) to use to find the field in the validation data 

3346 serialization_alias: The alias to use as a key when serializing 

3347 serialization_exclude: Whether to exclude the field when serializing 

3348 serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value. 

3349 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3350 frozen: Whether the field is frozen 

3351 """ 

3352 return _dict_not_none( 

3353 type='dataclass-field', 

3354 name=name, 

3355 schema=schema, 

3356 kw_only=kw_only, 

3357 init=init, 

3358 init_only=init_only, 

3359 validation_alias=validation_alias, 

3360 serialization_alias=serialization_alias, 

3361 serialization_exclude=serialization_exclude, 

3362 serialization_exclude_if=serialization_exclude_if, 

3363 metadata=metadata, 

3364 frozen=frozen, 

3365 ) 

3366 

3367 

3368class DataclassArgsSchema(TypedDict, total=False): 

3369 type: Required[Literal['dataclass-args']] 

3370 dataclass_name: Required[str] 

3371 fields: Required[list[DataclassField]] 

3372 computed_fields: list[ComputedField] 

3373 collect_init_only: bool # default: False 

3374 ref: str 

3375 metadata: dict[str, Any] 

3376 serialization: SerSchema 

3377 extra_behavior: ExtraBehavior 

3378 

3379 

3380def dataclass_args_schema( 

3381 dataclass_name: str, 

3382 fields: list[DataclassField], 

3383 *, 

3384 computed_fields: list[ComputedField] | None = None, 

3385 collect_init_only: bool | None = None, 

3386 ref: str | None = None, 

3387 metadata: dict[str, Any] | None = None, 

3388 serialization: SerSchema | None = None, 

3389 extra_behavior: ExtraBehavior | None = None, 

3390) -> DataclassArgsSchema: 

3391 """ 

3392 Returns a schema for validating dataclass arguments, e.g.: 

3393 

3394 ```py 

3395 from pydantic_core import SchemaValidator, core_schema 

3396 

3397 field_a = core_schema.dataclass_field( 

3398 name='a', schema=core_schema.str_schema(), kw_only=False 

3399 ) 

3400 field_b = core_schema.dataclass_field( 

3401 name='b', schema=core_schema.bool_schema(), kw_only=False 

3402 ) 

3403 schema = core_schema.dataclass_args_schema('Foobar', [field_a, field_b]) 

3404 v = SchemaValidator(schema) 

3405 assert v.validate_python({'a': 'hello', 'b': True}) == ({'a': 'hello', 'b': True}, None) 

3406 ``` 

3407 

3408 Args: 

3409 dataclass_name: The name of the dataclass being validated 

3410 fields: The fields to use for the dataclass 

3411 computed_fields: Computed fields to use when serializing the dataclass 

3412 collect_init_only: Whether to collect init only fields into a dict to pass to `__post_init__` 

3413 ref: optional unique identifier of the schema, used to reference the schema in other places 

3414 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3415 serialization: Custom serialization schema 

3416 extra_behavior: How to handle extra fields 

3417 """ 

3418 return _dict_not_none( 

3419 type='dataclass-args', 

3420 dataclass_name=dataclass_name, 

3421 fields=fields, 

3422 computed_fields=computed_fields, 

3423 collect_init_only=collect_init_only, 

3424 ref=ref, 

3425 metadata=metadata, 

3426 serialization=serialization, 

3427 extra_behavior=extra_behavior, 

3428 ) 

3429 

3430 

3431class DataclassSchema(TypedDict, total=False): 

3432 type: Required[Literal['dataclass']] 

3433 cls: Required[type[Any]] 

3434 generic_origin: type[Any] 

3435 schema: Required[CoreSchema] 

3436 fields: Required[list[str]] 

3437 cls_name: str 

3438 post_init: bool # default: False 

3439 revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never' 

3440 strict: bool # default: False 

3441 frozen: bool # default False 

3442 ref: str 

3443 metadata: dict[str, Any] 

3444 serialization: SerSchema 

3445 slots: bool 

3446 config: CoreConfig 

3447 

3448 

3449def dataclass_schema( 

3450 cls: type[Any], 

3451 schema: CoreSchema, 

3452 fields: list[str], 

3453 *, 

3454 generic_origin: type[Any] | None = None, 

3455 cls_name: str | None = None, 

3456 post_init: bool | None = None, 

3457 revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None, 

3458 strict: bool | None = None, 

3459 ref: str | None = None, 

3460 metadata: dict[str, Any] | None = None, 

3461 serialization: SerSchema | None = None, 

3462 frozen: bool | None = None, 

3463 slots: bool | None = None, 

3464 config: CoreConfig | None = None, 

3465) -> DataclassSchema: 

3466 """ 

3467 Returns a schema for a dataclass. As with `ModelSchema`, this schema can only be used as a field within 

3468 another schema, not as the root type. 

3469 

3470 Args: 

3471 cls: The dataclass type, used to perform subclass checks 

3472 schema: The schema to use for the dataclass fields 

3473 fields: Fields of the dataclass, this is used in serialization and in validation during re-validation 

3474 and while validating assignment 

3475 generic_origin: The origin type used for this dataclass, if it's a parametrized generic. Ex, 

3476 if this model schema represents `SomeDataclass[int]`, generic_origin is `SomeDataclass` 

3477 cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`) 

3478 post_init: Whether to call `__post_init__` after validation 

3479 revalidate_instances: whether instances of models and dataclasses (including subclass instances) 

3480 should re-validate defaults to config.revalidate_instances, else 'never' 

3481 strict: Whether to require an exact instance of `cls` 

3482 ref: optional unique identifier of the schema, used to reference the schema in other places 

3483 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3484 serialization: Custom serialization schema 

3485 frozen: Whether the dataclass is frozen 

3486 slots: Whether `slots=True` on the dataclass, means each field is assigned independently, rather than 

3487 simply setting `__dict__`, default false 

3488 """ 

3489 return _dict_not_none( 

3490 type='dataclass', 

3491 cls=cls, 

3492 generic_origin=generic_origin, 

3493 fields=fields, 

3494 cls_name=cls_name, 

3495 schema=schema, 

3496 post_init=post_init, 

3497 revalidate_instances=revalidate_instances, 

3498 strict=strict, 

3499 ref=ref, 

3500 metadata=metadata, 

3501 serialization=serialization, 

3502 frozen=frozen, 

3503 slots=slots, 

3504 config=config, 

3505 ) 

3506 

3507 

3508class ArgumentsParameter(TypedDict, total=False): 

3509 name: Required[str] 

3510 schema: Required[CoreSchema] 

3511 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] # default positional_or_keyword 

3512 alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]] 

3513 

3514 

3515def arguments_parameter( 

3516 name: str, 

3517 schema: CoreSchema, 

3518 *, 

3519 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None, 

3520 alias: str | list[str | int] | list[list[str | int]] | None = None, 

3521) -> ArgumentsParameter: 

3522 """ 

3523 Returns a schema that matches an argument parameter, e.g.: 

3524 

3525 ```py 

3526 from pydantic_core import SchemaValidator, core_schema 

3527 

3528 param = core_schema.arguments_parameter( 

3529 name='a', schema=core_schema.str_schema(), mode='positional_only' 

3530 ) 

3531 schema = core_schema.arguments_schema([param]) 

3532 v = SchemaValidator(schema) 

3533 assert v.validate_python(('hello',)) == (('hello',), {}) 

3534 ``` 

3535 

3536 Args: 

3537 name: The name to use for the argument parameter 

3538 schema: The schema to use for the argument parameter 

3539 mode: The mode to use for the argument parameter 

3540 alias: The alias to use for the argument parameter 

3541 """ 

3542 return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias) 

3543 

3544 

3545VarKwargsMode: TypeAlias = Literal['uniform', 'unpacked-typed-dict'] 

3546 

3547 

3548class ArgumentsSchema(TypedDict, total=False): 

3549 type: Required[Literal['arguments']] 

3550 arguments_schema: Required[list[ArgumentsParameter]] 

3551 validate_by_name: bool 

3552 validate_by_alias: bool 

3553 var_args_schema: CoreSchema 

3554 var_kwargs_mode: VarKwargsMode 

3555 var_kwargs_schema: CoreSchema 

3556 ref: str 

3557 metadata: dict[str, Any] 

3558 serialization: SerSchema 

3559 

3560 

3561def arguments_schema( 

3562 arguments: list[ArgumentsParameter], 

3563 *, 

3564 validate_by_name: bool | None = None, 

3565 validate_by_alias: bool | None = None, 

3566 var_args_schema: CoreSchema | None = None, 

3567 var_kwargs_mode: VarKwargsMode | None = None, 

3568 var_kwargs_schema: CoreSchema | None = None, 

3569 ref: str | None = None, 

3570 metadata: dict[str, Any] | None = None, 

3571 serialization: SerSchema | None = None, 

3572) -> ArgumentsSchema: 

3573 """ 

3574 Returns a schema that matches an arguments schema, e.g.: 

3575 

3576 ```py 

3577 from pydantic_core import SchemaValidator, core_schema 

3578 

3579 param_a = core_schema.arguments_parameter( 

3580 name='a', schema=core_schema.str_schema(), mode='positional_only' 

3581 ) 

3582 param_b = core_schema.arguments_parameter( 

3583 name='b', schema=core_schema.bool_schema(), mode='positional_only' 

3584 ) 

3585 schema = core_schema.arguments_schema([param_a, param_b]) 

3586 v = SchemaValidator(schema) 

3587 assert v.validate_python(('hello', True)) == (('hello', True), {}) 

3588 ``` 

3589 

3590 Args: 

3591 arguments: The arguments to use for the arguments schema 

3592 validate_by_name: Whether to populate by the parameter names, defaults to `False`. 

3593 validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`. 

3594 var_args_schema: The variable args schema to use for the arguments schema 

3595 var_kwargs_mode: The validation mode to use for variadic keyword arguments. If `'uniform'`, every value of the 

3596 keyword arguments will be validated against the `var_kwargs_schema` schema. If `'unpacked-typed-dict'`, 

3597 the `var_kwargs_schema` argument must be a [`typed_dict_schema`][pydantic_core.core_schema.typed_dict_schema] 

3598 var_kwargs_schema: The variable kwargs schema to use for the arguments schema 

3599 ref: optional unique identifier of the schema, used to reference the schema in other places 

3600 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3601 serialization: Custom serialization schema 

3602 """ 

3603 return _dict_not_none( 

3604 type='arguments', 

3605 arguments_schema=arguments, 

3606 validate_by_name=validate_by_name, 

3607 validate_by_alias=validate_by_alias, 

3608 var_args_schema=var_args_schema, 

3609 var_kwargs_mode=var_kwargs_mode, 

3610 var_kwargs_schema=var_kwargs_schema, 

3611 ref=ref, 

3612 metadata=metadata, 

3613 serialization=serialization, 

3614 ) 

3615 

3616 

3617class ArgumentsV3Parameter(TypedDict, total=False): 

3618 name: Required[str] 

3619 schema: Required[CoreSchema] 

3620 mode: Literal[ 

3621 'positional_only', 

3622 'positional_or_keyword', 

3623 'keyword_only', 

3624 'var_args', 

3625 'var_kwargs_uniform', 

3626 'var_kwargs_unpacked_typed_dict', 

3627 ] # default positional_or_keyword 

3628 alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]] 

3629 

3630 

3631def arguments_v3_parameter( 

3632 name: str, 

3633 schema: CoreSchema, 

3634 *, 

3635 mode: Literal[ 

3636 'positional_only', 

3637 'positional_or_keyword', 

3638 'keyword_only', 

3639 'var_args', 

3640 'var_kwargs_uniform', 

3641 'var_kwargs_unpacked_typed_dict', 

3642 ] 

3643 | None = None, 

3644 alias: str | list[str | int] | list[list[str | int]] | None = None, 

3645) -> ArgumentsV3Parameter: 

3646 """ 

3647 Returns a schema that matches an argument parameter, e.g.: 

3648 

3649 ```py 

3650 from pydantic_core import SchemaValidator, core_schema 

3651 

3652 param = core_schema.arguments_v3_parameter( 

3653 name='a', schema=core_schema.str_schema(), mode='positional_only' 

3654 ) 

3655 schema = core_schema.arguments_v3_schema([param]) 

3656 v = SchemaValidator(schema) 

3657 assert v.validate_python({'a': 'hello'}) == (('hello',), {}) 

3658 ``` 

3659 

3660 Args: 

3661 name: The name to use for the argument parameter 

3662 schema: The schema to use for the argument parameter 

3663 mode: The mode to use for the argument parameter 

3664 alias: The alias to use for the argument parameter 

3665 """ 

3666 return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias) 

3667 

3668 

3669class ArgumentsV3Schema(TypedDict, total=False): 

3670 type: Required[Literal['arguments-v3']] 

3671 arguments_schema: Required[list[ArgumentsV3Parameter]] 

3672 validate_by_name: bool 

3673 validate_by_alias: bool 

3674 extra_behavior: Literal['forbid', 'ignore'] # 'allow' doesn't make sense here. 

3675 ref: str 

3676 metadata: dict[str, Any] 

3677 serialization: SerSchema 

3678 

3679 

3680def arguments_v3_schema( 

3681 arguments: list[ArgumentsV3Parameter], 

3682 *, 

3683 validate_by_name: bool | None = None, 

3684 validate_by_alias: bool | None = None, 

3685 extra_behavior: Literal['forbid', 'ignore'] | None = None, 

3686 ref: str | None = None, 

3687 metadata: dict[str, Any] | None = None, 

3688 serialization: SerSchema | None = None, 

3689) -> ArgumentsV3Schema: 

3690 """ 

3691 Returns a schema that matches an arguments schema, e.g.: 

3692 

3693 ```py 

3694 from pydantic_core import SchemaValidator, core_schema 

3695 

3696 param_a = core_schema.arguments_v3_parameter( 

3697 name='a', schema=core_schema.str_schema(), mode='positional_only' 

3698 ) 

3699 param_b = core_schema.arguments_v3_parameter( 

3700 name='kwargs', schema=core_schema.bool_schema(), mode='var_kwargs_uniform' 

3701 ) 

3702 schema = core_schema.arguments_v3_schema([param_a, param_b]) 

3703 v = SchemaValidator(schema) 

3704 assert v.validate_python({'a': 'hi', 'kwargs': {'b': True}}) == (('hi',), {'b': True}) 

3705 ``` 

3706 

3707 This schema is currently not used by other Pydantic components. In V3, it will most likely 

3708 become the default arguments schema for the `'call'` schema. 

3709 

3710 Args: 

3711 arguments: The arguments to use for the arguments schema. 

3712 validate_by_name: Whether to populate by the parameter names, defaults to `False`. 

3713 validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`. 

3714 extra_behavior: The extra behavior to use. 

3715 ref: optional unique identifier of the schema, used to reference the schema in other places. 

3716 metadata: Any other information you want to include with the schema, not used by pydantic-core. 

3717 serialization: Custom serialization schema. 

3718 """ 

3719 return _dict_not_none( 

3720 type='arguments-v3', 

3721 arguments_schema=arguments, 

3722 validate_by_name=validate_by_name, 

3723 validate_by_alias=validate_by_alias, 

3724 extra_behavior=extra_behavior, 

3725 ref=ref, 

3726 metadata=metadata, 

3727 serialization=serialization, 

3728 ) 

3729 

3730 

3731class CallSchema(TypedDict, total=False): 

3732 type: Required[Literal['call']] 

3733 arguments_schema: Required[CoreSchema] 

3734 function: Required[Callable[..., Any]] 

3735 function_name: str # default function.__name__ 

3736 return_schema: CoreSchema 

3737 ref: str 

3738 metadata: dict[str, Any] 

3739 serialization: SerSchema 

3740 

3741 

3742def call_schema( 

3743 arguments: CoreSchema, 

3744 function: Callable[..., Any], 

3745 *, 

3746 function_name: str | None = None, 

3747 return_schema: CoreSchema | None = None, 

3748 ref: str | None = None, 

3749 metadata: dict[str, Any] | None = None, 

3750 serialization: SerSchema | None = None, 

3751) -> CallSchema: 

3752 """ 

3753 Returns a schema that matches an arguments schema, then calls a function, e.g.: 

3754 

3755 ```py 

3756 from pydantic_core import SchemaValidator, core_schema 

3757 

3758 param_a = core_schema.arguments_parameter( 

3759 name='a', schema=core_schema.str_schema(), mode='positional_only' 

3760 ) 

3761 param_b = core_schema.arguments_parameter( 

3762 name='b', schema=core_schema.bool_schema(), mode='positional_only' 

3763 ) 

3764 args_schema = core_schema.arguments_schema([param_a, param_b]) 

3765 

3766 schema = core_schema.call_schema( 

3767 arguments=args_schema, 

3768 function=lambda a, b: a + str(not b), 

3769 return_schema=core_schema.str_schema(), 

3770 ) 

3771 v = SchemaValidator(schema) 

3772 assert v.validate_python((('hello', True))) == 'helloFalse' 

3773 ``` 

3774 

3775 Args: 

3776 arguments: The arguments to use for the arguments schema 

3777 function: The function to use for the call schema 

3778 function_name: The function name to use for the call schema, if not provided `function.__name__` is used 

3779 return_schema: The return schema to use for the call schema 

3780 ref: optional unique identifier of the schema, used to reference the schema in other places 

3781 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3782 serialization: Custom serialization schema 

3783 """ 

3784 return _dict_not_none( 

3785 type='call', 

3786 arguments_schema=arguments, 

3787 function=function, 

3788 function_name=function_name, 

3789 return_schema=return_schema, 

3790 ref=ref, 

3791 metadata=metadata, 

3792 serialization=serialization, 

3793 ) 

3794 

3795 

3796class CustomErrorSchema(TypedDict, total=False): 

3797 type: Required[Literal['custom-error']] 

3798 schema: Required[CoreSchema] 

3799 custom_error_type: Required[str] 

3800 custom_error_message: str 

3801 custom_error_context: dict[str, Union[str, int, float]] 

3802 ref: str 

3803 metadata: dict[str, Any] 

3804 serialization: SerSchema 

3805 

3806 

3807def custom_error_schema( 

3808 schema: CoreSchema, 

3809 custom_error_type: str, 

3810 *, 

3811 custom_error_message: str | None = None, 

3812 custom_error_context: dict[str, Any] | None = None, 

3813 ref: str | None = None, 

3814 metadata: dict[str, Any] | None = None, 

3815 serialization: SerSchema | None = None, 

3816) -> CustomErrorSchema: 

3817 """ 

3818 Returns a schema that matches a custom error value, e.g.: 

3819 

3820 ```py 

3821 from pydantic_core import SchemaValidator, core_schema 

3822 

3823 schema = core_schema.custom_error_schema( 

3824 schema=core_schema.int_schema(), 

3825 custom_error_type='MyError', 

3826 custom_error_message='Error msg', 

3827 ) 

3828 v = SchemaValidator(schema) 

3829 v.validate_python(1) 

3830 ``` 

3831 

3832 Args: 

3833 schema: The schema to use for the custom error schema 

3834 custom_error_type: The custom error type to use for the custom error schema 

3835 custom_error_message: The custom error message to use for the custom error schema 

3836 custom_error_context: The custom error context to use for the custom error schema 

3837 ref: optional unique identifier of the schema, used to reference the schema in other places 

3838 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3839 serialization: Custom serialization schema 

3840 """ 

3841 return _dict_not_none( 

3842 type='custom-error', 

3843 schema=schema, 

3844 custom_error_type=custom_error_type, 

3845 custom_error_message=custom_error_message, 

3846 custom_error_context=custom_error_context, 

3847 ref=ref, 

3848 metadata=metadata, 

3849 serialization=serialization, 

3850 ) 

3851 

3852 

3853class JsonSchema(TypedDict, total=False): 

3854 type: Required[Literal['json']] 

3855 schema: CoreSchema 

3856 ref: str 

3857 metadata: dict[str, Any] 

3858 serialization: SerSchema 

3859 

3860 

3861def json_schema( 

3862 schema: CoreSchema | None = None, 

3863 *, 

3864 ref: str | None = None, 

3865 metadata: dict[str, Any] | None = None, 

3866 serialization: SerSchema | None = None, 

3867) -> JsonSchema: 

3868 """ 

3869 Returns a schema that matches a JSON value, e.g.: 

3870 

3871 ```py 

3872 from pydantic_core import SchemaValidator, core_schema 

3873 

3874 dict_schema = core_schema.model_fields_schema( 

3875 { 

3876 'field_a': core_schema.model_field(core_schema.str_schema()), 

3877 'field_b': core_schema.model_field(core_schema.bool_schema()), 

3878 }, 

3879 ) 

3880 

3881 class MyModel: 

3882 __slots__ = ( 

3883 '__dict__', 

3884 '__pydantic_fields_set__', 

3885 '__pydantic_extra__', 

3886 '__pydantic_private__', 

3887 ) 

3888 field_a: str 

3889 field_b: bool 

3890 

3891 json_schema = core_schema.json_schema(schema=dict_schema) 

3892 schema = core_schema.model_schema(cls=MyModel, schema=json_schema) 

3893 v = SchemaValidator(schema) 

3894 m = v.validate_python('{"field_a": "hello", "field_b": true}') 

3895 assert isinstance(m, MyModel) 

3896 ``` 

3897 

3898 Args: 

3899 schema: The schema to use for the JSON schema 

3900 ref: optional unique identifier of the schema, used to reference the schema in other places 

3901 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3902 serialization: Custom serialization schema 

3903 """ 

3904 return _dict_not_none(type='json', schema=schema, ref=ref, metadata=metadata, serialization=serialization) 

3905 

3906 

3907class UrlSchema(TypedDict, total=False): 

3908 type: Required[Literal['url']] 

3909 max_length: int 

3910 allowed_schemes: list[str] 

3911 host_required: bool # default False 

3912 default_host: str 

3913 default_port: int 

3914 default_path: str 

3915 strict: bool 

3916 ref: str 

3917 metadata: dict[str, Any] 

3918 serialization: SerSchema 

3919 

3920 

3921def url_schema( 

3922 *, 

3923 max_length: int | None = None, 

3924 allowed_schemes: list[str] | None = None, 

3925 host_required: bool | None = None, 

3926 default_host: str | None = None, 

3927 default_port: int | None = None, 

3928 default_path: str | None = None, 

3929 preserve_empty_path: bool | None = None, 

3930 strict: bool | None = None, 

3931 ref: str | None = None, 

3932 metadata: dict[str, Any] | None = None, 

3933 serialization: SerSchema | None = None, 

3934) -> UrlSchema: 

3935 """ 

3936 Returns a schema that matches a URL value, e.g.: 

3937 

3938 ```py 

3939 from pydantic_core import SchemaValidator, core_schema 

3940 

3941 schema = core_schema.url_schema() 

3942 v = SchemaValidator(schema) 

3943 print(v.validate_python('https://example.com')) 

3944 #> https://example.com/ 

3945 ``` 

3946 

3947 Args: 

3948 max_length: The maximum length of the URL 

3949 allowed_schemes: The allowed URL schemes 

3950 host_required: Whether the URL must have a host 

3951 default_host: The default host to use if the URL does not have a host 

3952 default_port: The default port to use if the URL does not have a port 

3953 default_path: The default path to use if the URL does not have a path 

3954 preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False 

3955 strict: Whether to use strict URL parsing 

3956 ref: optional unique identifier of the schema, used to reference the schema in other places 

3957 metadata: Any other information you want to include with the schema, not used by pydantic-core 

3958 serialization: Custom serialization schema 

3959 """ 

3960 return _dict_not_none( 

3961 type='url', 

3962 max_length=max_length, 

3963 allowed_schemes=allowed_schemes, 

3964 host_required=host_required, 

3965 default_host=default_host, 

3966 default_port=default_port, 

3967 default_path=default_path, 

3968 preserve_empty_path=preserve_empty_path, 

3969 strict=strict, 

3970 ref=ref, 

3971 metadata=metadata, 

3972 serialization=serialization, 

3973 ) 

3974 

3975 

3976class MultiHostUrlSchema(TypedDict, total=False): 

3977 type: Required[Literal['multi-host-url']] 

3978 max_length: int 

3979 allowed_schemes: list[str] 

3980 host_required: bool # default False 

3981 default_host: str 

3982 default_port: int 

3983 default_path: str 

3984 strict: bool 

3985 ref: str 

3986 metadata: dict[str, Any] 

3987 serialization: SerSchema 

3988 

3989 

3990def multi_host_url_schema( 

3991 *, 

3992 max_length: int | None = None, 

3993 allowed_schemes: list[str] | None = None, 

3994 host_required: bool | None = None, 

3995 default_host: str | None = None, 

3996 default_port: int | None = None, 

3997 default_path: str | None = None, 

3998 preserve_empty_path: bool | None = None, 

3999 strict: bool | None = None, 

4000 ref: str | None = None, 

4001 metadata: dict[str, Any] | None = None, 

4002 serialization: SerSchema | None = None, 

4003) -> MultiHostUrlSchema: 

4004 """ 

4005 Returns a schema that matches a URL value with possibly multiple hosts, e.g.: 

4006 

4007 ```py 

4008 from pydantic_core import SchemaValidator, core_schema 

4009 

4010 schema = core_schema.multi_host_url_schema() 

4011 v = SchemaValidator(schema) 

4012 print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1')) 

4013 #> redis://localhost,0.0.0.0,127.0.0.1 

4014 ``` 

4015 

4016 Args: 

4017 max_length: The maximum length of the URL 

4018 allowed_schemes: The allowed URL schemes 

4019 host_required: Whether the URL must have a host 

4020 default_host: The default host to use if the URL does not have a host 

4021 default_port: The default port to use if the URL does not have a port 

4022 default_path: The default path to use if the URL does not have a path 

4023 preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False 

4024 strict: Whether to use strict URL parsing 

4025 ref: optional unique identifier of the schema, used to reference the schema in other places 

4026 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4027 serialization: Custom serialization schema 

4028 """ 

4029 return _dict_not_none( 

4030 type='multi-host-url', 

4031 max_length=max_length, 

4032 allowed_schemes=allowed_schemes, 

4033 host_required=host_required, 

4034 default_host=default_host, 

4035 default_port=default_port, 

4036 default_path=default_path, 

4037 preserve_empty_path=preserve_empty_path, 

4038 strict=strict, 

4039 ref=ref, 

4040 metadata=metadata, 

4041 serialization=serialization, 

4042 ) 

4043 

4044 

4045class DefinitionsSchema(TypedDict, total=False): 

4046 type: Required[Literal['definitions']] 

4047 schema: Required[CoreSchema] 

4048 definitions: Required[list[CoreSchema]] 

4049 metadata: dict[str, Any] 

4050 serialization: SerSchema 

4051 

4052 

4053def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema: 

4054 """ 

4055 Build a schema that contains both an inner schema and a list of definitions which can be used 

4056 within the inner schema. 

4057 

4058 ```py 

4059 from pydantic_core import SchemaValidator, core_schema 

4060 

4061 schema = core_schema.definitions_schema( 

4062 core_schema.list_schema(core_schema.definition_reference_schema('foobar')), 

4063 [core_schema.int_schema(ref='foobar')], 

4064 ) 

4065 v = SchemaValidator(schema) 

4066 assert v.validate_python([1, 2, '3']) == [1, 2, 3] 

4067 ``` 

4068 

4069 Args: 

4070 schema: The inner schema 

4071 definitions: List of definitions which can be referenced within inner schema 

4072 """ 

4073 return DefinitionsSchema(type='definitions', schema=schema, definitions=definitions) 

4074 

4075 

4076class DefinitionReferenceSchema(TypedDict, total=False): 

4077 type: Required[Literal['definition-ref']] 

4078 schema_ref: Required[str] 

4079 ref: str 

4080 metadata: dict[str, Any] 

4081 serialization: SerSchema 

4082 

4083 

4084def definition_reference_schema( 

4085 schema_ref: str, 

4086 ref: str | None = None, 

4087 metadata: dict[str, Any] | None = None, 

4088 serialization: SerSchema | None = None, 

4089) -> DefinitionReferenceSchema: 

4090 """ 

4091 Returns a schema that points to a schema stored in "definitions", this is useful for nested recursive 

4092 models and also when you want to define validators separately from the main schema, e.g.: 

4093 

4094 ```py 

4095 from pydantic_core import SchemaValidator, core_schema 

4096 

4097 schema_definition = core_schema.definition_reference_schema('list-schema') 

4098 schema = core_schema.definitions_schema( 

4099 schema=schema_definition, 

4100 definitions=[ 

4101 core_schema.list_schema(items_schema=schema_definition, ref='list-schema'), 

4102 ], 

4103 ) 

4104 v = SchemaValidator(schema) 

4105 assert v.validate_python([()]) == [[]] 

4106 ``` 

4107 

4108 Args: 

4109 schema_ref: The schema ref to use for the definition reference schema 

4110 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4111 serialization: Custom serialization schema 

4112 """ 

4113 return _dict_not_none( 

4114 type='definition-ref', schema_ref=schema_ref, ref=ref, metadata=metadata, serialization=serialization 

4115 ) 

4116 

4117 

4118MYPY = False 

4119# See https://github.com/python/mypy/issues/14034 for details, in summary mypy is extremely slow to process this 

4120# union which kills performance not just for pydantic, but even for code using pydantic 

4121if not MYPY: 

4122 CoreSchema = Union[ 

4123 InvalidSchema, 

4124 AnySchema, 

4125 NoneSchema, 

4126 BoolSchema, 

4127 IntSchema, 

4128 FloatSchema, 

4129 DecimalSchema, 

4130 StringSchema, 

4131 BytesSchema, 

4132 DateSchema, 

4133 TimeSchema, 

4134 DatetimeSchema, 

4135 TimedeltaSchema, 

4136 LiteralSchema, 

4137 MissingSentinelSchema, 

4138 EnumSchema, 

4139 IsInstanceSchema, 

4140 IsSubclassSchema, 

4141 CallableSchema, 

4142 ListSchema, 

4143 TupleSchema, 

4144 SetSchema, 

4145 FrozenSetSchema, 

4146 GeneratorSchema, 

4147 DictSchema, 

4148 AfterValidatorFunctionSchema, 

4149 BeforeValidatorFunctionSchema, 

4150 WrapValidatorFunctionSchema, 

4151 PlainValidatorFunctionSchema, 

4152 WithDefaultSchema, 

4153 NullableSchema, 

4154 UnionSchema, 

4155 TaggedUnionSchema, 

4156 ChainSchema, 

4157 LaxOrStrictSchema, 

4158 JsonOrPythonSchema, 

4159 TypedDictSchema, 

4160 ModelFieldsSchema, 

4161 ModelSchema, 

4162 DataclassArgsSchema, 

4163 DataclassSchema, 

4164 ArgumentsSchema, 

4165 ArgumentsV3Schema, 

4166 CallSchema, 

4167 CustomErrorSchema, 

4168 JsonSchema, 

4169 UrlSchema, 

4170 MultiHostUrlSchema, 

4171 DefinitionsSchema, 

4172 DefinitionReferenceSchema, 

4173 UuidSchema, 

4174 ComplexSchema, 

4175 ] 

4176elif False: 

4177 CoreSchema: TypeAlias = Mapping[str, Any] 

4178 

4179 

4180# to update this, call `pytest -k test_core_schema_type_literal` and copy the output 

4181CoreSchemaType = Literal[ 

4182 'invalid', 

4183 'any', 

4184 'none', 

4185 'bool', 

4186 'int', 

4187 'float', 

4188 'decimal', 

4189 'str', 

4190 'bytes', 

4191 'date', 

4192 'time', 

4193 'datetime', 

4194 'timedelta', 

4195 'literal', 

4196 'missing-sentinel', 

4197 'enum', 

4198 'is-instance', 

4199 'is-subclass', 

4200 'callable', 

4201 'list', 

4202 'tuple', 

4203 'set', 

4204 'frozenset', 

4205 'generator', 

4206 'dict', 

4207 'function-after', 

4208 'function-before', 

4209 'function-wrap', 

4210 'function-plain', 

4211 'default', 

4212 'nullable', 

4213 'union', 

4214 'tagged-union', 

4215 'chain', 

4216 'lax-or-strict', 

4217 'json-or-python', 

4218 'typed-dict', 

4219 'model-fields', 

4220 'model', 

4221 'dataclass-args', 

4222 'dataclass', 

4223 'arguments', 

4224 'arguments-v3', 

4225 'call', 

4226 'custom-error', 

4227 'json', 

4228 'url', 

4229 'multi-host-url', 

4230 'definitions', 

4231 'definition-ref', 

4232 'uuid', 

4233 'complex', 

4234] 

4235 

4236CoreSchemaFieldType = Literal['model-field', 'dataclass-field', 'typed-dict-field', 'computed-field'] 

4237 

4238 

4239# used in _pydantic_core.pyi::PydanticKnownError 

4240# to update this, call `pytest -k test_all_errors` and copy the output 

4241ErrorType = Literal[ 

4242 'no_such_attribute', 

4243 'json_invalid', 

4244 'json_type', 

4245 'needs_python_object', 

4246 'recursion_loop', 

4247 'missing', 

4248 'frozen_field', 

4249 'frozen_instance', 

4250 'extra_forbidden', 

4251 'invalid_key', 

4252 'get_attribute_error', 

4253 'model_type', 

4254 'model_attributes_type', 

4255 'dataclass_type', 

4256 'dataclass_exact_type', 

4257 'default_factory_not_called', 

4258 'none_required', 

4259 'greater_than', 

4260 'greater_than_equal', 

4261 'less_than', 

4262 'less_than_equal', 

4263 'multiple_of', 

4264 'finite_number', 

4265 'too_short', 

4266 'too_long', 

4267 'iterable_type', 

4268 'iteration_error', 

4269 'string_type', 

4270 'string_sub_type', 

4271 'string_unicode', 

4272 'string_too_short', 

4273 'string_too_long', 

4274 'string_pattern_mismatch', 

4275 'string_not_ascii', 

4276 'enum', 

4277 'dict_type', 

4278 'mapping_type', 

4279 'list_type', 

4280 'tuple_type', 

4281 'set_type', 

4282 'set_item_not_hashable', 

4283 'bool_type', 

4284 'bool_parsing', 

4285 'int_type', 

4286 'int_parsing', 

4287 'int_parsing_size', 

4288 'int_from_float', 

4289 'float_type', 

4290 'float_parsing', 

4291 'bytes_type', 

4292 'bytes_too_short', 

4293 'bytes_too_long', 

4294 'bytes_invalid_encoding', 

4295 'value_error', 

4296 'assertion_error', 

4297 'literal_error', 

4298 'missing_sentinel_error', 

4299 'date_type', 

4300 'date_parsing', 

4301 'date_from_datetime_parsing', 

4302 'date_from_datetime_inexact', 

4303 'date_past', 

4304 'date_future', 

4305 'time_type', 

4306 'time_parsing', 

4307 'datetime_type', 

4308 'datetime_parsing', 

4309 'datetime_object_invalid', 

4310 'datetime_from_date_parsing', 

4311 'datetime_past', 

4312 'datetime_future', 

4313 'timezone_naive', 

4314 'timezone_aware', 

4315 'timezone_offset', 

4316 'time_delta_type', 

4317 'time_delta_parsing', 

4318 'frozen_set_type', 

4319 'is_instance_of', 

4320 'is_subclass_of', 

4321 'callable_type', 

4322 'union_tag_invalid', 

4323 'union_tag_not_found', 

4324 'arguments_type', 

4325 'missing_argument', 

4326 'unexpected_keyword_argument', 

4327 'missing_keyword_only_argument', 

4328 'unexpected_positional_argument', 

4329 'missing_positional_only_argument', 

4330 'multiple_argument_values', 

4331 'url_type', 

4332 'url_parsing', 

4333 'url_syntax_violation', 

4334 'url_too_long', 

4335 'url_scheme', 

4336 'uuid_type', 

4337 'uuid_parsing', 

4338 'uuid_version', 

4339 'decimal_type', 

4340 'decimal_parsing', 

4341 'decimal_max_digits', 

4342 'decimal_max_places', 

4343 'decimal_whole_digits', 

4344 'complex_type', 

4345 'complex_str_parsing', 

4346] 

4347 

4348 

4349def _dict_not_none(**kwargs: Any) -> Any: 

4350 return {k: v for k, v in kwargs.items() if v is not None} 

4351 

4352 

4353def iter_union_choices(union_schema: UnionSchema) -> Generator[CoreSchema]: 

4354 """Iterate over the choices of a `'union'` schema.""" 

4355 for choice in union_schema['choices']: 

4356 if isinstance(choice, tuple): 

4357 yield choice[0] 

4358 else: 

4359 yield choice 

4360 

4361 

4362############################################################################### 

4363# All this stuff is deprecated by #980 and will be removed eventually 

4364# They're kept because some code external code will be using them 

4365 

4366 

4367@deprecated('`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.') 

4368def field_before_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs): 

4369 warnings.warn( 

4370 '`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.', 

4371 DeprecationWarning, 

4372 ) 

4373 return with_info_before_validator_function(function, schema, field_name=field_name, **kwargs) 

4374 

4375 

4376@deprecated('`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.') 

4377def general_before_validator_function(*args, **kwargs): 

4378 warnings.warn( 

4379 '`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.', 

4380 DeprecationWarning, 

4381 ) 

4382 return with_info_before_validator_function(*args, **kwargs) 

4383 

4384 

4385@deprecated('`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.') 

4386def field_after_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs): 

4387 warnings.warn( 

4388 '`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.', 

4389 DeprecationWarning, 

4390 ) 

4391 return with_info_after_validator_function(function, schema, field_name=field_name, **kwargs) 

4392 

4393 

4394@deprecated('`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.') 

4395def general_after_validator_function(*args, **kwargs): 

4396 warnings.warn( 

4397 '`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.', 

4398 DeprecationWarning, 

4399 ) 

4400 return with_info_after_validator_function(*args, **kwargs) 

4401 

4402 

4403@deprecated('`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.') 

4404def field_wrap_validator_function( 

4405 function: WithInfoWrapValidatorFunction, field_name: str, schema: CoreSchema, **kwargs 

4406): 

4407 warnings.warn( 

4408 '`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.', 

4409 DeprecationWarning, 

4410 ) 

4411 return with_info_wrap_validator_function(function, schema, field_name=field_name, **kwargs) 

4412 

4413 

4414@deprecated('`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.') 

4415def general_wrap_validator_function(*args, **kwargs): 

4416 warnings.warn( 

4417 '`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.', 

4418 DeprecationWarning, 

4419 ) 

4420 return with_info_wrap_validator_function(*args, **kwargs) 

4421 

4422 

4423@deprecated('`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.') 

4424def field_plain_validator_function(function: WithInfoValidatorFunction, field_name: str, **kwargs): 

4425 warnings.warn( 

4426 '`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.', 

4427 DeprecationWarning, 

4428 ) 

4429 return with_info_plain_validator_function(function, field_name=field_name, **kwargs) 

4430 

4431 

4432@deprecated('`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.') 

4433def general_plain_validator_function(*args, **kwargs): 

4434 warnings.warn( 

4435 '`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.', 

4436 DeprecationWarning, 

4437 ) 

4438 return with_info_plain_validator_function(*args, **kwargs) 

4439 

4440 

4441_deprecated_import_lookup = { 

4442 'FieldValidationInfo': ValidationInfo, 

4443 'FieldValidatorFunction': WithInfoValidatorFunction, 

4444 'GeneralValidatorFunction': WithInfoValidatorFunction, 

4445 'FieldWrapValidatorFunction': WithInfoWrapValidatorFunction, 

4446} 

4447 

4448if TYPE_CHECKING: 

4449 FieldValidationInfo = ValidationInfo 

4450 

4451 

4452def __getattr__(attr_name: str) -> object: 

4453 new_attr = _deprecated_import_lookup.get(attr_name) 

4454 if new_attr is None: 

4455 raise AttributeError(f"module 'pydantic_core' has no attribute '{attr_name}'") 

4456 else: 

4457 import warnings 

4458 

4459 msg = f'`{attr_name}` is deprecated, use `{new_attr.__name__}` instead.' 

4460 warnings.warn(msg, DeprecationWarning, stacklevel=1) 

4461 return new_attr