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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1057 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 Callable, Generator, Mapping 

11from datetime import date, datetime, time, timedelta 

12from decimal import Decimal 

13from fractions import Fraction 

14from re import Pattern 

15from typing import TYPE_CHECKING, Any, Literal, Union, overload 

16 

17from typing_extensions import TypeVar, deprecated 

18 

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

20 from typing_extensions import TypedDict 

21else: 

22 from typing import TypedDict 

23 

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

25 from typing import TypeAlias 

26 

27 from typing_extensions import Protocol, Required 

28else: 

29 from typing import Protocol, Required, TypeAlias 

30 

31if TYPE_CHECKING: 

32 from pydantic_core import PydanticUndefined 

33else: 

34 # The initial build of pydantic_core requires PydanticUndefined to generate 

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

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

37 try: 

38 from pydantic_core import PydanticUndefined 

39 except ImportError: 

40 PydanticUndefined = object() 

41 

42 

43ExtraBehavior: TypeAlias = Literal['allow', 'forbid', 'ignore'] 

44 

45 

46class CoreConfig(TypedDict, total=False): 

47 """ 

48 Base class for schema configuration options. 

49 

50 Attributes: 

51 title: The name of the configuration. 

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

53 extra_fields_behavior: The behavior for handling extra fields. 

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

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

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

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

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

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

60 str_max_length: The maximum length for string fields. 

61 str_min_length: The minimum length for string fields. 

62 str_strip_whitespace: Whether to strip whitespace from string fields. 

63 str_to_lower: Whether to convert string fields to lowercase. 

64 str_to_upper: Whether to convert string fields to uppercase. 

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

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

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

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

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

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

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

72 ser_json_inf_nan: The serialization option for infinity and NaN values 

73 in float fields. Default is 'null'. 

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

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

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

77 Requires exceptiongroup backport pre Python 3.11. 

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

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

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

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

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

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

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

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

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

87 """ 

88 

89 title: str 

90 strict: bool 

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

92 extra_fields_behavior: ExtraBehavior 

93 typed_dict_total: bool # default: True 

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

95 from_attributes: bool 

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

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

98 loc_by_alias: bool 

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

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

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

102 validate_default: bool 

103 # used on typed-dicts and arguments 

104 # fields related to string fields only 

105 str_max_length: int 

106 str_min_length: int 

107 str_strip_whitespace: bool 

108 str_to_lower: bool 

109 str_to_upper: bool 

110 # fields related to float fields only 

111 allow_inf_nan: bool # default: True 

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

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

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

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

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

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

118 # used to hide input data from ValidationError repr 

119 hide_input_in_errors: bool 

120 validation_error_cause: bool # default: False 

121 coerce_numbers_to_str: bool # default: False 

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

123 cache_strings: bool | Literal['all', 'keys', 'none'] # default: 'True' 

124 validate_by_alias: bool # default: True 

125 validate_by_name: bool # default: False 

126 serialize_by_alias: bool # default: False 

127 polymorphic_serialization: bool # default: False 

128 url_preserve_empty_path: bool # default: False 

129 

130 

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

132 

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

134 

135 

136class SerializationInfo(Protocol[ContextT]): 

137 """Extra data used during serialization.""" 

138 

139 @property 

140 def include(self) -> IncExCall: 

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

142 ... 

143 

144 @property 

145 def exclude(self) -> IncExCall: 

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

147 ... 

148 

149 @property 

150 def context(self) -> ContextT: 

151 """The current serialization context.""" 

152 ... 

153 

154 @property 

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

156 """The serialization mode set during serialization.""" 

157 ... 

158 

159 @property 

160 def by_alias(self) -> bool: 

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

162 ... 

163 

164 @property 

165 def exclude_unset(self) -> bool: 

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

167 ... 

168 

169 @property 

170 def exclude_defaults(self) -> bool: 

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

172 ... 

173 

174 @property 

175 def exclude_none(self) -> bool: 

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

177 ... 

178 

179 @property 

180 def exclude_computed_fields(self) -> bool: 

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

182 ... 

183 

184 @property 

185 def serialize_as_any(self) -> bool: 

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

187 ... 

188 

189 @property 

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

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

192 ... 

193 

194 @property 

195 def round_trip(self) -> bool: 

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

197 ... 

198 

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

200 

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

202 

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

204 

205 

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

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

208 

209 @property 

210 def field_name(self) -> str: 

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

212 ... 

213 

214 

215class ValidationInfo(Protocol[ContextT]): 

216 """Extra data used during validation.""" 

217 

218 @property 

219 def context(self) -> ContextT: 

220 """The current validation context.""" 

221 ... 

222 

223 @property 

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

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

226 ... 

227 

228 @property 

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

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

231 ... 

232 

233 @property 

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

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

236 ... 

237 

238 @property 

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

240 """ 

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

242 attached to a model field. 

243 """ 

244 ... 

245 

246 

247ExpectedSerializationTypes: TypeAlias = Literal[ 

248 'none', 

249 'int', 

250 'bool', 

251 'float', 

252 'str', 

253 'bytes', 

254 'bytearray', 

255 'list', 

256 'deque', 

257 'tuple', 

258 'set', 

259 'frozenset', 

260 'generator', 

261 'dict', 

262 'frozendict', 

263 'ordered-dict', 

264 'counter', 

265 'datetime', 

266 'date', 

267 'time', 

268 'timedelta', 

269 'url', 

270 'multi-host-url', 

271 'json', 

272 'uuid', 

273 'any', 

274] 

275 

276 

277class SimpleSerSchema(TypedDict, total=False): 

278 type: Required[ExpectedSerializationTypes] 

279 

280 

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

282 """ 

283 Returns a schema for serialization with a custom type. 

284 

285 Note that any core schema can be used as a serialization schema, e.g. `int_schema()` 

286 is equivalent to `simple_ser_schema('int')`. 

287 

288 Args: 

289 type: The type to use for serialization 

290 """ 

291 return SimpleSerSchema(type=type) 

292 

293 

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

295GeneralPlainNoInfoSerializerFunction: TypeAlias = Callable[[Any], Any] 

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

297GeneralPlainInfoSerializerFunction: TypeAlias = Callable[[Any, SerializationInfo[Any]], Any] 

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

299FieldPlainNoInfoSerializerFunction: TypeAlias = Callable[[Any, Any], Any] 

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

301FieldPlainInfoSerializerFunction: TypeAlias = Callable[[Any, Any, FieldSerializationInfo[Any]], Any] 

302SerializerFunction: TypeAlias = ( 

303 GeneralPlainNoInfoSerializerFunction 

304 | GeneralPlainInfoSerializerFunction 

305 | FieldPlainNoInfoSerializerFunction 

306 | FieldPlainInfoSerializerFunction 

307) 

308 

309WhenUsed: TypeAlias = Literal['always', 'unless-none', 'json', 'json-unless-none'] 

310""" 

311Values have the following meanings: 

312 

313* `'always'` means always use 

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

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

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

317""" 

318 

319 

320class PlainSerializerFunctionSerSchema(TypedDict, total=False): 

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

322 function: Required[SerializerFunction] 

323 is_field_serializer: bool # default False 

324 info_arg: bool # default False 

325 return_schema: CoreSchema # if omitted, AnySchema is used 

326 when_used: WhenUsed # default: 'always' 

327 

328 

329def plain_serializer_function_ser_schema( 

330 function: SerializerFunction, 

331 *, 

332 is_field_serializer: bool | None = None, 

333 info_arg: bool | None = None, 

334 return_schema: CoreSchema | None = None, 

335 when_used: WhenUsed = 'always', 

336) -> PlainSerializerFunctionSerSchema: 

337 """ 

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

339 

340 Args: 

341 function: The function to use for serialization 

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

343 and `info` includes `field_name` 

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

345 return_schema: Schema to use for serializing return value 

346 when_used: When the function should be called 

347 """ 

348 if when_used == 'always': 

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

350 when_used = None # type: ignore 

351 return _dict_not_none( 

352 type='function-plain', 

353 function=function, 

354 is_field_serializer=is_field_serializer, 

355 info_arg=info_arg, 

356 return_schema=return_schema, 

357 when_used=when_used, 

358 ) 

359 

360 

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

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

363 

364 

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

366GeneralWrapNoInfoSerializerFunction: TypeAlias = Callable[[Any, SerializerFunctionWrapHandler], Any] 

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

368GeneralWrapInfoSerializerFunction: TypeAlias = Callable[ 

369 [Any, SerializerFunctionWrapHandler, SerializationInfo[Any]], Any 

370] 

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

372FieldWrapNoInfoSerializerFunction: TypeAlias = Callable[[Any, Any, SerializerFunctionWrapHandler], Any] 

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

374FieldWrapInfoSerializerFunction: TypeAlias = Callable[ 

375 [Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo[Any]], Any 

376] 

377WrapSerializerFunction: TypeAlias = ( 

378 GeneralWrapNoInfoSerializerFunction 

379 | GeneralWrapInfoSerializerFunction 

380 | FieldWrapNoInfoSerializerFunction 

381 | FieldWrapInfoSerializerFunction 

382) 

383 

384 

385class WrapSerializerFunctionSerSchema(TypedDict, total=False): 

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

387 function: Required[WrapSerializerFunction] 

388 is_field_serializer: bool # default False 

389 info_arg: bool # default False 

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

391 return_schema: CoreSchema # if omitted, AnySchema is used 

392 when_used: WhenUsed # default: 'always' 

393 

394 

395def wrap_serializer_function_ser_schema( 

396 function: WrapSerializerFunction, 

397 *, 

398 is_field_serializer: bool | None = None, 

399 info_arg: bool | None = None, 

400 schema: CoreSchema | None = None, 

401 return_schema: CoreSchema | None = None, 

402 when_used: WhenUsed = 'always', 

403) -> WrapSerializerFunctionSerSchema: 

404 """ 

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

406 

407 Args: 

408 function: The function to use for serialization 

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

410 and `info` includes `field_name` 

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

412 schema: The schema to use for the inner serialization 

413 return_schema: Schema to use for serializing return value 

414 when_used: When the function should be called 

415 """ 

416 if when_used == 'always': 

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

418 when_used = None # type: ignore 

419 return _dict_not_none( 

420 type='function-wrap', 

421 function=function, 

422 is_field_serializer=is_field_serializer, 

423 info_arg=info_arg, 

424 schema=schema, 

425 return_schema=return_schema, 

426 when_used=when_used, 

427 ) 

428 

429 

430class FormatSerSchema(TypedDict, total=False): 

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

432 formatting_string: Required[str] 

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

434 

435 

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

437 """ 

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

439 

440 Args: 

441 formatting_string: String defining the format to use 

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

443 """ 

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

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

446 when_used = None # type: ignore 

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

448 

449 

450class ToStringSerSchema(TypedDict, total=False): 

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

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

453 

454 

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

456 """ 

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

458 

459 Args: 

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

461 """ 

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

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

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

465 s['when_used'] = when_used 

466 return s # type: ignore 

467 

468 

469class ModelSerSchema(TypedDict, total=False): 

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

471 cls: Required[type[Any]] 

472 schema: Required[CoreSchema] 

473 

474 

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

476 """ 

477 Returns a schema for serialization using a model. 

478 

479 Note that any core schema can be used as a serialization schema, e.g. `model_schema()` 

480 can be used instead. 

481 

482 Args: 

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

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

485 """ 

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

487 

488 

489SerSchema: TypeAlias = 'SimpleSerSchema | PlainSerializerFunctionSerSchema | WrapSerializerFunctionSerSchema | FormatSerSchema | ToStringSerSchema | ModelSerSchema | CoreSchema' 

490 

491"""The schemas that can be used as the `serialization` key of a core schema.""" 

492 

493 

494class InvalidSchema(TypedDict, total=False): 

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

496 ref: str 

497 metadata: dict[str, Any] 

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

499 # all other CoreSchema union members 

500 serialization: SerSchema 

501 

502 

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

504 """ 

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

506 

507 Args: 

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

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

510 """ 

511 

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

513 

514 

515class ComputedField(TypedDict, total=False): 

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

517 property_name: Required[str] 

518 return_schema: Required[CoreSchema] 

519 alias: str 

520 serialization_exclude_if: Callable[[Any], bool] 

521 metadata: dict[str, Any] 

522 

523 

524def computed_field( 

525 property_name: str, 

526 return_schema: CoreSchema, 

527 *, 

528 alias: str | None = None, 

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

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

531) -> ComputedField: 

532 """ 

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

534 

535 Args: 

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

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

538 alias: The name to use in the serialized output 

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

540 """ 

541 return _dict_not_none( 

542 type='computed-field', 

543 property_name=property_name, 

544 return_schema=return_schema, 

545 alias=alias, 

546 serialization_exclude_if=serialization_exclude_if, 

547 metadata=metadata, 

548 ) 

549 

550 

551class AnySchema(TypedDict, total=False): 

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

553 ref: str 

554 metadata: dict[str, Any] 

555 serialization: SerSchema 

556 

557 

558def any_schema( 

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

560) -> AnySchema: 

561 """ 

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

563 

564 ```py 

565 from pydantic_core import SchemaValidator, core_schema 

566 

567 schema = core_schema.any_schema() 

568 v = SchemaValidator(schema) 

569 assert v.validate_python(1) == 1 

570 ``` 

571 

572 Args: 

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

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

575 serialization: Custom serialization schema 

576 """ 

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

578 

579 

580class NoneSchema(TypedDict, total=False): 

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

582 ref: str 

583 metadata: dict[str, Any] 

584 serialization: SerSchema 

585 

586 

587def none_schema( 

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

589) -> NoneSchema: 

590 """ 

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

592 

593 ```py 

594 from pydantic_core import SchemaValidator, core_schema 

595 

596 schema = core_schema.none_schema() 

597 v = SchemaValidator(schema) 

598 assert v.validate_python(None) is None 

599 ``` 

600 

601 Args: 

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

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

604 serialization: Custom serialization schema 

605 """ 

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

607 

608 

609class BoolSchema(TypedDict, total=False): 

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

611 strict: bool 

612 ref: str 

613 metadata: dict[str, Any] 

614 serialization: SerSchema 

615 

616 

617def bool_schema( 

618 strict: bool | None = None, 

619 ref: str | None = None, 

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

621 serialization: SerSchema | None = None, 

622) -> BoolSchema: 

623 """ 

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

625 

626 ```py 

627 from pydantic_core import SchemaValidator, core_schema 

628 

629 schema = core_schema.bool_schema() 

630 v = SchemaValidator(schema) 

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

632 ``` 

633 

634 Args: 

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

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

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

638 serialization: Custom serialization schema 

639 """ 

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

641 

642 

643class IntSchema(TypedDict, total=False): 

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

645 multiple_of: int 

646 le: int 

647 ge: int 

648 lt: int 

649 gt: int 

650 strict: bool 

651 ref: str 

652 metadata: dict[str, Any] 

653 serialization: SerSchema 

654 

655 

656def int_schema( 

657 *, 

658 multiple_of: int | None = None, 

659 le: int | None = None, 

660 ge: int | None = None, 

661 lt: int | None = None, 

662 gt: int | None = None, 

663 strict: bool | None = None, 

664 ref: str | None = None, 

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

666 serialization: SerSchema | None = None, 

667) -> IntSchema: 

668 """ 

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

670 

671 ```py 

672 from pydantic_core import SchemaValidator, core_schema 

673 

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

675 v = SchemaValidator(schema) 

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

677 ``` 

678 

679 Args: 

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

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

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

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

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

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

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

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

688 serialization: Custom serialization schema 

689 """ 

690 return _dict_not_none( 

691 type='int', 

692 multiple_of=multiple_of, 

693 le=le, 

694 ge=ge, 

695 lt=lt, 

696 gt=gt, 

697 strict=strict, 

698 ref=ref, 

699 metadata=metadata, 

700 serialization=serialization, 

701 ) 

702 

703 

704class FloatSchema(TypedDict, total=False): 

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

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

707 multiple_of: float 

708 le: float 

709 ge: float 

710 lt: float 

711 gt: float 

712 strict: bool 

713 ref: str 

714 metadata: dict[str, Any] 

715 serialization: SerSchema 

716 

717 

718def float_schema( 

719 *, 

720 allow_inf_nan: bool | None = None, 

721 multiple_of: float | None = None, 

722 le: float | None = None, 

723 ge: float | None = None, 

724 lt: float | None = None, 

725 gt: float | None = None, 

726 strict: bool | None = None, 

727 ref: str | None = None, 

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

729 serialization: SerSchema | None = None, 

730) -> FloatSchema: 

731 """ 

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

733 

734 ```py 

735 from pydantic_core import SchemaValidator, core_schema 

736 

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

738 v = SchemaValidator(schema) 

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

740 ``` 

741 

742 Args: 

743 allow_inf_nan: Whether to allow inf and nan values 

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

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

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

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

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

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

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

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

752 serialization: Custom serialization schema 

753 """ 

754 return _dict_not_none( 

755 type='float', 

756 allow_inf_nan=allow_inf_nan, 

757 multiple_of=multiple_of, 

758 le=le, 

759 ge=ge, 

760 lt=lt, 

761 gt=gt, 

762 strict=strict, 

763 ref=ref, 

764 metadata=metadata, 

765 serialization=serialization, 

766 ) 

767 

768 

769class DecimalSchema(TypedDict, total=False): 

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

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

772 multiple_of: Decimal 

773 le: Decimal 

774 ge: Decimal 

775 lt: Decimal 

776 gt: Decimal 

777 max_digits: int 

778 decimal_places: int 

779 strict: bool 

780 ref: str 

781 metadata: dict[str, Any] 

782 serialization: SerSchema 

783 

784 

785def decimal_schema( 

786 *, 

787 allow_inf_nan: bool | None = None, 

788 multiple_of: Decimal | None = None, 

789 le: Decimal | None = None, 

790 ge: Decimal | None = None, 

791 lt: Decimal | None = None, 

792 gt: Decimal | None = None, 

793 max_digits: int | None = None, 

794 decimal_places: int | None = None, 

795 strict: bool | None = None, 

796 ref: str | None = None, 

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

798 serialization: SerSchema | None = None, 

799) -> DecimalSchema: 

800 """ 

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

802 

803 ```py 

804 from decimal import Decimal 

805 from pydantic_core import SchemaValidator, core_schema 

806 

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

808 v = SchemaValidator(schema) 

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

810 ``` 

811 

812 Args: 

813 allow_inf_nan: Whether to allow inf and nan values 

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

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

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

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

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

819 max_digits: The maximum number of decimal digits allowed 

820 decimal_places: The maximum number of decimal places allowed 

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

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

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

824 serialization: Custom serialization schema 

825 """ 

826 return _dict_not_none( 

827 type='decimal', 

828 gt=gt, 

829 ge=ge, 

830 lt=lt, 

831 le=le, 

832 max_digits=max_digits, 

833 decimal_places=decimal_places, 

834 multiple_of=multiple_of, 

835 allow_inf_nan=allow_inf_nan, 

836 strict=strict, 

837 ref=ref, 

838 metadata=metadata, 

839 serialization=serialization, 

840 ) 

841 

842 

843class FractionSchema(TypedDict, total=False): 

844 type: Required[Literal['fraction']] 

845 multiple_of: Fraction 

846 le: Fraction 

847 ge: Fraction 

848 lt: Fraction 

849 gt: Fraction 

850 strict: bool 

851 ref: str 

852 metadata: dict[str, Any] 

853 serialization: SerSchema 

854 

855 

856def fraction_schema( 

857 *, 

858 multiple_of: Fraction | None = None, 

859 le: Fraction | None = None, 

860 ge: Fraction | None = None, 

861 lt: Fraction | None = None, 

862 gt: Fraction | None = None, 

863 strict: bool | None = None, 

864 ref: str | None = None, 

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

866 serialization: SerSchema | None = None, 

867) -> FractionSchema: 

868 """ 

869 Returns a schema that matches a fraction value, e.g.: 

870 

871 ```py 

872 from fractions import Fraction 

873 from pydantic_core import SchemaValidator, core_schema 

874 

875 schema = core_schema.fraction_schema(le=Fraction(3, 4), ge=Fraction(1, 4)) 

876 v = SchemaValidator(schema) 

877 assert v.validate_python('1/2') == Fraction(1, 2) 

878 ``` 

879 

880 Args: 

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

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

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

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

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

886 strict: Whether the value should be a Fraction or a value that can be converted to a Fraction 

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

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

889 serialization: Custom serialization schema 

890 """ 

891 return _dict_not_none( 

892 type='fraction', 

893 multiple_of=multiple_of, 

894 gt=gt, 

895 ge=ge, 

896 lt=lt, 

897 le=le, 

898 strict=strict, 

899 ref=ref, 

900 metadata=metadata, 

901 serialization=serialization, 

902 ) 

903 

904 

905class ComplexSchema(TypedDict, total=False): 

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

907 strict: bool 

908 ref: str 

909 metadata: dict[str, Any] 

910 serialization: SerSchema 

911 

912 

913def complex_schema( 

914 *, 

915 strict: bool | None = None, 

916 ref: str | None = None, 

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

918 serialization: SerSchema | None = None, 

919) -> ComplexSchema: 

920 """ 

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

922 

923 ```py 

924 from pydantic_core import SchemaValidator, core_schema 

925 

926 schema = core_schema.complex_schema() 

927 v = SchemaValidator(schema) 

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

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

930 ``` 

931 

932 Args: 

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

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

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

936 serialization: Custom serialization schema 

937 """ 

938 return _dict_not_none( 

939 type='complex', 

940 strict=strict, 

941 ref=ref, 

942 metadata=metadata, 

943 serialization=serialization, 

944 ) 

945 

946 

947class StringSchema(TypedDict, total=False): 

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

949 pattern: str | Pattern[str] 

950 max_length: int 

951 min_length: int 

952 strip_whitespace: bool 

953 to_lower: bool 

954 to_upper: bool 

955 ascii_only: bool 

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

957 strict: bool 

958 coerce_numbers_to_str: bool 

959 ref: str 

960 metadata: dict[str, Any] 

961 serialization: SerSchema 

962 

963 

964def str_schema( 

965 *, 

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

967 max_length: int | None = None, 

968 min_length: int | None = None, 

969 strip_whitespace: bool | None = None, 

970 to_lower: bool | None = None, 

971 to_upper: bool | None = None, 

972 ascii_only: bool | None = None, 

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

974 strict: bool | None = None, 

975 coerce_numbers_to_str: bool | None = None, 

976 ref: str | None = None, 

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

978 serialization: SerSchema | None = None, 

979) -> StringSchema: 

980 """ 

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

982 

983 ```py 

984 from pydantic_core import SchemaValidator, core_schema 

985 

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

987 v = SchemaValidator(schema) 

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

989 ``` 

990 

991 Args: 

992 pattern: A regex pattern that the value must match 

993 max_length: The value must be at most this length 

994 min_length: The value must be at least this length 

995 strip_whitespace: Whether to strip whitespace from the value 

996 to_lower: Whether to convert the value to lowercase 

997 to_upper: Whether to convert the value to uppercase 

998 ascii_only: Whether the value must contain only ASCII characters 

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

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

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

1002 resistant, but does not support all regex features. 

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

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

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

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

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

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

1009 serialization: Custom serialization schema 

1010 """ 

1011 return _dict_not_none( 

1012 type='str', 

1013 pattern=pattern, 

1014 max_length=max_length, 

1015 min_length=min_length, 

1016 strip_whitespace=strip_whitespace, 

1017 to_lower=to_lower, 

1018 to_upper=to_upper, 

1019 ascii_only=ascii_only, 

1020 regex_engine=regex_engine, 

1021 strict=strict, 

1022 coerce_numbers_to_str=coerce_numbers_to_str, 

1023 ref=ref, 

1024 metadata=metadata, 

1025 serialization=serialization, 

1026 ) 

1027 

1028 

1029class BytesSchema(TypedDict, total=False): 

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

1031 max_length: int 

1032 min_length: int 

1033 strict: bool 

1034 ref: str 

1035 metadata: dict[str, Any] 

1036 serialization: SerSchema 

1037 

1038 

1039def bytes_schema( 

1040 *, 

1041 max_length: int | None = None, 

1042 min_length: int | None = None, 

1043 strict: bool | None = None, 

1044 ref: str | None = None, 

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

1046 serialization: SerSchema | None = None, 

1047) -> BytesSchema: 

1048 """ 

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

1050 

1051 ```py 

1052 from pydantic_core import SchemaValidator, core_schema 

1053 

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

1055 v = SchemaValidator(schema) 

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

1057 ``` 

1058 

1059 Args: 

1060 max_length: The value must be at most this length 

1061 min_length: The value must be at least this length 

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

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

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

1065 serialization: Custom serialization schema 

1066 """ 

1067 return _dict_not_none( 

1068 type='bytes', 

1069 max_length=max_length, 

1070 min_length=min_length, 

1071 strict=strict, 

1072 ref=ref, 

1073 metadata=metadata, 

1074 serialization=serialization, 

1075 ) 

1076 

1077 

1078class DateSchema(TypedDict, total=False): 

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

1080 strict: bool 

1081 le: date 

1082 ge: date 

1083 lt: date 

1084 gt: date 

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

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

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

1088 now_utc_offset: int 

1089 ref: str 

1090 metadata: dict[str, Any] 

1091 serialization: SerSchema 

1092 

1093 

1094def date_schema( 

1095 *, 

1096 strict: bool | None = None, 

1097 le: date | None = None, 

1098 ge: date | None = None, 

1099 lt: date | None = None, 

1100 gt: date | None = None, 

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

1102 now_utc_offset: int | None = None, 

1103 ref: str | None = None, 

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

1105 serialization: SerSchema | None = None, 

1106) -> DateSchema: 

1107 """ 

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

1109 

1110 ```py 

1111 from datetime import date 

1112 from pydantic_core import SchemaValidator, core_schema 

1113 

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

1115 v = SchemaValidator(schema) 

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

1117 ``` 

1118 

1119 Args: 

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

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

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

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

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

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

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

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

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

1129 serialization: Custom serialization schema 

1130 """ 

1131 return _dict_not_none( 

1132 type='date', 

1133 strict=strict, 

1134 le=le, 

1135 ge=ge, 

1136 lt=lt, 

1137 gt=gt, 

1138 now_op=now_op, 

1139 now_utc_offset=now_utc_offset, 

1140 ref=ref, 

1141 metadata=metadata, 

1142 serialization=serialization, 

1143 ) 

1144 

1145 

1146class TimeSchema(TypedDict, total=False): 

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

1148 strict: bool 

1149 le: time 

1150 ge: time 

1151 lt: time 

1152 gt: time 

1153 tz_constraint: Literal['aware', 'naive'] | int 

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

1155 ref: str 

1156 metadata: dict[str, Any] 

1157 serialization: SerSchema 

1158 

1159 

1160def time_schema( 

1161 *, 

1162 strict: bool | None = None, 

1163 le: time | None = None, 

1164 ge: time | None = None, 

1165 lt: time | None = None, 

1166 gt: time | None = None, 

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

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

1169 ref: str | None = None, 

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

1171 serialization: SerSchema | None = None, 

1172) -> TimeSchema: 

1173 """ 

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

1175 

1176 ```py 

1177 from datetime import time 

1178 from pydantic_core import SchemaValidator, core_schema 

1179 

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

1181 v = SchemaValidator(schema) 

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

1183 ``` 

1184 

1185 Args: 

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

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

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

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

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

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

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

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

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

1195 serialization: Custom serialization schema 

1196 """ 

1197 return _dict_not_none( 

1198 type='time', 

1199 strict=strict, 

1200 le=le, 

1201 ge=ge, 

1202 lt=lt, 

1203 gt=gt, 

1204 tz_constraint=tz_constraint, 

1205 microseconds_precision=microseconds_precision, 

1206 ref=ref, 

1207 metadata=metadata, 

1208 serialization=serialization, 

1209 ) 

1210 

1211 

1212class DatetimeSchema(TypedDict, total=False): 

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

1214 strict: bool 

1215 le: datetime 

1216 ge: datetime 

1217 lt: datetime 

1218 gt: datetime 

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

1220 tz_constraint: Literal['aware', 'naive'] | int 

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

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

1223 now_utc_offset: int 

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

1225 ref: str 

1226 metadata: dict[str, Any] 

1227 serialization: SerSchema 

1228 

1229 

1230def datetime_schema( 

1231 *, 

1232 strict: bool | None = None, 

1233 le: datetime | None = None, 

1234 ge: datetime | None = None, 

1235 lt: datetime | None = None, 

1236 gt: datetime | None = None, 

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

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

1239 now_utc_offset: int | None = None, 

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

1241 ref: str | None = None, 

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

1243 serialization: SerSchema | None = None, 

1244) -> DatetimeSchema: 

1245 """ 

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

1247 

1248 ```py 

1249 from datetime import datetime 

1250 from pydantic_core import SchemaValidator, core_schema 

1251 

1252 schema = core_schema.datetime_schema() 

1253 v = SchemaValidator(schema) 

1254 now = datetime.now() 

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

1256 ``` 

1257 

1258 Args: 

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

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

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

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

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

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

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

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

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

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

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

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

1271 serialization: Custom serialization schema 

1272 """ 

1273 return _dict_not_none( 

1274 type='datetime', 

1275 strict=strict, 

1276 le=le, 

1277 ge=ge, 

1278 lt=lt, 

1279 gt=gt, 

1280 now_op=now_op, 

1281 tz_constraint=tz_constraint, 

1282 now_utc_offset=now_utc_offset, 

1283 microseconds_precision=microseconds_precision, 

1284 ref=ref, 

1285 metadata=metadata, 

1286 serialization=serialization, 

1287 ) 

1288 

1289 

1290class TimedeltaSchema(TypedDict, total=False): 

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

1292 strict: bool 

1293 multiple_of: timedelta 

1294 le: timedelta 

1295 ge: timedelta 

1296 lt: timedelta 

1297 gt: timedelta 

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

1299 ref: str 

1300 metadata: dict[str, Any] 

1301 serialization: SerSchema 

1302 

1303 

1304def timedelta_schema( 

1305 *, 

1306 strict: bool | None = None, 

1307 multiple_of: timedelta | None = None, 

1308 le: timedelta | None = None, 

1309 ge: timedelta | None = None, 

1310 lt: timedelta | None = None, 

1311 gt: timedelta | None = None, 

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

1313 ref: str | None = None, 

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

1315 serialization: SerSchema | None = None, 

1316) -> TimedeltaSchema: 

1317 """ 

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

1319 

1320 ```py 

1321 from datetime import timedelta 

1322 from pydantic_core import SchemaValidator, core_schema 

1323 

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

1325 v = SchemaValidator(schema) 

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

1327 ``` 

1328 

1329 Args: 

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

1331 multiple_of: The value must be a multiple of this timedelta 

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

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

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

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

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

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

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

1339 serialization: Custom serialization schema 

1340 """ 

1341 return _dict_not_none( 

1342 type='timedelta', 

1343 strict=strict, 

1344 multiple_of=multiple_of, 

1345 le=le, 

1346 ge=ge, 

1347 lt=lt, 

1348 gt=gt, 

1349 microseconds_precision=microseconds_precision, 

1350 ref=ref, 

1351 metadata=metadata, 

1352 serialization=serialization, 

1353 ) 

1354 

1355 

1356class LiteralSchema(TypedDict, total=False): 

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

1358 expected: Required[list[Any]] 

1359 ref: str 

1360 metadata: dict[str, Any] 

1361 serialization: SerSchema 

1362 

1363 

1364def literal_schema( 

1365 expected: list[Any], 

1366 *, 

1367 ref: str | None = None, 

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

1369 serialization: SerSchema | None = None, 

1370) -> LiteralSchema: 

1371 """ 

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

1373 

1374 ```py 

1375 from pydantic_core import SchemaValidator, core_schema 

1376 

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

1378 v = SchemaValidator(schema) 

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

1380 ``` 

1381 

1382 Args: 

1383 expected: The value must be one of these values 

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

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

1386 serialization: Custom serialization schema 

1387 """ 

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

1389 

1390 

1391class EnumSchema(TypedDict, total=False): 

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

1393 cls: Required[Any] 

1394 members: Required[list[Any]] 

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

1396 missing: Callable[[Any], Any] 

1397 strict: bool 

1398 ref: str 

1399 metadata: dict[str, Any] 

1400 serialization: SerSchema 

1401 

1402 

1403@overload 

1404@deprecated('The `missing` argument on `enum_schema()` is deprecated and no longer used.') 

1405def enum_schema( 

1406 cls: Any, 

1407 members: list[Any], 

1408 *, 

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

1410 missing: Callable[[Any], Any] | None, 

1411 strict: bool | None = None, 

1412 ref: str | None = None, 

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

1414 serialization: SerSchema | None = None, 

1415) -> EnumSchema: ... 

1416 

1417 

1418@overload 

1419def enum_schema( 

1420 cls: Any, 

1421 members: list[Any], 

1422 *, 

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

1424 strict: bool | None = None, 

1425 ref: str | None = None, 

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

1427 serialization: SerSchema | None = None, 

1428) -> EnumSchema: ... 

1429 

1430 

1431def enum_schema( 

1432 cls: Any, 

1433 members: list[Any], 

1434 *, 

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

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

1437 strict: bool | None = None, 

1438 ref: str | None = None, 

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

1440 serialization: SerSchema | None = None, 

1441) -> EnumSchema: 

1442 """ 

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

1444 

1445 ```py 

1446 from enum import Enum 

1447 from pydantic_core import SchemaValidator, core_schema 

1448 

1449 class Color(Enum): 

1450 RED = 1 

1451 GREEN = 2 

1452 BLUE = 3 

1453 

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

1455 v = SchemaValidator(schema) 

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

1457 ``` 

1458 

1459 Args: 

1460 cls: The enum class 

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

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

1463 missing: Deprecated and no longer used, the `_missing_` hook of the enum class is now called by the enum validator 

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

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

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

1467 serialization: Custom serialization schema 

1468 """ 

1469 if missing is not None: 

1470 warnings.warn( 

1471 'The `missing` argument on `enum_schema()` is deprecated and no longer used.', 

1472 DeprecationWarning, 

1473 stacklevel=2, 

1474 ) 

1475 

1476 return _dict_not_none( 

1477 type='enum', 

1478 cls=cls, 

1479 members=members, 

1480 sub_type=sub_type, 

1481 missing=missing, 

1482 strict=strict, 

1483 ref=ref, 

1484 metadata=metadata, 

1485 serialization=serialization, 

1486 ) 

1487 

1488 

1489class MissingSentinelSchema(TypedDict, total=False): 

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

1491 schema: CoreSchema 

1492 metadata: dict[str, Any] 

1493 serialization: SerSchema 

1494 

1495 

1496def missing_sentinel_schema( 

1497 schema: CoreSchema | None = None, 

1498 *, 

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

1500 serialization: SerSchema | None = None, 

1501) -> MissingSentinelSchema: 

1502 """ 

1503 Returns a schema that matches the `MISSING` sentinel, or, if provided, the wrapped schema, e.g.: 

1504 

1505 ```py 

1506 from pydantic_core import MISSING, SchemaValidator, core_schema 

1507 

1508 schema = core_schema.missing_sentinel_schema(core_schema.int_schema()) 

1509 v = SchemaValidator(schema) 

1510 assert v.validate_python(MISSING) is MISSING 

1511 assert v.validate_python(1) == 1 

1512 ``` 

1513 

1514 If no schema is provided, only the `MISSING` sentinel is a valid input. 

1515 

1516 Args: 

1517 schema: The schema to wrap 

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

1519 serialization: Custom serialization schema 

1520 """ 

1521 

1522 return _dict_not_none( 

1523 type='missing-sentinel', 

1524 schema=schema, 

1525 metadata=metadata, 

1526 serialization=serialization, 

1527 ) 

1528 

1529 

1530class EllipsisSchema(TypedDict, total=False): 

1531 type: Required[Literal['ellipsis']] 

1532 metadata: dict[str, Any] 

1533 serialization: SerSchema 

1534 

1535 

1536def ellipsis_schema( 

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

1538 serialization: SerSchema | None = None, 

1539) -> EllipsisSchema: 

1540 """Returns a schema for the [`Ellipsis`][] literal.""" 

1541 

1542 return _dict_not_none( 

1543 type='ellipsis', 

1544 metadata=metadata, 

1545 serialization=serialization, 

1546 ) 

1547 

1548 

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

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

1551 

1552 

1553class IsInstanceSchema(TypedDict, total=False): 

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

1555 cls: Required[Any] 

1556 cls_repr: str 

1557 ref: str 

1558 metadata: dict[str, Any] 

1559 serialization: SerSchema 

1560 

1561 

1562def is_instance_schema( 

1563 cls: Any, 

1564 *, 

1565 cls_repr: str | None = None, 

1566 ref: str | None = None, 

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

1568 serialization: SerSchema | None = None, 

1569) -> IsInstanceSchema: 

1570 """ 

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

1572 

1573 ```py 

1574 from pydantic_core import SchemaValidator, core_schema 

1575 

1576 class A: 

1577 pass 

1578 

1579 schema = core_schema.is_instance_schema(cls=A) 

1580 v = SchemaValidator(schema) 

1581 v.validate_python(A()) 

1582 ``` 

1583 

1584 Args: 

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

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

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

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

1589 serialization: Custom serialization schema 

1590 """ 

1591 return _dict_not_none( 

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

1593 ) 

1594 

1595 

1596class IsSubclassSchema(TypedDict, total=False): 

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

1598 cls: Required[type[Any]] 

1599 cls_repr: str 

1600 ref: str 

1601 metadata: dict[str, Any] 

1602 serialization: SerSchema 

1603 

1604 

1605def is_subclass_schema( 

1606 cls: type[Any], 

1607 *, 

1608 cls_repr: str | None = None, 

1609 ref: str | None = None, 

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

1611 serialization: SerSchema | None = None, 

1612) -> IsInstanceSchema: 

1613 """ 

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

1615 

1616 ```py 

1617 from pydantic_core import SchemaValidator, core_schema 

1618 

1619 class A: 

1620 pass 

1621 

1622 class B(A): 

1623 pass 

1624 

1625 schema = core_schema.is_subclass_schema(cls=A) 

1626 v = SchemaValidator(schema) 

1627 v.validate_python(B) 

1628 ``` 

1629 

1630 Args: 

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

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

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

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

1635 serialization: Custom serialization schema 

1636 """ 

1637 return _dict_not_none( 

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

1639 ) 

1640 

1641 

1642class CallableSchema(TypedDict, total=False): 

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

1644 ref: str 

1645 metadata: dict[str, Any] 

1646 serialization: SerSchema 

1647 

1648 

1649def callable_schema( 

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

1651) -> CallableSchema: 

1652 """ 

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

1654 

1655 ```py 

1656 from pydantic_core import SchemaValidator, core_schema 

1657 

1658 schema = core_schema.callable_schema() 

1659 v = SchemaValidator(schema) 

1660 v.validate_python(min) 

1661 ``` 

1662 

1663 Args: 

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

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

1666 serialization: Custom serialization schema 

1667 """ 

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

1669 

1670 

1671class UuidSchema(TypedDict, total=False): 

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

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

1674 strict: bool 

1675 ref: str 

1676 metadata: dict[str, Any] 

1677 serialization: SerSchema 

1678 

1679 

1680def uuid_schema( 

1681 *, 

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

1683 strict: bool | None = None, 

1684 ref: str | None = None, 

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

1686 serialization: SerSchema | None = None, 

1687) -> UuidSchema: 

1688 return _dict_not_none( 

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

1690 ) 

1691 

1692 

1693class IncExSeqSerSchema(TypedDict, total=False): 

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

1695 include: set[int] 

1696 exclude: set[int] 

1697 

1698 

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

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

1701 

1702 

1703IncExSeqOrElseSerSchema: TypeAlias = Union[IncExSeqSerSchema, SerSchema] # noqa: UP007 (TypeError when evaluating) 

1704 

1705 

1706class ListSchema(TypedDict, total=False): 

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

1708 items_schema: CoreSchema 

1709 min_length: int 

1710 max_length: int 

1711 fail_fast: bool 

1712 strict: bool 

1713 ref: str 

1714 metadata: dict[str, Any] 

1715 serialization: IncExSeqOrElseSerSchema 

1716 

1717 

1718def list_schema( 

1719 items_schema: CoreSchema | None = None, 

1720 *, 

1721 min_length: int | None = None, 

1722 max_length: int | None = None, 

1723 fail_fast: bool | None = None, 

1724 strict: bool | None = None, 

1725 ref: str | None = None, 

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

1727 serialization: IncExSeqOrElseSerSchema | None = None, 

1728) -> ListSchema: 

1729 """ 

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

1731 

1732 ```py 

1733 from pydantic_core import SchemaValidator, core_schema 

1734 

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

1736 v = SchemaValidator(schema) 

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

1738 ``` 

1739 

1740 Args: 

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

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

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

1744 fail_fast: Stop validation on the first error 

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

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

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

1748 serialization: Custom serialization schema 

1749 """ 

1750 return _dict_not_none( 

1751 type='list', 

1752 items_schema=items_schema, 

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 DequeSchema(TypedDict, total=False): 

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

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: IncExSeqOrElseSerSchema 

1773 

1774 

1775def deque_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: IncExSeqOrElseSerSchema | None = None, 

1785) -> DequeSchema: 

1786 """ 

1787 Returns a schema that matches a [`collections.deque`][] value, e.g.: 

1788 

1789 ```py 

1790 from collections import deque 

1791 

1792 from pydantic_core import SchemaValidator, core_schema 

1793 

1794 schema = core_schema.deque_schema(core_schema.int_schema(), min_length=0, max_length=10) 

1795 v = SchemaValidator(schema) 

1796 assert v.validate_python(['4']) == deque([4]) 

1797 ``` 

1798 

1799 In lax mode, any iterable (except strings, bytes and mappings) is accepted and converted to a deque. 

1800 If the input is a deque instance, its `maxlen` is preserved on the output. 

1801 

1802 Args: 

1803 items_schema: The value must be a deque of items that match this schema 

1804 min_length: The value must be a deque with at least this many items 

1805 max_length: The value must be a deque with at most this many items 

1806 fail_fast: Stop validation on the first error 

1807 strict: The value must be a deque instance 

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

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

1810 serialization: Custom serialization schema 

1811 """ 

1812 return _dict_not_none( 

1813 type='deque', 

1814 items_schema=items_schema, 

1815 min_length=min_length, 

1816 max_length=max_length, 

1817 fail_fast=fail_fast, 

1818 strict=strict, 

1819 ref=ref, 

1820 metadata=metadata, 

1821 serialization=serialization, 

1822 ) 

1823 

1824 

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

1826def tuple_positional_schema( 

1827 items_schema: list[CoreSchema], 

1828 *, 

1829 extras_schema: CoreSchema | None = None, 

1830 strict: bool | None = None, 

1831 ref: str | None = None, 

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

1833 serialization: IncExSeqOrElseSerSchema | None = None, 

1834) -> TupleSchema: 

1835 """ 

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

1837 

1838 ```py 

1839 from pydantic_core import SchemaValidator, core_schema 

1840 

1841 schema = core_schema.tuple_positional_schema( 

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

1843 ) 

1844 v = SchemaValidator(schema) 

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

1846 ``` 

1847 

1848 Args: 

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

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

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

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

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

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

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

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

1857 serialization: Custom serialization schema 

1858 """ 

1859 if extras_schema is not None: 

1860 variadic_item_index = len(items_schema) 

1861 items_schema = items_schema + [extras_schema] 

1862 else: 

1863 variadic_item_index = None 

1864 return tuple_schema( 

1865 items_schema=items_schema, 

1866 variadic_item_index=variadic_item_index, 

1867 strict=strict, 

1868 ref=ref, 

1869 metadata=metadata, 

1870 serialization=serialization, 

1871 ) 

1872 

1873 

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

1875def tuple_variable_schema( 

1876 items_schema: CoreSchema | None = None, 

1877 *, 

1878 min_length: int | None = None, 

1879 max_length: int | None = None, 

1880 strict: bool | None = None, 

1881 ref: str | None = None, 

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

1883 serialization: IncExSeqOrElseSerSchema | None = None, 

1884) -> TupleSchema: 

1885 """ 

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

1887 

1888 ```py 

1889 from pydantic_core import SchemaValidator, core_schema 

1890 

1891 schema = core_schema.tuple_variable_schema( 

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

1893 ) 

1894 v = SchemaValidator(schema) 

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

1896 ``` 

1897 

1898 Args: 

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

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

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

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

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

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

1905 serialization: Custom serialization schema 

1906 """ 

1907 return tuple_schema( 

1908 items_schema=[items_schema or any_schema()], 

1909 variadic_item_index=0, 

1910 min_length=min_length, 

1911 max_length=max_length, 

1912 strict=strict, 

1913 ref=ref, 

1914 metadata=metadata, 

1915 serialization=serialization, 

1916 ) 

1917 

1918 

1919class TupleSchema(TypedDict, total=False): 

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

1921 items_schema: Required[list[CoreSchema]] 

1922 variadic_item_index: int 

1923 min_length: int 

1924 max_length: int 

1925 fail_fast: bool 

1926 strict: bool 

1927 ref: str 

1928 metadata: dict[str, Any] 

1929 serialization: IncExSeqOrElseSerSchema 

1930 

1931 

1932def tuple_schema( 

1933 items_schema: list[CoreSchema], 

1934 *, 

1935 variadic_item_index: int | None = None, 

1936 min_length: int | None = None, 

1937 max_length: int | None = None, 

1938 fail_fast: bool | None = None, 

1939 strict: bool | None = None, 

1940 ref: str | None = None, 

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

1942 serialization: IncExSeqOrElseSerSchema | None = None, 

1943) -> TupleSchema: 

1944 """ 

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

1946 

1947 ```py 

1948 from pydantic_core import SchemaValidator, core_schema 

1949 

1950 schema = core_schema.tuple_schema( 

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

1952 variadic_item_index=1, 

1953 ) 

1954 v = SchemaValidator(schema) 

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

1956 ``` 

1957 

1958 Args: 

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

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

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

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

1963 fail_fast: Stop validation on the first error 

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

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

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

1967 serialization: Custom serialization schema 

1968 """ 

1969 return _dict_not_none( 

1970 type='tuple', 

1971 items_schema=items_schema, 

1972 variadic_item_index=variadic_item_index, 

1973 min_length=min_length, 

1974 max_length=max_length, 

1975 fail_fast=fail_fast, 

1976 strict=strict, 

1977 ref=ref, 

1978 metadata=metadata, 

1979 serialization=serialization, 

1980 ) 

1981 

1982 

1983class SetSchema(TypedDict, total=False): 

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

1985 items_schema: CoreSchema 

1986 min_length: int 

1987 max_length: int 

1988 fail_fast: bool 

1989 strict: bool 

1990 ref: str 

1991 metadata: dict[str, Any] 

1992 serialization: SerSchema 

1993 

1994 

1995def set_schema( 

1996 items_schema: CoreSchema | None = None, 

1997 *, 

1998 min_length: int | None = None, 

1999 max_length: int | None = None, 

2000 fail_fast: bool | None = None, 

2001 strict: bool | None = None, 

2002 ref: str | None = None, 

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

2004 serialization: SerSchema | None = None, 

2005) -> SetSchema: 

2006 """ 

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

2008 

2009 ```py 

2010 from pydantic_core import SchemaValidator, core_schema 

2011 

2012 schema = core_schema.set_schema( 

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

2014 ) 

2015 v = SchemaValidator(schema) 

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

2017 ``` 

2018 

2019 Args: 

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

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

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

2023 fail_fast: Stop validation on the first error 

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

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

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

2027 serialization: Custom serialization schema 

2028 """ 

2029 return _dict_not_none( 

2030 type='set', 

2031 items_schema=items_schema, 

2032 min_length=min_length, 

2033 max_length=max_length, 

2034 fail_fast=fail_fast, 

2035 strict=strict, 

2036 ref=ref, 

2037 metadata=metadata, 

2038 serialization=serialization, 

2039 ) 

2040 

2041 

2042class FrozenSetSchema(TypedDict, total=False): 

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

2044 items_schema: CoreSchema 

2045 min_length: int 

2046 max_length: int 

2047 fail_fast: bool 

2048 strict: bool 

2049 ref: str 

2050 metadata: dict[str, Any] 

2051 serialization: SerSchema 

2052 

2053 

2054def frozenset_schema( 

2055 items_schema: CoreSchema | None = None, 

2056 *, 

2057 min_length: int | None = None, 

2058 max_length: int | None = None, 

2059 fail_fast: bool | None = None, 

2060 strict: bool | None = None, 

2061 ref: str | None = None, 

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

2063 serialization: SerSchema | None = None, 

2064) -> FrozenSetSchema: 

2065 """ 

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

2067 

2068 ```py 

2069 from pydantic_core import SchemaValidator, core_schema 

2070 

2071 schema = core_schema.frozenset_schema( 

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

2073 ) 

2074 v = SchemaValidator(schema) 

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

2076 ``` 

2077 

2078 Args: 

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

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

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

2082 fail_fast: Stop validation on the first error 

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

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

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

2086 serialization: Custom serialization schema 

2087 """ 

2088 return _dict_not_none( 

2089 type='frozenset', 

2090 items_schema=items_schema, 

2091 min_length=min_length, 

2092 max_length=max_length, 

2093 fail_fast=fail_fast, 

2094 strict=strict, 

2095 ref=ref, 

2096 metadata=metadata, 

2097 serialization=serialization, 

2098 ) 

2099 

2100 

2101class GeneratorSchema(TypedDict, total=False): 

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

2103 items_schema: CoreSchema 

2104 min_length: int 

2105 max_length: int 

2106 ref: str 

2107 metadata: dict[str, Any] 

2108 serialization: IncExSeqOrElseSerSchema 

2109 

2110 

2111def generator_schema( 

2112 items_schema: CoreSchema | None = None, 

2113 *, 

2114 min_length: int | None = None, 

2115 max_length: int | None = None, 

2116 ref: str | None = None, 

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

2118 serialization: IncExSeqOrElseSerSchema | None = None, 

2119) -> GeneratorSchema: 

2120 """ 

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

2122 

2123 ```py 

2124 from typing import Iterator 

2125 from pydantic_core import SchemaValidator, core_schema 

2126 

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

2128 yield 1 

2129 

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

2131 v = SchemaValidator(schema) 

2132 v.validate_python(gen()) 

2133 ``` 

2134 

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

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

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

2138 

2139 Args: 

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

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

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

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

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

2145 serialization: Custom serialization schema 

2146 """ 

2147 return _dict_not_none( 

2148 type='generator', 

2149 items_schema=items_schema, 

2150 min_length=min_length, 

2151 max_length=max_length, 

2152 ref=ref, 

2153 metadata=metadata, 

2154 serialization=serialization, 

2155 ) 

2156 

2157 

2158IncExDict: TypeAlias = set[int | str] 

2159 

2160 

2161class IncExDictSerSchema(TypedDict, total=False): 

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

2163 include: IncExDict 

2164 exclude: IncExDict 

2165 

2166 

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

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

2169 

2170 

2171IncExDictOrElseSerSchema: TypeAlias = Union[IncExDictSerSchema, SerSchema] # noqa: UP007 (TypeError when evaluating) 

2172 

2173 

2174class DictSchema(TypedDict, total=False): 

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

2176 keys_schema: CoreSchema # default: AnySchema 

2177 values_schema: CoreSchema # default: AnySchema 

2178 min_length: int 

2179 max_length: int 

2180 fail_fast: bool 

2181 strict: bool 

2182 ref: str 

2183 metadata: dict[str, Any] 

2184 serialization: IncExDictOrElseSerSchema 

2185 

2186 

2187def dict_schema( 

2188 keys_schema: CoreSchema | None = None, 

2189 values_schema: CoreSchema | None = None, 

2190 *, 

2191 min_length: int | None = None, 

2192 max_length: int | None = None, 

2193 fail_fast: bool | None = None, 

2194 strict: bool | None = None, 

2195 ref: str | None = None, 

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

2197 serialization: SerSchema | None = None, 

2198) -> DictSchema: 

2199 """ 

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

2201 

2202 ```py 

2203 from pydantic_core import SchemaValidator, core_schema 

2204 

2205 schema = core_schema.dict_schema( 

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

2207 ) 

2208 v = SchemaValidator(schema) 

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

2210 ``` 

2211 

2212 Args: 

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

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

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

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

2217 fail_fast: Stop validation on the first error 

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

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

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

2221 serialization: Custom serialization schema 

2222 """ 

2223 return _dict_not_none( 

2224 type='dict', 

2225 keys_schema=keys_schema, 

2226 values_schema=values_schema, 

2227 min_length=min_length, 

2228 max_length=max_length, 

2229 fail_fast=fail_fast, 

2230 strict=strict, 

2231 ref=ref, 

2232 metadata=metadata, 

2233 serialization=serialization, 

2234 ) 

2235 

2236 

2237class FrozenDictSchema(TypedDict, total=False): 

2238 type: Required[Literal['frozendict']] 

2239 keys_schema: CoreSchema # default: AnySchema 

2240 values_schema: CoreSchema # default: AnySchema 

2241 min_length: int 

2242 max_length: int 

2243 fail_fast: bool 

2244 strict: bool 

2245 ref: str 

2246 metadata: dict[str, Any] 

2247 serialization: IncExDictOrElseSerSchema 

2248 

2249 

2250def frozendict_schema( 

2251 keys_schema: CoreSchema | None = None, 

2252 values_schema: CoreSchema | None = None, 

2253 *, 

2254 min_length: int | None = None, 

2255 max_length: int | None = None, 

2256 fail_fast: bool | None = None, 

2257 strict: bool | None = None, 

2258 ref: str | None = None, 

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

2260 serialization: SerSchema | None = None, 

2261) -> FrozenDictSchema: 

2262 """ 

2263 Returns a schema that matches a `frozendict` value, e.g.: 

2264 

2265 ```py {requires="3.15" lint="skip"} 

2266 from pydantic_core import SchemaValidator, core_schema 

2267 

2268 schema = core_schema.frozendict_schema( 

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

2270 ) 

2271 v = SchemaValidator(schema) 

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

2273 ``` 

2274 

2275 !!! note 

2276 The `frozendict` builtin type is only available in Python 3.15 and above. 

2277 Using this schema on older Python versions will raise a [`SchemaError`][pydantic_core.SchemaError] 

2278 when the validator or serializer is built. 

2279 

2280 Args: 

2281 keys_schema: The value must be a frozendict with keys that match this schema 

2282 values_schema: The value must be a frozendict with values that match this schema 

2283 min_length: The value must be a frozendict with at least this many items 

2284 max_length: The value must be a frozendict with at most this many items 

2285 fail_fast: Stop validation on the first error 

2286 strict: Whether the input should be validated with strict mode 

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

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

2289 serialization: Custom serialization schema 

2290 """ 

2291 return _dict_not_none( 

2292 type='frozendict', 

2293 keys_schema=keys_schema, 

2294 values_schema=values_schema, 

2295 min_length=min_length, 

2296 max_length=max_length, 

2297 fail_fast=fail_fast, 

2298 strict=strict, 

2299 ref=ref, 

2300 metadata=metadata, 

2301 serialization=serialization, 

2302 ) 

2303 

2304 

2305class OrderedDictSchema(TypedDict, total=False): 

2306 type: Required[Literal['ordered-dict']] 

2307 keys_schema: CoreSchema # default: AnySchema 

2308 values_schema: CoreSchema # default: AnySchema 

2309 min_length: int 

2310 max_length: int 

2311 fail_fast: bool 

2312 strict: bool 

2313 ref: str 

2314 metadata: dict[str, Any] 

2315 serialization: IncExDictOrElseSerSchema 

2316 

2317 

2318def ordered_dict_schema( 

2319 keys_schema: CoreSchema | None = None, 

2320 values_schema: CoreSchema | None = None, 

2321 *, 

2322 min_length: int | None = None, 

2323 max_length: int | None = None, 

2324 fail_fast: bool | None = None, 

2325 strict: bool | None = None, 

2326 ref: str | None = None, 

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

2328 serialization: SerSchema | None = None, 

2329) -> OrderedDictSchema: 

2330 """ 

2331 Returns a schema that matches a [`collections.OrderedDict`][] value, e.g.: 

2332 

2333 ```py 

2334 from collections import OrderedDict 

2335 

2336 from pydantic_core import SchemaValidator, core_schema 

2337 

2338 schema = core_schema.ordered_dict_schema( 

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

2340 ) 

2341 v = SchemaValidator(schema) 

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

2343 ``` 

2344 

2345 In lax mode, any mapping is accepted and converted to an `OrderedDict`. 

2346 

2347 Args: 

2348 keys_schema: The value must be an `OrderedDict` with keys that match this schema 

2349 values_schema: The value must be an `OrderedDict` with values that match this schema 

2350 min_length: The value must be an `OrderedDict` with at least this many items 

2351 max_length: The value must be an `OrderedDict` with at most this many items 

2352 fail_fast: Stop validation on the first error 

2353 strict: The value must be an `OrderedDict` instance 

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

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

2356 serialization: Custom serialization schema 

2357 """ 

2358 return _dict_not_none( 

2359 type='ordered-dict', 

2360 keys_schema=keys_schema, 

2361 values_schema=values_schema, 

2362 min_length=min_length, 

2363 max_length=max_length, 

2364 fail_fast=fail_fast, 

2365 strict=strict, 

2366 ref=ref, 

2367 metadata=metadata, 

2368 serialization=serialization, 

2369 ) 

2370 

2371 

2372class CounterSchema(TypedDict, total=False): 

2373 type: Required[Literal['counter']] 

2374 keys_schema: CoreSchema # default: AnySchema 

2375 values_schema: CoreSchema # default: AnySchema 

2376 min_length: int 

2377 max_length: int 

2378 fail_fast: bool 

2379 strict: bool 

2380 ref: str 

2381 metadata: dict[str, Any] 

2382 serialization: IncExDictOrElseSerSchema 

2383 

2384 

2385def counter_schema( 

2386 keys_schema: CoreSchema | None = None, 

2387 values_schema: CoreSchema | None = None, 

2388 *, 

2389 min_length: int | None = None, 

2390 max_length: int | None = None, 

2391 fail_fast: bool | None = None, 

2392 strict: bool | None = None, 

2393 ref: str | None = None, 

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

2395 serialization: SerSchema | None = None, 

2396) -> CounterSchema: 

2397 """ 

2398 Returns a schema that matches a [`collections.Counter`][] value, e.g.: 

2399 

2400 ```py 

2401 from collections import Counter 

2402 

2403 from pydantic_core import SchemaValidator, core_schema 

2404 

2405 schema = core_schema.counter_schema( 

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

2407 ) 

2408 v = SchemaValidator(schema) 

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

2410 ``` 

2411 

2412 In lax mode, any mapping is accepted and converted to a `Counter`. 

2413 

2414 Args: 

2415 keys_schema: The value must be a `Counter` with keys that match this schema 

2416 values_schema: The value must be a `Counter` with values that match this schema 

2417 min_length: The value must be a `Counter` with at least this many items 

2418 max_length: The value must be a `Counter` with at most this many items 

2419 fail_fast: Stop validation on the first error 

2420 strict: The value must be a `Counter` instance 

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

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

2423 serialization: Custom serialization schema 

2424 """ 

2425 return _dict_not_none( 

2426 type='counter', 

2427 keys_schema=keys_schema, 

2428 values_schema=values_schema, 

2429 min_length=min_length, 

2430 max_length=max_length, 

2431 fail_fast=fail_fast, 

2432 strict=strict, 

2433 ref=ref, 

2434 metadata=metadata, 

2435 serialization=serialization, 

2436 ) 

2437 

2438 

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

2440NoInfoValidatorFunction: TypeAlias = Callable[[Any], Any] 

2441 

2442 

2443class NoInfoValidatorFunctionSchema(TypedDict): 

2444 type: Literal['no-info'] 

2445 function: NoInfoValidatorFunction 

2446 

2447 

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

2449WithInfoValidatorFunction: TypeAlias = Callable[[Any, ValidationInfo[Any]], Any] 

2450 

2451 

2452class WithInfoValidatorFunctionSchema(TypedDict, total=False): 

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

2454 function: Required[WithInfoValidatorFunction] 

2455 field_name: str # deprecated 

2456 

2457 

2458ValidationFunction: TypeAlias = NoInfoValidatorFunctionSchema | WithInfoValidatorFunctionSchema 

2459 

2460 

2461class _ValidatorFunctionSchema(TypedDict, total=False): 

2462 function: Required[ValidationFunction] 

2463 schema: Required[CoreSchema] 

2464 ref: str 

2465 metadata: dict[str, Any] 

2466 serialization: SerSchema 

2467 

2468 

2469class BeforeValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): 

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

2471 json_schema_input_schema: CoreSchema 

2472 

2473 

2474def no_info_before_validator_function( 

2475 function: NoInfoValidatorFunction, 

2476 schema: CoreSchema, 

2477 *, 

2478 ref: str | None = None, 

2479 json_schema_input_schema: CoreSchema | None = None, 

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

2481 serialization: SerSchema | None = None, 

2482) -> BeforeValidatorFunctionSchema: 

2483 """ 

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

2485 

2486 ```py 

2487 from pydantic_core import SchemaValidator, core_schema 

2488 

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

2490 return v.decode() + 'world' 

2491 

2492 func_schema = core_schema.no_info_before_validator_function( 

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

2494 ) 

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

2496 

2497 v = SchemaValidator(schema) 

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

2499 ``` 

2500 

2501 Args: 

2502 function: The validator function to call 

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

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

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

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

2507 serialization: Custom serialization schema 

2508 """ 

2509 return _dict_not_none( 

2510 type='function-before', 

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

2512 schema=schema, 

2513 ref=ref, 

2514 json_schema_input_schema=json_schema_input_schema, 

2515 metadata=metadata, 

2516 serialization=serialization, 

2517 ) 

2518 

2519 

2520@overload 

2521@deprecated( 

2522 'The `field_name` argument on `with_info_before_validator_function` is deprecated, ' 

2523 'it will be passed to the function through `ValidationState` instead.' 

2524) 

2525def with_info_before_validator_function( 

2526 function: WithInfoValidatorFunction, 

2527 schema: CoreSchema, 

2528 *, 

2529 field_name: str | None, 

2530 ref: str | None = None, 

2531 json_schema_input_schema: CoreSchema | None = None, 

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

2533 serialization: SerSchema | None = None, 

2534) -> BeforeValidatorFunctionSchema: ... 

2535 

2536 

2537@overload 

2538def with_info_before_validator_function( 

2539 function: WithInfoValidatorFunction, 

2540 schema: CoreSchema, 

2541 *, 

2542 ref: str | None = None, 

2543 json_schema_input_schema: CoreSchema | None = None, 

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

2545 serialization: SerSchema | None = None, 

2546) -> BeforeValidatorFunctionSchema: ... 

2547 

2548 

2549def with_info_before_validator_function( 

2550 function: WithInfoValidatorFunction, 

2551 schema: CoreSchema, 

2552 *, 

2553 field_name: str | None = None, 

2554 ref: str | None = None, 

2555 json_schema_input_schema: CoreSchema | None = None, 

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

2557 serialization: SerSchema | None = None, 

2558) -> BeforeValidatorFunctionSchema: 

2559 """ 

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

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

2562 

2563 ```py 

2564 from pydantic_core import SchemaValidator, core_schema 

2565 

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

2567 assert info.data is not None 

2568 assert info.field_name is not None 

2569 return v.decode() + 'world' 

2570 

2571 func_schema = core_schema.with_info_before_validator_function( 

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

2573 ) 

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

2575 

2576 v = SchemaValidator(schema) 

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

2578 ``` 

2579 

2580 Args: 

2581 function: The validator function to call 

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

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

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

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

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

2587 serialization: Custom serialization schema 

2588 """ 

2589 if field_name is not None: 

2590 warnings.warn( 

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

2592 DeprecationWarning, 

2593 stacklevel=2, 

2594 ) 

2595 

2596 return _dict_not_none( 

2597 type='function-before', 

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

2599 schema=schema, 

2600 ref=ref, 

2601 json_schema_input_schema=json_schema_input_schema, 

2602 metadata=metadata, 

2603 serialization=serialization, 

2604 ) 

2605 

2606 

2607class AfterValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): 

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

2609 

2610 

2611def no_info_after_validator_function( 

2612 function: NoInfoValidatorFunction, 

2613 schema: CoreSchema, 

2614 *, 

2615 ref: str | None = None, 

2616 json_schema_input_schema: CoreSchema | None = None, 

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

2618 serialization: SerSchema | None = None, 

2619) -> AfterValidatorFunctionSchema: 

2620 """ 

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

2622 

2623 ```py 

2624 from pydantic_core import SchemaValidator, core_schema 

2625 

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

2627 return v + 'world' 

2628 

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

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

2631 

2632 v = SchemaValidator(schema) 

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

2634 ``` 

2635 

2636 Args: 

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

2638 schema: The schema to validate before the validator function 

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

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

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

2642 serialization: Custom serialization schema 

2643 """ 

2644 return _dict_not_none( 

2645 type='function-after', 

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

2647 schema=schema, 

2648 ref=ref, 

2649 json_schema_input_schema=json_schema_input_schema, 

2650 metadata=metadata, 

2651 serialization=serialization, 

2652 ) 

2653 

2654 

2655@overload 

2656@deprecated( 

2657 'The `field_name` argument on `with_info_after_validator_function` is deprecated, ' 

2658 'it will be passed to the function through `ValidationState` instead.' 

2659) 

2660def with_info_after_validator_function( 

2661 function: WithInfoValidatorFunction, 

2662 schema: CoreSchema, 

2663 *, 

2664 field_name: str | None, 

2665 ref: str | None = None, 

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

2667 serialization: SerSchema | None = None, 

2668) -> AfterValidatorFunctionSchema: ... 

2669 

2670 

2671@overload 

2672def with_info_after_validator_function( 

2673 function: WithInfoValidatorFunction, 

2674 schema: CoreSchema, 

2675 *, 

2676 ref: str | None = None, 

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

2678 serialization: SerSchema | None = None, 

2679) -> AfterValidatorFunctionSchema: ... 

2680 

2681 

2682def with_info_after_validator_function( 

2683 function: WithInfoValidatorFunction, 

2684 schema: CoreSchema, 

2685 *, 

2686 field_name: str | None = None, 

2687 ref: str | None = None, 

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

2689 serialization: SerSchema | None = None, 

2690) -> AfterValidatorFunctionSchema: 

2691 """ 

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

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

2694 

2695 ```py 

2696 from pydantic_core import SchemaValidator, core_schema 

2697 

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

2699 assert info.data is not None 

2700 assert info.field_name is not None 

2701 return v + 'world' 

2702 

2703 func_schema = core_schema.with_info_after_validator_function( 

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

2705 ) 

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

2707 

2708 v = SchemaValidator(schema) 

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

2710 ``` 

2711 

2712 Args: 

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

2714 schema: The schema to validate before the validator function 

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

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

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

2718 serialization: Custom serialization schema 

2719 """ 

2720 if field_name is not None: 

2721 warnings.warn( 

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

2723 DeprecationWarning, 

2724 stacklevel=2, 

2725 ) 

2726 

2727 return _dict_not_none( 

2728 type='function-after', 

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

2730 schema=schema, 

2731 ref=ref, 

2732 metadata=metadata, 

2733 serialization=serialization, 

2734 ) 

2735 

2736 

2737class ValidatorFunctionWrapHandler(Protocol): 

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

2739 ... 

2740 

2741 

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

2743NoInfoWrapValidatorFunction: TypeAlias = Callable[[Any, ValidatorFunctionWrapHandler], Any] 

2744 

2745 

2746class NoInfoWrapValidatorFunctionSchema(TypedDict): 

2747 type: Literal['no-info'] 

2748 function: NoInfoWrapValidatorFunction 

2749 

2750 

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

2752WithInfoWrapValidatorFunction: TypeAlias = Callable[[Any, ValidatorFunctionWrapHandler, ValidationInfo[Any]], Any] 

2753 

2754 

2755class WithInfoWrapValidatorFunctionSchema(TypedDict, total=False): 

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

2757 function: Required[WithInfoWrapValidatorFunction] 

2758 field_name: str # deprecated 

2759 

2760 

2761WrapValidatorFunction: TypeAlias = NoInfoWrapValidatorFunctionSchema | WithInfoWrapValidatorFunctionSchema 

2762 

2763 

2764class WrapValidatorFunctionSchema(TypedDict, total=False): 

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

2766 function: Required[WrapValidatorFunction] 

2767 schema: Required[CoreSchema] 

2768 ref: str 

2769 json_schema_input_schema: CoreSchema 

2770 metadata: dict[str, Any] 

2771 serialization: SerSchema 

2772 

2773 

2774def no_info_wrap_validator_function( 

2775 function: NoInfoWrapValidatorFunction, 

2776 schema: CoreSchema, 

2777 *, 

2778 ref: str | None = None, 

2779 json_schema_input_schema: CoreSchema | None = None, 

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

2781 serialization: SerSchema | None = None, 

2782) -> WrapValidatorFunctionSchema: 

2783 """ 

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

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

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

2787 

2788 ```py 

2789 from pydantic_core import SchemaValidator, core_schema 

2790 

2791 def fn( 

2792 v: str, 

2793 validator: core_schema.ValidatorFunctionWrapHandler, 

2794 ) -> str: 

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

2796 

2797 schema = core_schema.no_info_wrap_validator_function( 

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

2799 ) 

2800 v = SchemaValidator(schema) 

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

2802 ``` 

2803 

2804 Args: 

2805 function: The validator function to call 

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

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

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

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

2810 serialization: Custom serialization schema 

2811 """ 

2812 return _dict_not_none( 

2813 type='function-wrap', 

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

2815 schema=schema, 

2816 json_schema_input_schema=json_schema_input_schema, 

2817 ref=ref, 

2818 metadata=metadata, 

2819 serialization=serialization, 

2820 ) 

2821 

2822 

2823@overload 

2824@deprecated( 

2825 'The `field_name` argument on `with_info_wrap_validator_function` is deprecated, ' 

2826 'it will be passed to the function through `ValidationState` instead.' 

2827) 

2828def with_info_wrap_validator_function( 

2829 function: WithInfoWrapValidatorFunction, 

2830 schema: CoreSchema, 

2831 *, 

2832 field_name: str | None, 

2833 json_schema_input_schema: CoreSchema | None = None, 

2834 ref: str | None = None, 

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

2836 serialization: SerSchema | None = None, 

2837) -> WrapValidatorFunctionSchema: ... 

2838 

2839 

2840@overload 

2841def with_info_wrap_validator_function( 

2842 function: WithInfoWrapValidatorFunction, 

2843 schema: CoreSchema, 

2844 *, 

2845 json_schema_input_schema: CoreSchema | None = None, 

2846 ref: str | None = None, 

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

2848 serialization: SerSchema | None = None, 

2849) -> WrapValidatorFunctionSchema: ... 

2850 

2851 

2852def with_info_wrap_validator_function( 

2853 function: WithInfoWrapValidatorFunction, 

2854 schema: CoreSchema, 

2855 *, 

2856 field_name: str | None = None, 

2857 json_schema_input_schema: CoreSchema | None = None, 

2858 ref: str | None = None, 

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

2860 serialization: SerSchema | None = None, 

2861) -> WrapValidatorFunctionSchema: 

2862 """ 

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

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

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

2866 

2867 ```py 

2868 from pydantic_core import SchemaValidator, core_schema 

2869 

2870 def fn( 

2871 v: str, 

2872 validator: core_schema.ValidatorFunctionWrapHandler, 

2873 info: core_schema.ValidationInfo, 

2874 ) -> str: 

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

2876 

2877 schema = core_schema.with_info_wrap_validator_function( 

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

2879 ) 

2880 v = SchemaValidator(schema) 

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

2882 ``` 

2883 

2884 Args: 

2885 function: The validator function to call 

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

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

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

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

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

2891 serialization: Custom serialization schema 

2892 """ 

2893 if field_name is not None: 

2894 warnings.warn( 

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

2896 DeprecationWarning, 

2897 stacklevel=2, 

2898 ) 

2899 

2900 return _dict_not_none( 

2901 type='function-wrap', 

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

2903 schema=schema, 

2904 json_schema_input_schema=json_schema_input_schema, 

2905 ref=ref, 

2906 metadata=metadata, 

2907 serialization=serialization, 

2908 ) 

2909 

2910 

2911class PlainValidatorFunctionSchema(TypedDict, total=False): 

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

2913 function: Required[ValidationFunction] 

2914 ref: str 

2915 json_schema_input_schema: CoreSchema 

2916 metadata: dict[str, Any] 

2917 serialization: SerSchema 

2918 

2919 

2920def no_info_plain_validator_function( 

2921 function: NoInfoValidatorFunction, 

2922 *, 

2923 ref: str | None = None, 

2924 json_schema_input_schema: CoreSchema | None = None, 

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

2926 serialization: SerSchema | None = None, 

2927) -> PlainValidatorFunctionSchema: 

2928 """ 

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

2930 

2931 ```py 

2932 from pydantic_core import SchemaValidator, core_schema 

2933 

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

2935 assert 'hello' in v 

2936 return v + 'world' 

2937 

2938 schema = core_schema.no_info_plain_validator_function(function=fn) 

2939 v = SchemaValidator(schema) 

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

2941 ``` 

2942 

2943 Args: 

2944 function: The validator function to call 

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

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

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

2948 serialization: Custom serialization schema 

2949 """ 

2950 return _dict_not_none( 

2951 type='function-plain', 

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

2953 ref=ref, 

2954 json_schema_input_schema=json_schema_input_schema, 

2955 metadata=metadata, 

2956 serialization=serialization, 

2957 ) 

2958 

2959 

2960@overload 

2961@deprecated( 

2962 'The `field_name` argument on `with_info_plain_validator_function` is deprecated, ' 

2963 'it will be passed to the function through `ValidationState` instead.' 

2964) 

2965def with_info_plain_validator_function( 

2966 function: WithInfoValidatorFunction, 

2967 *, 

2968 field_name: str | None, 

2969 ref: str | None = None, 

2970 json_schema_input_schema: CoreSchema | None = None, 

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

2972 serialization: SerSchema | None = None, 

2973) -> PlainValidatorFunctionSchema: ... 

2974 

2975 

2976@overload 

2977def with_info_plain_validator_function( 

2978 function: WithInfoValidatorFunction, 

2979 *, 

2980 ref: str | None = None, 

2981 json_schema_input_schema: CoreSchema | None = None, 

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

2983 serialization: SerSchema | None = None, 

2984) -> PlainValidatorFunctionSchema: ... 

2985 

2986 

2987def with_info_plain_validator_function( 

2988 function: WithInfoValidatorFunction, 

2989 *, 

2990 field_name: str | None = None, 

2991 ref: str | None = None, 

2992 json_schema_input_schema: CoreSchema | None = None, 

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

2994 serialization: SerSchema | None = None, 

2995) -> PlainValidatorFunctionSchema: 

2996 """ 

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

2998 

2999 ```py 

3000 from pydantic_core import SchemaValidator, core_schema 

3001 

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

3003 assert 'hello' in v 

3004 return v + 'world' 

3005 

3006 schema = core_schema.with_info_plain_validator_function(function=fn) 

3007 v = SchemaValidator(schema) 

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

3009 ``` 

3010 

3011 Args: 

3012 function: The validator function to call 

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

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

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

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

3017 serialization: Custom serialization schema 

3018 """ 

3019 if field_name is not None: 

3020 warnings.warn( 

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

3022 DeprecationWarning, 

3023 stacklevel=2, 

3024 ) 

3025 

3026 return _dict_not_none( 

3027 type='function-plain', 

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

3029 ref=ref, 

3030 json_schema_input_schema=json_schema_input_schema, 

3031 metadata=metadata, 

3032 serialization=serialization, 

3033 ) 

3034 

3035 

3036class WithDefaultSchema(TypedDict, total=False): 

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

3038 schema: Required[CoreSchema] 

3039 default: Any 

3040 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] 

3041 default_factory_takes_data: bool 

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

3043 validate_default: bool # default: False 

3044 strict: bool 

3045 ref: str 

3046 metadata: dict[str, Any] 

3047 serialization: SerSchema 

3048 

3049 

3050def with_default_schema( 

3051 schema: CoreSchema, 

3052 *, 

3053 default: Any = PydanticUndefined, 

3054 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None, 

3055 default_factory_takes_data: bool | None = None, 

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

3057 validate_default: bool | None = None, 

3058 strict: bool | None = None, 

3059 ref: str | None = None, 

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

3061 serialization: SerSchema | None = None, 

3062) -> WithDefaultSchema: 

3063 """ 

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

3065 

3066 ```py 

3067 from pydantic_core import SchemaValidator, core_schema 

3068 

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

3070 wrapper_schema = core_schema.typed_dict_schema( 

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

3072 ) 

3073 v = SchemaValidator(wrapper_schema) 

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

3075 ``` 

3076 

3077 Args: 

3078 schema: The schema to add a default value to 

3079 default: The default value to use 

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

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

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

3083 validate_default: Whether the default value should be validated 

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

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

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

3087 serialization: Custom serialization schema 

3088 """ 

3089 s = _dict_not_none( 

3090 type='default', 

3091 schema=schema, 

3092 default_factory=default_factory, 

3093 default_factory_takes_data=default_factory_takes_data, 

3094 on_error=on_error, 

3095 validate_default=validate_default, 

3096 strict=strict, 

3097 ref=ref, 

3098 metadata=metadata, 

3099 serialization=serialization, 

3100 ) 

3101 if default is not PydanticUndefined: 

3102 s['default'] = default 

3103 return s 

3104 

3105 

3106class NullableSchema(TypedDict, total=False): 

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

3108 schema: Required[CoreSchema] 

3109 strict: bool 

3110 ref: str 

3111 metadata: dict[str, Any] 

3112 serialization: SerSchema 

3113 

3114 

3115def nullable_schema( 

3116 schema: CoreSchema, 

3117 *, 

3118 strict: bool | None = None, 

3119 ref: str | None = None, 

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

3121 serialization: SerSchema | None = None, 

3122) -> NullableSchema: 

3123 """ 

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

3125 

3126 ```py 

3127 from pydantic_core import SchemaValidator, core_schema 

3128 

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

3130 v = SchemaValidator(schema) 

3131 assert v.validate_python(None) is None 

3132 ``` 

3133 

3134 Args: 

3135 schema: The schema to wrap 

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

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

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

3139 serialization: Custom serialization schema 

3140 """ 

3141 return _dict_not_none( 

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

3143 ) 

3144 

3145 

3146class UnionSchema(TypedDict, total=False): 

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

3148 choices: Required[list[CoreSchema | tuple[CoreSchema, str]]] 

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

3150 auto_collapse: bool 

3151 custom_error_type: str 

3152 custom_error_message: str 

3153 custom_error_context: dict[str, str | int | float] 

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

3155 strict: bool 

3156 ref: str 

3157 metadata: dict[str, Any] 

3158 serialization: SerSchema 

3159 

3160 

3161def union_schema( 

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

3163 *, 

3164 auto_collapse: bool | None = None, 

3165 custom_error_type: str | None = None, 

3166 custom_error_message: str | None = None, 

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

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

3169 ref: str | None = None, 

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

3171 serialization: SerSchema | None = None, 

3172) -> UnionSchema: 

3173 """ 

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

3175 

3176 ```py 

3177 from pydantic_core import SchemaValidator, core_schema 

3178 

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

3180 v = SchemaValidator(schema) 

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

3182 assert v.validate_python(1) == 1 

3183 ``` 

3184 

3185 Args: 

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

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

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

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

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

3191 mode: How to select which choice to return 

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

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

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

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

3196 serialization: Custom serialization schema 

3197 """ 

3198 return _dict_not_none( 

3199 type='union', 

3200 choices=choices, 

3201 auto_collapse=auto_collapse, 

3202 custom_error_type=custom_error_type, 

3203 custom_error_message=custom_error_message, 

3204 custom_error_context=custom_error_context, 

3205 mode=mode, 

3206 ref=ref, 

3207 metadata=metadata, 

3208 serialization=serialization, 

3209 ) 

3210 

3211 

3212class TaggedUnionSchema(TypedDict, total=False): 

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

3214 choices: Required[dict[Any, CoreSchema]] 

3215 discriminator: Required[str | list[str | int] | list[list[str | int]] | Callable[[Any], Any]] 

3216 custom_error_type: str 

3217 custom_error_message: str 

3218 custom_error_context: dict[str, str | int | float] 

3219 strict: bool 

3220 from_attributes: bool # default: True 

3221 ref: str 

3222 metadata: dict[str, Any] 

3223 serialization: SerSchema 

3224 

3225 

3226def tagged_union_schema( 

3227 choices: dict[Any, CoreSchema], 

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

3229 *, 

3230 custom_error_type: str | None = None, 

3231 custom_error_message: str | None = None, 

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

3233 strict: bool | None = None, 

3234 from_attributes: bool | None = None, 

3235 ref: str | None = None, 

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

3237 serialization: SerSchema | None = None, 

3238) -> TaggedUnionSchema: 

3239 """ 

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

3241 

3242 ```py 

3243 from pydantic_core import SchemaValidator, core_schema 

3244 

3245 apple_schema = core_schema.typed_dict_schema( 

3246 { 

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

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

3249 } 

3250 ) 

3251 banana_schema = core_schema.typed_dict_schema( 

3252 { 

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

3254 'spam': core_schema.typed_dict_field( 

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

3256 ), 

3257 } 

3258 ) 

3259 schema = core_schema.tagged_union_schema( 

3260 choices={ 

3261 'apple': apple_schema, 

3262 'banana': banana_schema, 

3263 }, 

3264 discriminator='foo', 

3265 ) 

3266 v = SchemaValidator(schema) 

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

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

3269 'foo': 'banana', 

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

3271 } 

3272 ``` 

3273 

3274 Args: 

3275 choices: The schemas to match 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3292 serialization: Custom serialization schema 

3293 """ 

3294 return _dict_not_none( 

3295 type='tagged-union', 

3296 choices=choices, 

3297 discriminator=discriminator, 

3298 custom_error_type=custom_error_type, 

3299 custom_error_message=custom_error_message, 

3300 custom_error_context=custom_error_context, 

3301 strict=strict, 

3302 from_attributes=from_attributes, 

3303 ref=ref, 

3304 metadata=metadata, 

3305 serialization=serialization, 

3306 ) 

3307 

3308 

3309class ChainSchema(TypedDict, total=False): 

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

3311 steps: Required[list[CoreSchema]] 

3312 ref: str 

3313 metadata: dict[str, Any] 

3314 serialization: SerSchema 

3315 

3316 

3317def chain_schema( 

3318 steps: list[CoreSchema], 

3319 *, 

3320 ref: str | None = None, 

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

3322 serialization: SerSchema | None = None, 

3323) -> ChainSchema: 

3324 """ 

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

3326 

3327 ```py 

3328 from pydantic_core import SchemaValidator, core_schema 

3329 

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

3331 assert 'hello' in v 

3332 return v + ' world' 

3333 

3334 fn_schema = core_schema.with_info_plain_validator_function(function=fn) 

3335 schema = core_schema.chain_schema( 

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

3337 ) 

3338 v = SchemaValidator(schema) 

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

3340 ``` 

3341 

3342 Args: 

3343 steps: The schemas to chain 

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

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

3346 serialization: Custom serialization schema 

3347 """ 

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

3349 

3350 

3351class LaxOrStrictSchema(TypedDict, total=False): 

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

3353 lax_schema: Required[CoreSchema] 

3354 strict_schema: Required[CoreSchema] 

3355 strict: bool 

3356 ref: str 

3357 metadata: dict[str, Any] 

3358 serialization: SerSchema 

3359 

3360 

3361def lax_or_strict_schema( 

3362 lax_schema: CoreSchema, 

3363 strict_schema: CoreSchema, 

3364 *, 

3365 strict: bool | None = None, 

3366 ref: str | None = None, 

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

3368 serialization: SerSchema | None = None, 

3369) -> LaxOrStrictSchema: 

3370 """ 

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

3372 

3373 ```py 

3374 from pydantic_core import SchemaValidator, core_schema 

3375 

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

3377 assert 'hello' in v 

3378 return v + ' world' 

3379 

3380 lax_schema = core_schema.int_schema(strict=False) 

3381 strict_schema = core_schema.int_schema(strict=True) 

3382 

3383 schema = core_schema.lax_or_strict_schema( 

3384 lax_schema=lax_schema, strict_schema=strict_schema, strict=True 

3385 ) 

3386 v = SchemaValidator(schema) 

3387 assert v.validate_python(123) == 123 

3388 

3389 schema = core_schema.lax_or_strict_schema( 

3390 lax_schema=lax_schema, strict_schema=strict_schema, strict=False 

3391 ) 

3392 v = SchemaValidator(schema) 

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

3394 ``` 

3395 

3396 Args: 

3397 lax_schema: The lax schema to use 

3398 strict_schema: The strict schema to use 

3399 strict: Whether the strict schema should be used 

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

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

3402 serialization: Custom serialization schema 

3403 """ 

3404 return _dict_not_none( 

3405 type='lax-or-strict', 

3406 lax_schema=lax_schema, 

3407 strict_schema=strict_schema, 

3408 strict=strict, 

3409 ref=ref, 

3410 metadata=metadata, 

3411 serialization=serialization, 

3412 ) 

3413 

3414 

3415class JsonOrPythonSchema(TypedDict, total=False): 

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

3417 json_schema: Required[CoreSchema] 

3418 python_schema: Required[CoreSchema] 

3419 ref: str 

3420 metadata: dict[str, Any] 

3421 serialization: SerSchema 

3422 

3423 

3424def json_or_python_schema( 

3425 json_schema: CoreSchema, 

3426 python_schema: CoreSchema, 

3427 *, 

3428 ref: str | None = None, 

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

3430 serialization: SerSchema | None = None, 

3431) -> JsonOrPythonSchema: 

3432 """ 

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

3434 

3435 ```py 

3436 from pydantic_core import SchemaValidator, ValidationError, core_schema 

3437 

3438 v = SchemaValidator( 

3439 core_schema.json_or_python_schema( 

3440 json_schema=core_schema.int_schema(), 

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

3442 ) 

3443 ) 

3444 

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

3446 

3447 try: 

3448 v.validate_python('123') 

3449 except ValidationError: 

3450 pass 

3451 else: 

3452 raise AssertionError('Validation should have failed') 

3453 ``` 

3454 

3455 Args: 

3456 json_schema: The schema to use for Json inputs 

3457 python_schema: The schema to use for Python inputs 

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

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

3460 serialization: Custom serialization schema 

3461 """ 

3462 return _dict_not_none( 

3463 type='json-or-python', 

3464 json_schema=json_schema, 

3465 python_schema=python_schema, 

3466 ref=ref, 

3467 metadata=metadata, 

3468 serialization=serialization, 

3469 ) 

3470 

3471 

3472class TypedDictField(TypedDict, total=False): 

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

3474 schema: Required[CoreSchema] 

3475 required: bool 

3476 validation_alias: str | list[str | int] | list[list[str | int]] 

3477 serialization_alias: str 

3478 serialization_exclude: bool # default: False 

3479 metadata: dict[str, Any] 

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

3481 

3482 

3483def typed_dict_field( 

3484 schema: CoreSchema, 

3485 *, 

3486 required: bool | None = None, 

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

3488 serialization_alias: str | None = None, 

3489 serialization_exclude: bool | None = None, 

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

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

3492) -> TypedDictField: 

3493 """ 

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

3495 

3496 ```py 

3497 from pydantic_core import core_schema 

3498 

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

3500 ``` 

3501 

3502 Args: 

3503 schema: The schema to use for the field 

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

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

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

3507 serialization_exclude: Whether to exclude the field when serializing 

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

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

3510 """ 

3511 return _dict_not_none( 

3512 type='typed-dict-field', 

3513 schema=schema, 

3514 required=required, 

3515 validation_alias=validation_alias, 

3516 serialization_alias=serialization_alias, 

3517 serialization_exclude=serialization_exclude, 

3518 serialization_exclude_if=serialization_exclude_if, 

3519 metadata=metadata, 

3520 ) 

3521 

3522 

3523class TypedDictSchema(TypedDict, total=False): 

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

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

3526 cls: type[Any] 

3527 cls_name: str 

3528 computed_fields: list[ComputedField] 

3529 strict: bool 

3530 extras_schema: CoreSchema 

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

3532 extra_behavior: ExtraBehavior 

3533 total: bool # default: True 

3534 ref: str 

3535 metadata: dict[str, Any] 

3536 serialization: SerSchema 

3537 config: CoreConfig 

3538 

3539 

3540def typed_dict_schema( 

3541 fields: dict[str, TypedDictField], 

3542 *, 

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

3544 cls_name: str | None = None, 

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

3546 strict: bool | None = None, 

3547 extras_schema: CoreSchema | None = None, 

3548 extra_behavior: ExtraBehavior | None = None, 

3549 total: bool | None = None, 

3550 ref: str | None = None, 

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

3552 serialization: SerSchema | None = None, 

3553 config: CoreConfig | None = None, 

3554) -> TypedDictSchema: 

3555 """ 

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

3557 

3558 ```py 

3559 from typing_extensions import TypedDict 

3560 

3561 from pydantic_core import SchemaValidator, core_schema 

3562 

3563 class MyTypedDict(TypedDict): 

3564 a: str 

3565 

3566 wrapper_schema = core_schema.typed_dict_schema( 

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

3568 ) 

3569 v = SchemaValidator(wrapper_schema) 

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

3571 ``` 

3572 

3573 Args: 

3574 fields: The fields to use for the typed dict 

3575 cls: The class to use for the typed dict 

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

3577 is provided. 

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

3579 strict: Whether the typed dict is strict 

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

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

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

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

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

3585 serialization: Custom serialization schema 

3586 """ 

3587 return _dict_not_none( 

3588 type='typed-dict', 

3589 fields=fields, 

3590 cls=cls, 

3591 cls_name=cls_name, 

3592 computed_fields=computed_fields, 

3593 strict=strict, 

3594 extras_schema=extras_schema, 

3595 extra_behavior=extra_behavior, 

3596 total=total, 

3597 ref=ref, 

3598 metadata=metadata, 

3599 serialization=serialization, 

3600 config=config, 

3601 ) 

3602 

3603 

3604class ModelField(TypedDict, total=False): 

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

3606 schema: Required[CoreSchema] 

3607 validation_alias: str | list[str | int] | list[list[str | int]] 

3608 serialization_alias: str 

3609 serialization_exclude: bool # default: False 

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

3611 frozen: bool 

3612 metadata: dict[str, Any] 

3613 

3614 

3615def model_field( 

3616 schema: CoreSchema, 

3617 *, 

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

3619 serialization_alias: str | None = None, 

3620 serialization_exclude: bool | None = None, 

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

3622 frozen: bool | None = None, 

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

3624) -> ModelField: 

3625 """ 

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

3627 

3628 ```py 

3629 from pydantic_core import core_schema 

3630 

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

3632 ``` 

3633 

3634 Args: 

3635 schema: The schema to use for the field 

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

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

3638 serialization_exclude: Whether to exclude the field when serializing 

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

3640 frozen: Whether the field is frozen 

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

3642 """ 

3643 return _dict_not_none( 

3644 type='model-field', 

3645 schema=schema, 

3646 validation_alias=validation_alias, 

3647 serialization_alias=serialization_alias, 

3648 serialization_exclude=serialization_exclude, 

3649 serialization_exclude_if=serialization_exclude_if, 

3650 frozen=frozen, 

3651 metadata=metadata, 

3652 ) 

3653 

3654 

3655class ModelFieldsSchema(TypedDict, total=False): 

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

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

3658 model_name: str 

3659 computed_fields: list[ComputedField] 

3660 strict: bool 

3661 extras_schema: CoreSchema 

3662 extras_keys_schema: CoreSchema 

3663 extra_behavior: ExtraBehavior 

3664 from_attributes: bool 

3665 ref: str 

3666 metadata: dict[str, Any] 

3667 serialization: SerSchema 

3668 

3669 

3670def model_fields_schema( 

3671 fields: dict[str, ModelField], 

3672 *, 

3673 model_name: str | None = None, 

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

3675 strict: bool | None = None, 

3676 extras_schema: CoreSchema | None = None, 

3677 extras_keys_schema: CoreSchema | None = None, 

3678 extra_behavior: ExtraBehavior | None = None, 

3679 from_attributes: bool | None = None, 

3680 ref: str | None = None, 

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

3682 serialization: SerSchema | None = None, 

3683) -> ModelFieldsSchema: 

3684 """ 

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

3686 

3687 ```py 

3688 from pydantic_core import SchemaValidator, core_schema 

3689 

3690 wrapper_schema = core_schema.model_fields_schema( 

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

3692 ) 

3693 v = SchemaValidator(wrapper_schema) 

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

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

3696 ``` 

3697 

3698 Args: 

3699 fields: The fields of the model 

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

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

3702 strict: Whether the model is strict 

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

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

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

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

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

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

3709 serialization: Custom serialization schema 

3710 """ 

3711 return _dict_not_none( 

3712 type='model-fields', 

3713 fields=fields, 

3714 model_name=model_name, 

3715 computed_fields=computed_fields, 

3716 strict=strict, 

3717 extras_schema=extras_schema, 

3718 extras_keys_schema=extras_keys_schema, 

3719 extra_behavior=extra_behavior, 

3720 from_attributes=from_attributes, 

3721 ref=ref, 

3722 metadata=metadata, 

3723 serialization=serialization, 

3724 ) 

3725 

3726 

3727class ModelSchema(TypedDict, total=False): 

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

3729 cls: Required[type[Any]] 

3730 generic_origin: type[Any] 

3731 schema: Required[CoreSchema] 

3732 custom_init: bool 

3733 root_model: bool 

3734 post_init: str 

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

3736 strict: bool 

3737 frozen: bool 

3738 extra_behavior: ExtraBehavior 

3739 config: CoreConfig 

3740 ref: str 

3741 metadata: dict[str, Any] 

3742 serialization: SerSchema 

3743 

3744 

3745def model_schema( 

3746 cls: type[Any], 

3747 schema: CoreSchema, 

3748 *, 

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

3750 custom_init: bool | None = None, 

3751 root_model: bool | None = None, 

3752 post_init: str | None = None, 

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

3754 strict: bool | None = None, 

3755 frozen: bool | None = None, 

3756 extra_behavior: ExtraBehavior | None = None, 

3757 config: CoreConfig | None = None, 

3758 ref: str | None = None, 

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

3760 serialization: SerSchema | None = None, 

3761) -> ModelSchema: 

3762 """ 

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

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

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

3766 to `__dict__` and `__pydantic_fields_set__` respectively. 

3767 

3768 Example: 

3769 

3770 ```py 

3771 from pydantic_core import CoreConfig, SchemaValidator, core_schema 

3772 

3773 class MyModel: 

3774 __slots__ = ( 

3775 '__dict__', 

3776 '__pydantic_fields_set__', 

3777 '__pydantic_extra__', 

3778 '__pydantic_private__', 

3779 ) 

3780 

3781 schema = core_schema.model_schema( 

3782 cls=MyModel, 

3783 config=CoreConfig(str_max_length=5), 

3784 schema=core_schema.model_fields_schema( 

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

3786 ), 

3787 ) 

3788 v = SchemaValidator(schema) 

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

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

3791 ``` 

3792 

3793 Args: 

3794 cls: The class to use for the model 

3795 schema: The schema to use for the model 

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

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

3798 custom_init: Whether the model has a custom init method 

3799 root_model: Whether the model is a `RootModel` 

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

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

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

3803 strict: Whether the model is strict 

3804 frozen: Whether the model is frozen 

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

3806 config: The config to use for the model 

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

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

3809 serialization: Custom serialization schema 

3810 """ 

3811 return _dict_not_none( 

3812 type='model', 

3813 cls=cls, 

3814 generic_origin=generic_origin, 

3815 schema=schema, 

3816 custom_init=custom_init, 

3817 root_model=root_model, 

3818 post_init=post_init, 

3819 revalidate_instances=revalidate_instances, 

3820 strict=strict, 

3821 frozen=frozen, 

3822 extra_behavior=extra_behavior, 

3823 config=config, 

3824 ref=ref, 

3825 metadata=metadata, 

3826 serialization=serialization, 

3827 ) 

3828 

3829 

3830class DataclassField(TypedDict, total=False): 

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

3832 name: Required[str] 

3833 schema: Required[CoreSchema] 

3834 kw_only: bool # default: True 

3835 init: bool # default: True 

3836 init_only: bool # default: False 

3837 frozen: bool # default: False 

3838 validation_alias: str | list[str | int] | list[list[str | int]] 

3839 serialization_alias: str 

3840 serialization_exclude: bool # default: False 

3841 metadata: dict[str, Any] 

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

3843 

3844 

3845def dataclass_field( 

3846 name: str, 

3847 schema: CoreSchema, 

3848 *, 

3849 kw_only: bool | None = None, 

3850 init: bool | None = None, 

3851 init_only: bool | None = None, 

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

3853 serialization_alias: str | None = None, 

3854 serialization_exclude: bool | None = None, 

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

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

3857 frozen: bool | None = None, 

3858) -> DataclassField: 

3859 """ 

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

3861 

3862 ```py 

3863 from pydantic_core import SchemaValidator, core_schema 

3864 

3865 field = core_schema.dataclass_field( 

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

3867 ) 

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

3869 v = SchemaValidator(schema) 

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

3871 ``` 

3872 

3873 Args: 

3874 name: The name to use for the argument parameter 

3875 schema: The schema to use for the argument parameter 

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

3877 init: Whether the field should be validated during initialization 

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

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

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

3881 serialization_exclude: Whether to exclude the field when serializing 

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

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

3884 frozen: Whether the field is frozen 

3885 """ 

3886 return _dict_not_none( 

3887 type='dataclass-field', 

3888 name=name, 

3889 schema=schema, 

3890 kw_only=kw_only, 

3891 init=init, 

3892 init_only=init_only, 

3893 validation_alias=validation_alias, 

3894 serialization_alias=serialization_alias, 

3895 serialization_exclude=serialization_exclude, 

3896 serialization_exclude_if=serialization_exclude_if, 

3897 metadata=metadata, 

3898 frozen=frozen, 

3899 ) 

3900 

3901 

3902class DataclassArgsSchema(TypedDict, total=False): 

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

3904 dataclass_name: Required[str] 

3905 fields: Required[list[DataclassField]] 

3906 computed_fields: list[ComputedField] 

3907 collect_init_only: bool # default: False 

3908 ref: str 

3909 metadata: dict[str, Any] 

3910 serialization: SerSchema 

3911 extra_behavior: ExtraBehavior 

3912 

3913 

3914def dataclass_args_schema( 

3915 dataclass_name: str, 

3916 fields: list[DataclassField], 

3917 *, 

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

3919 collect_init_only: bool | None = None, 

3920 ref: str | None = None, 

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

3922 serialization: SerSchema | None = None, 

3923 extra_behavior: ExtraBehavior | None = None, 

3924) -> DataclassArgsSchema: 

3925 """ 

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

3927 

3928 ```py 

3929 from pydantic_core import SchemaValidator, core_schema 

3930 

3931 field_a = core_schema.dataclass_field( 

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

3933 ) 

3934 field_b = core_schema.dataclass_field( 

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

3936 ) 

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

3938 v = SchemaValidator(schema) 

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

3940 ``` 

3941 

3942 Args: 

3943 dataclass_name: The name of the dataclass being validated 

3944 fields: The fields to use for the dataclass 

3945 computed_fields: Computed fields to use when serializing the dataclass 

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

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

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

3949 serialization: Custom serialization schema 

3950 extra_behavior: How to handle extra fields 

3951 """ 

3952 return _dict_not_none( 

3953 type='dataclass-args', 

3954 dataclass_name=dataclass_name, 

3955 fields=fields, 

3956 computed_fields=computed_fields, 

3957 collect_init_only=collect_init_only, 

3958 ref=ref, 

3959 metadata=metadata, 

3960 serialization=serialization, 

3961 extra_behavior=extra_behavior, 

3962 ) 

3963 

3964 

3965class DataclassSchema(TypedDict, total=False): 

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

3967 cls: Required[type[Any]] 

3968 generic_origin: type[Any] 

3969 schema: Required[CoreSchema] 

3970 fields: Required[list[str]] 

3971 cls_name: str 

3972 post_init: bool # default: False 

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

3974 strict: bool # default: False 

3975 frozen: bool # default False 

3976 ref: str 

3977 metadata: dict[str, Any] 

3978 serialization: SerSchema 

3979 slots: bool 

3980 config: CoreConfig 

3981 

3982 

3983def dataclass_schema( 

3984 cls: type[Any], 

3985 schema: CoreSchema, 

3986 fields: list[str], 

3987 *, 

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

3989 cls_name: str | None = None, 

3990 post_init: bool | None = None, 

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

3992 strict: bool | None = None, 

3993 ref: str | None = None, 

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

3995 serialization: SerSchema | None = None, 

3996 frozen: bool | None = None, 

3997 slots: bool | None = None, 

3998 config: CoreConfig | None = None, 

3999) -> DataclassSchema: 

4000 """ 

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

4002 another schema, not as the root type. 

4003 

4004 Args: 

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

4006 schema: The schema to use for the dataclass fields 

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

4008 and while validating assignment 

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

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

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

4012 post_init: Whether to call `__post_init__` after validation 

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

4014 should re-validate defaults to config.revalidate_instances, else 'never' 

4015 strict: Whether to require an exact instance of `cls` 

4016 ref: optional unique identifier of the schema, used to reference the schema in other places 

4017 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4018 serialization: Custom serialization schema 

4019 frozen: Whether the dataclass is frozen 

4020 slots: Whether `slots=True` on the dataclass, means each field is assigned independently, rather than 

4021 simply setting `__dict__`, default false 

4022 """ 

4023 return _dict_not_none( 

4024 type='dataclass', 

4025 cls=cls, 

4026 generic_origin=generic_origin, 

4027 fields=fields, 

4028 cls_name=cls_name, 

4029 schema=schema, 

4030 post_init=post_init, 

4031 revalidate_instances=revalidate_instances, 

4032 strict=strict, 

4033 ref=ref, 

4034 metadata=metadata, 

4035 serialization=serialization, 

4036 frozen=frozen, 

4037 slots=slots, 

4038 config=config, 

4039 ) 

4040 

4041 

4042class NamedTupleField(TypedDict, total=False): 

4043 type: Required[Literal['named-tuple-field']] 

4044 name: Required[str] 

4045 schema: Required[CoreSchema] 

4046 validation_alias: str | list[str | int] | list[list[str | int]] 

4047 metadata: dict[str, Any] 

4048 

4049 

4050def named_tuple_field( 

4051 name: str, 

4052 schema: CoreSchema, 

4053 *, 

4054 validation_alias: str | list[str | int] | list[list[str | int]] | None = None, 

4055 metadata: dict[str, Any] | None = None, 

4056) -> NamedTupleField: 

4057 """ 

4058 Returns a schema for a named tuple field, e.g.: 

4059 

4060 ```py 

4061 from pydantic_core import core_schema 

4062 

4063 field = core_schema.named_tuple_field(name='x', schema=core_schema.int_schema()) 

4064 ``` 

4065 

4066 Args: 

4067 name: The name of the field 

4068 schema: The schema to use for the field 

4069 validation_alias: The alias(es) to use to find the field in the validation data, only used 

4070 when validating from a dictionary or mapping 

4071 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4072 """ 

4073 return _dict_not_none( 

4074 type='named-tuple-field', 

4075 name=name, 

4076 schema=schema, 

4077 validation_alias=validation_alias, 

4078 metadata=metadata, 

4079 ) 

4080 

4081 

4082class NamedTupleSchema(TypedDict, total=False): 

4083 type: Required[Literal['named-tuple']] 

4084 cls: Required[type[Any]] 

4085 fields: Required[list[NamedTupleField]] 

4086 cls_name: str 

4087 ref: str 

4088 metadata: dict[str, Any] 

4089 serialization: SerSchema 

4090 

4091 

4092def named_tuple_schema( 

4093 cls: type[Any], 

4094 fields: list[NamedTupleField], 

4095 *, 

4096 cls_name: str | None = None, 

4097 ref: str | None = None, 

4098 metadata: dict[str, Any] | None = None, 

4099 serialization: SerSchema | None = None, 

4100) -> NamedTupleSchema: 

4101 """ 

4102 Returns a schema for a named tuple, e.g.: 

4103 

4104 ```py 

4105 from typing import NamedTuple 

4106 

4107 from pydantic_core import SchemaValidator, core_schema 

4108 

4109 class Point(NamedTuple): 

4110 x: int 

4111 y: int 

4112 

4113 schema = core_schema.named_tuple_schema( 

4114 Point, 

4115 [ 

4116 core_schema.named_tuple_field(name='x', schema=core_schema.int_schema()), 

4117 core_schema.named_tuple_field(name='y', schema=core_schema.int_schema()), 

4118 ], 

4119 ) 

4120 v = SchemaValidator(schema) 

4121 assert v.validate_python((1, '2')) == Point(x=1, y=2) 

4122 ``` 

4123 

4124 Fields are validated positionally when the input is a (named) tuple, list or JSON array, 

4125 and by name when the input is a dictionary, mapping or JSON object. Instances of `cls` 

4126 always revalidate. Strict mode is currently ignored, matching the behavior of the 

4127 `'call'` core schema previously used for named tuples. 

4128 

4129 Args: 

4130 cls: The named tuple class, used to construct instances and perform instance checks 

4131 fields: The fields to use for the named tuple, in order 

4132 cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`) 

4133 ref: optional unique identifier of the schema, used to reference the schema in other places 

4134 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4135 serialization: Custom serialization schema 

4136 """ 

4137 return _dict_not_none( 

4138 type='named-tuple', 

4139 cls=cls, 

4140 fields=fields, 

4141 cls_name=cls_name, 

4142 ref=ref, 

4143 metadata=metadata, 

4144 serialization=serialization, 

4145 ) 

4146 

4147 

4148class ArgumentsParameter(TypedDict, total=False): 

4149 name: Required[str] 

4150 schema: Required[CoreSchema] 

4151 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] # default positional_or_keyword 

4152 alias: str | list[str | int] | list[list[str | int]] 

4153 

4154 

4155def arguments_parameter( 

4156 name: str, 

4157 schema: CoreSchema, 

4158 *, 

4159 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None, 

4160 alias: str | list[str | int] | list[list[str | int]] | None = None, 

4161) -> ArgumentsParameter: 

4162 """ 

4163 Returns a schema that matches an argument parameter, e.g.: 

4164 

4165 ```py 

4166 from pydantic_core import SchemaValidator, core_schema 

4167 

4168 param = core_schema.arguments_parameter( 

4169 name='a', schema=core_schema.str_schema(), mode='positional_only' 

4170 ) 

4171 schema = core_schema.arguments_schema([param]) 

4172 v = SchemaValidator(schema) 

4173 assert v.validate_python(('hello',)) == (('hello',), {}) 

4174 ``` 

4175 

4176 Args: 

4177 name: The name to use for the argument parameter 

4178 schema: The schema to use for the argument parameter 

4179 mode: The mode to use for the argument parameter 

4180 alias: The alias to use for the argument parameter 

4181 """ 

4182 return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias) 

4183 

4184 

4185VarKwargsMode: TypeAlias = Literal['uniform', 'unpacked-typed-dict'] 

4186 

4187 

4188class ArgumentsSchema(TypedDict, total=False): 

4189 type: Required[Literal['arguments']] 

4190 arguments_schema: Required[list[ArgumentsParameter]] 

4191 validate_by_name: bool 

4192 validate_by_alias: bool 

4193 var_args_schema: CoreSchema 

4194 var_kwargs_mode: VarKwargsMode 

4195 var_kwargs_schema: CoreSchema 

4196 ref: str 

4197 metadata: dict[str, Any] 

4198 serialization: SerSchema 

4199 

4200 

4201def arguments_schema( 

4202 arguments: list[ArgumentsParameter], 

4203 *, 

4204 validate_by_name: bool | None = None, 

4205 validate_by_alias: bool | None = None, 

4206 var_args_schema: CoreSchema | None = None, 

4207 var_kwargs_mode: VarKwargsMode | None = None, 

4208 var_kwargs_schema: CoreSchema | None = None, 

4209 ref: str | None = None, 

4210 metadata: dict[str, Any] | None = None, 

4211 serialization: SerSchema | None = None, 

4212) -> ArgumentsSchema: 

4213 """ 

4214 Returns a schema that matches an arguments schema, e.g.: 

4215 

4216 ```py 

4217 from pydantic_core import SchemaValidator, core_schema 

4218 

4219 param_a = core_schema.arguments_parameter( 

4220 name='a', schema=core_schema.str_schema(), mode='positional_only' 

4221 ) 

4222 param_b = core_schema.arguments_parameter( 

4223 name='b', schema=core_schema.bool_schema(), mode='positional_only' 

4224 ) 

4225 schema = core_schema.arguments_schema([param_a, param_b]) 

4226 v = SchemaValidator(schema) 

4227 assert v.validate_python(('hello', True)) == (('hello', True), {}) 

4228 ``` 

4229 

4230 Args: 

4231 arguments: The arguments to use for the arguments schema 

4232 validate_by_name: Whether to populate by the parameter names, defaults to `False`. 

4233 validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`. 

4234 var_args_schema: The variable args schema to use for the arguments schema 

4235 var_kwargs_mode: The validation mode to use for variadic keyword arguments. If `'uniform'`, every value of the 

4236 keyword arguments will be validated against the `var_kwargs_schema` schema. If `'unpacked-typed-dict'`, 

4237 the `var_kwargs_schema` argument must be a [`typed_dict_schema`][pydantic_core.core_schema.typed_dict_schema] 

4238 var_kwargs_schema: The variable kwargs schema to use for the arguments schema 

4239 ref: optional unique identifier of the schema, used to reference the schema in other places 

4240 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4241 serialization: Custom serialization schema 

4242 """ 

4243 return _dict_not_none( 

4244 type='arguments', 

4245 arguments_schema=arguments, 

4246 validate_by_name=validate_by_name, 

4247 validate_by_alias=validate_by_alias, 

4248 var_args_schema=var_args_schema, 

4249 var_kwargs_mode=var_kwargs_mode, 

4250 var_kwargs_schema=var_kwargs_schema, 

4251 ref=ref, 

4252 metadata=metadata, 

4253 serialization=serialization, 

4254 ) 

4255 

4256 

4257class ArgumentsV3Parameter(TypedDict, total=False): 

4258 name: Required[str] 

4259 schema: Required[CoreSchema] 

4260 mode: Literal[ 

4261 'positional_only', 

4262 'positional_or_keyword', 

4263 'keyword_only', 

4264 'var_args', 

4265 'var_kwargs_uniform', 

4266 'var_kwargs_unpacked_typed_dict', 

4267 ] # default positional_or_keyword 

4268 alias: str | list[str | int] | list[list[str | int]] 

4269 

4270 

4271def arguments_v3_parameter( 

4272 name: str, 

4273 schema: CoreSchema, 

4274 *, 

4275 mode: Literal[ 

4276 'positional_only', 

4277 'positional_or_keyword', 

4278 'keyword_only', 

4279 'var_args', 

4280 'var_kwargs_uniform', 

4281 'var_kwargs_unpacked_typed_dict', 

4282 ] 

4283 | None = None, 

4284 alias: str | list[str | int] | list[list[str | int]] | None = None, 

4285) -> ArgumentsV3Parameter: 

4286 """ 

4287 Returns a schema that matches an argument parameter, e.g.: 

4288 

4289 ```py 

4290 from pydantic_core import SchemaValidator, core_schema 

4291 

4292 param = core_schema.arguments_v3_parameter( 

4293 name='a', schema=core_schema.str_schema(), mode='positional_only' 

4294 ) 

4295 schema = core_schema.arguments_v3_schema([param]) 

4296 v = SchemaValidator(schema) 

4297 assert v.validate_python({'a': 'hello'}) == (('hello',), {}) 

4298 ``` 

4299 

4300 Args: 

4301 name: The name to use for the argument parameter 

4302 schema: The schema to use for the argument parameter 

4303 mode: The mode to use for the argument parameter 

4304 alias: The alias to use for the argument parameter 

4305 """ 

4306 return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias) 

4307 

4308 

4309class ArgumentsV3Schema(TypedDict, total=False): 

4310 type: Required[Literal['arguments-v3']] 

4311 arguments_schema: Required[list[ArgumentsV3Parameter]] 

4312 validate_by_name: bool 

4313 validate_by_alias: bool 

4314 extra_behavior: Literal['forbid', 'ignore'] # 'allow' doesn't make sense here. 

4315 ref: str 

4316 metadata: dict[str, Any] 

4317 serialization: SerSchema 

4318 

4319 

4320def arguments_v3_schema( 

4321 arguments: list[ArgumentsV3Parameter], 

4322 *, 

4323 validate_by_name: bool | None = None, 

4324 validate_by_alias: bool | None = None, 

4325 extra_behavior: Literal['forbid', 'ignore'] | None = None, 

4326 ref: str | None = None, 

4327 metadata: dict[str, Any] | None = None, 

4328 serialization: SerSchema | None = None, 

4329) -> ArgumentsV3Schema: 

4330 """ 

4331 Returns a schema that matches an arguments schema, e.g.: 

4332 

4333 ```py 

4334 from pydantic_core import SchemaValidator, core_schema 

4335 

4336 param_a = core_schema.arguments_v3_parameter( 

4337 name='a', schema=core_schema.str_schema(), mode='positional_only' 

4338 ) 

4339 param_b = core_schema.arguments_v3_parameter( 

4340 name='kwargs', schema=core_schema.bool_schema(), mode='var_kwargs_uniform' 

4341 ) 

4342 schema = core_schema.arguments_v3_schema([param_a, param_b]) 

4343 v = SchemaValidator(schema) 

4344 assert v.validate_python({'a': 'hi', 'kwargs': {'b': True}}) == (('hi',), {'b': True}) 

4345 ``` 

4346 

4347 This schema is currently not used by other Pydantic components. In V3, it will most likely 

4348 become the default arguments schema for the `'call'` schema. 

4349 

4350 Args: 

4351 arguments: The arguments to use for the arguments schema. 

4352 validate_by_name: Whether to populate by the parameter names, defaults to `False`. 

4353 validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`. 

4354 extra_behavior: The extra behavior to use. 

4355 ref: optional unique identifier of the schema, used to reference the schema in other places. 

4356 metadata: Any other information you want to include with the schema, not used by pydantic-core. 

4357 serialization: Custom serialization schema. 

4358 """ 

4359 return _dict_not_none( 

4360 type='arguments-v3', 

4361 arguments_schema=arguments, 

4362 validate_by_name=validate_by_name, 

4363 validate_by_alias=validate_by_alias, 

4364 extra_behavior=extra_behavior, 

4365 ref=ref, 

4366 metadata=metadata, 

4367 serialization=serialization, 

4368 ) 

4369 

4370 

4371class CallSchema(TypedDict, total=False): 

4372 type: Required[Literal['call']] 

4373 arguments_schema: Required[CoreSchema] 

4374 function: Required[Callable[..., Any]] 

4375 function_name: str # default function.__name__ 

4376 return_schema: CoreSchema 

4377 ref: str 

4378 metadata: dict[str, Any] 

4379 serialization: SerSchema 

4380 

4381 

4382def call_schema( 

4383 arguments: CoreSchema, 

4384 function: Callable[..., Any], 

4385 *, 

4386 function_name: str | None = None, 

4387 return_schema: CoreSchema | None = None, 

4388 ref: str | None = None, 

4389 metadata: dict[str, Any] | None = None, 

4390 serialization: SerSchema | None = None, 

4391) -> CallSchema: 

4392 """ 

4393 Returns a schema that matches an arguments schema, then calls a function, e.g.: 

4394 

4395 ```py 

4396 from pydantic_core import SchemaValidator, core_schema 

4397 

4398 param_a = core_schema.arguments_parameter( 

4399 name='a', schema=core_schema.str_schema(), mode='positional_only' 

4400 ) 

4401 param_b = core_schema.arguments_parameter( 

4402 name='b', schema=core_schema.bool_schema(), mode='positional_only' 

4403 ) 

4404 args_schema = core_schema.arguments_schema([param_a, param_b]) 

4405 

4406 schema = core_schema.call_schema( 

4407 arguments=args_schema, 

4408 function=lambda a, b: a + str(not b), 

4409 return_schema=core_schema.str_schema(), 

4410 ) 

4411 v = SchemaValidator(schema) 

4412 assert v.validate_python((('hello', True))) == 'helloFalse' 

4413 ``` 

4414 

4415 Args: 

4416 arguments: The arguments to use for the arguments schema 

4417 function: The function to use for the call schema 

4418 function_name: The function name to use for the call schema, if not provided `function.__name__` is used 

4419 return_schema: The return schema to use for the call schema 

4420 ref: optional unique identifier of the schema, used to reference the schema in other places 

4421 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4422 serialization: Custom serialization schema 

4423 """ 

4424 return _dict_not_none( 

4425 type='call', 

4426 arguments_schema=arguments, 

4427 function=function, 

4428 function_name=function_name, 

4429 return_schema=return_schema, 

4430 ref=ref, 

4431 metadata=metadata, 

4432 serialization=serialization, 

4433 ) 

4434 

4435 

4436class CustomErrorSchema(TypedDict, total=False): 

4437 type: Required[Literal['custom-error']] 

4438 schema: Required[CoreSchema] 

4439 custom_error_type: Required[str] 

4440 custom_error_message: str 

4441 custom_error_context: dict[str, str | int | float] 

4442 ref: str 

4443 metadata: dict[str, Any] 

4444 serialization: SerSchema 

4445 

4446 

4447def custom_error_schema( 

4448 schema: CoreSchema, 

4449 custom_error_type: str, 

4450 *, 

4451 custom_error_message: str | None = None, 

4452 custom_error_context: dict[str, Any] | None = None, 

4453 ref: str | None = None, 

4454 metadata: dict[str, Any] | None = None, 

4455 serialization: SerSchema | None = None, 

4456) -> CustomErrorSchema: 

4457 """ 

4458 Returns a schema that matches a custom error value, e.g.: 

4459 

4460 ```py 

4461 from pydantic_core import SchemaValidator, core_schema 

4462 

4463 schema = core_schema.custom_error_schema( 

4464 schema=core_schema.int_schema(), 

4465 custom_error_type='MyError', 

4466 custom_error_message='Error msg', 

4467 ) 

4468 v = SchemaValidator(schema) 

4469 v.validate_python(1) 

4470 ``` 

4471 

4472 Args: 

4473 schema: The schema to use for the custom error schema 

4474 custom_error_type: The custom error type to use for the custom error schema 

4475 custom_error_message: The custom error message to use for the custom error schema 

4476 custom_error_context: The custom error context to use for the custom error schema 

4477 ref: optional unique identifier of the schema, used to reference the schema in other places 

4478 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4479 serialization: Custom serialization schema 

4480 """ 

4481 return _dict_not_none( 

4482 type='custom-error', 

4483 schema=schema, 

4484 custom_error_type=custom_error_type, 

4485 custom_error_message=custom_error_message, 

4486 custom_error_context=custom_error_context, 

4487 ref=ref, 

4488 metadata=metadata, 

4489 serialization=serialization, 

4490 ) 

4491 

4492 

4493class JsonSchema(TypedDict, total=False): 

4494 type: Required[Literal['json']] 

4495 schema: CoreSchema 

4496 ref: str 

4497 metadata: dict[str, Any] 

4498 serialization: SerSchema 

4499 

4500 

4501def json_schema( 

4502 schema: CoreSchema | None = None, 

4503 *, 

4504 ref: str | None = None, 

4505 metadata: dict[str, Any] | None = None, 

4506 serialization: SerSchema | None = None, 

4507) -> JsonSchema: 

4508 """ 

4509 Returns a schema that matches a JSON value, e.g.: 

4510 

4511 ```py 

4512 from pydantic_core import SchemaValidator, core_schema 

4513 

4514 dict_schema = core_schema.model_fields_schema( 

4515 { 

4516 'field_a': core_schema.model_field(core_schema.str_schema()), 

4517 'field_b': core_schema.model_field(core_schema.bool_schema()), 

4518 }, 

4519 ) 

4520 

4521 class MyModel: 

4522 __slots__ = ( 

4523 '__dict__', 

4524 '__pydantic_fields_set__', 

4525 '__pydantic_extra__', 

4526 '__pydantic_private__', 

4527 ) 

4528 field_a: str 

4529 field_b: bool 

4530 

4531 json_schema = core_schema.json_schema(schema=dict_schema) 

4532 schema = core_schema.model_schema(cls=MyModel, schema=json_schema) 

4533 v = SchemaValidator(schema) 

4534 m = v.validate_python('{"field_a": "hello", "field_b": true}') 

4535 assert isinstance(m, MyModel) 

4536 ``` 

4537 

4538 Args: 

4539 schema: The schema to use for the JSON schema 

4540 ref: optional unique identifier of the schema, used to reference the schema in other places 

4541 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4542 serialization: Custom serialization schema 

4543 """ 

4544 return _dict_not_none(type='json', schema=schema, ref=ref, metadata=metadata, serialization=serialization) 

4545 

4546 

4547class UrlSchema(TypedDict, total=False): 

4548 type: Required[Literal['url']] 

4549 max_length: int 

4550 allowed_schemes: list[str] 

4551 host_required: bool # default False 

4552 default_host: str 

4553 default_port: int 

4554 default_path: str 

4555 strict: bool 

4556 ref: str 

4557 metadata: dict[str, Any] 

4558 serialization: SerSchema 

4559 

4560 

4561def url_schema( 

4562 *, 

4563 max_length: int | None = None, 

4564 allowed_schemes: list[str] | None = None, 

4565 host_required: bool | None = None, 

4566 default_host: str | None = None, 

4567 default_port: int | None = None, 

4568 default_path: str | None = None, 

4569 preserve_empty_path: bool | None = None, 

4570 strict: bool | None = None, 

4571 ref: str | None = None, 

4572 metadata: dict[str, Any] | None = None, 

4573 serialization: SerSchema | None = None, 

4574) -> UrlSchema: 

4575 """ 

4576 Returns a schema that matches a URL value, e.g.: 

4577 

4578 ```py 

4579 from pydantic_core import SchemaValidator, core_schema 

4580 

4581 schema = core_schema.url_schema() 

4582 v = SchemaValidator(schema) 

4583 print(v.validate_python('https://example.com')) 

4584 #> https://example.com/ 

4585 ``` 

4586 

4587 Args: 

4588 max_length: The maximum length of the URL 

4589 allowed_schemes: The allowed URL schemes 

4590 host_required: Whether the URL must have a host 

4591 default_host: The default host to use if the URL does not have a host 

4592 default_port: The default port to use if the URL does not have a port 

4593 default_path: The default path to use if the URL does not have a path 

4594 preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False 

4595 strict: Whether to use strict URL parsing 

4596 ref: optional unique identifier of the schema, used to reference the schema in other places 

4597 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4598 serialization: Custom serialization schema 

4599 """ 

4600 return _dict_not_none( 

4601 type='url', 

4602 max_length=max_length, 

4603 allowed_schemes=allowed_schemes, 

4604 host_required=host_required, 

4605 default_host=default_host, 

4606 default_port=default_port, 

4607 default_path=default_path, 

4608 preserve_empty_path=preserve_empty_path, 

4609 strict=strict, 

4610 ref=ref, 

4611 metadata=metadata, 

4612 serialization=serialization, 

4613 ) 

4614 

4615 

4616class MultiHostUrlSchema(TypedDict, total=False): 

4617 type: Required[Literal['multi-host-url']] 

4618 max_length: int 

4619 allowed_schemes: list[str] 

4620 host_required: bool # default False 

4621 default_host: str 

4622 default_port: int 

4623 default_path: str 

4624 strict: bool 

4625 ref: str 

4626 metadata: dict[str, Any] 

4627 serialization: SerSchema 

4628 

4629 

4630def multi_host_url_schema( 

4631 *, 

4632 max_length: int | None = None, 

4633 allowed_schemes: list[str] | None = None, 

4634 host_required: bool | None = None, 

4635 default_host: str | None = None, 

4636 default_port: int | None = None, 

4637 default_path: str | None = None, 

4638 preserve_empty_path: bool | None = None, 

4639 strict: bool | None = None, 

4640 ref: str | None = None, 

4641 metadata: dict[str, Any] | None = None, 

4642 serialization: SerSchema | None = None, 

4643) -> MultiHostUrlSchema: 

4644 """ 

4645 Returns a schema that matches a URL value with possibly multiple hosts, e.g.: 

4646 

4647 ```py 

4648 from pydantic_core import SchemaValidator, core_schema 

4649 

4650 schema = core_schema.multi_host_url_schema() 

4651 v = SchemaValidator(schema) 

4652 print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1')) 

4653 #> redis://localhost,0.0.0.0,127.0.0.1 

4654 ``` 

4655 

4656 Args: 

4657 max_length: The maximum length of the URL 

4658 allowed_schemes: The allowed URL schemes 

4659 host_required: Whether the URL must have a host 

4660 default_host: The default host to use if the URL does not have a host 

4661 default_port: The default port to use if the URL does not have a port 

4662 default_path: The default path to use if the URL does not have a path 

4663 preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False 

4664 strict: Whether to use strict URL parsing 

4665 ref: optional unique identifier of the schema, used to reference the schema in other places 

4666 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4667 serialization: Custom serialization schema 

4668 """ 

4669 return _dict_not_none( 

4670 type='multi-host-url', 

4671 max_length=max_length, 

4672 allowed_schemes=allowed_schemes, 

4673 host_required=host_required, 

4674 default_host=default_host, 

4675 default_port=default_port, 

4676 default_path=default_path, 

4677 preserve_empty_path=preserve_empty_path, 

4678 strict=strict, 

4679 ref=ref, 

4680 metadata=metadata, 

4681 serialization=serialization, 

4682 ) 

4683 

4684 

4685class DefinitionsSchema(TypedDict, total=False): 

4686 type: Required[Literal['definitions']] 

4687 schema: Required[CoreSchema] 

4688 definitions: Required[list[CoreSchema]] 

4689 metadata: dict[str, Any] 

4690 serialization: SerSchema 

4691 

4692 

4693def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema: 

4694 """ 

4695 Build a schema that contains both an inner schema and a list of definitions which can be used 

4696 within the inner schema. 

4697 

4698 ```py 

4699 from pydantic_core import SchemaValidator, core_schema 

4700 

4701 schema = core_schema.definitions_schema( 

4702 core_schema.list_schema(core_schema.definition_reference_schema('foobar')), 

4703 [core_schema.int_schema(ref='foobar')], 

4704 ) 

4705 v = SchemaValidator(schema) 

4706 assert v.validate_python([1, 2, '3']) == [1, 2, 3] 

4707 ``` 

4708 

4709 Args: 

4710 schema: The inner schema 

4711 definitions: List of definitions which can be referenced within inner schema 

4712 """ 

4713 return DefinitionsSchema(type='definitions', schema=schema, definitions=definitions) 

4714 

4715 

4716class DefinitionReferenceSchema(TypedDict, total=False): 

4717 type: Required[Literal['definition-ref']] 

4718 schema_ref: Required[str] 

4719 ref: str 

4720 metadata: dict[str, Any] 

4721 serialization: SerSchema 

4722 

4723 

4724def definition_reference_schema( 

4725 schema_ref: str, 

4726 ref: str | None = None, 

4727 metadata: dict[str, Any] | None = None, 

4728 serialization: SerSchema | None = None, 

4729) -> DefinitionReferenceSchema: 

4730 """ 

4731 Returns a schema that points to a schema stored in "definitions", this is useful for nested recursive 

4732 models and also when you want to define validators separately from the main schema, e.g.: 

4733 

4734 ```py 

4735 from pydantic_core import SchemaValidator, core_schema 

4736 

4737 schema_definition = core_schema.definition_reference_schema('list-schema') 

4738 schema = core_schema.definitions_schema( 

4739 schema=schema_definition, 

4740 definitions=[ 

4741 core_schema.list_schema(items_schema=schema_definition, ref='list-schema'), 

4742 ], 

4743 ) 

4744 v = SchemaValidator(schema) 

4745 assert v.validate_python([()]) == [[]] 

4746 ``` 

4747 

4748 Args: 

4749 schema_ref: The schema ref to use for the definition reference schema 

4750 metadata: Any other information you want to include with the schema, not used by pydantic-core 

4751 serialization: Custom serialization schema 

4752 """ 

4753 return _dict_not_none( 

4754 type='definition-ref', schema_ref=schema_ref, ref=ref, metadata=metadata, serialization=serialization 

4755 ) 

4756 

4757 

4758MYPY = False 

4759# See https://github.com/python/mypy/issues/14034 for details, in summary mypy is extremely slow to process this 

4760# union which kills performance not just for pydantic, but even for code using pydantic 

4761if not MYPY: 

4762 CoreSchema: TypeAlias = ( 

4763 InvalidSchema 

4764 | AnySchema 

4765 | NoneSchema 

4766 | BoolSchema 

4767 | IntSchema 

4768 | FloatSchema 

4769 | DecimalSchema 

4770 | FractionSchema 

4771 | StringSchema 

4772 | BytesSchema 

4773 | DateSchema 

4774 | TimeSchema 

4775 | DatetimeSchema 

4776 | TimedeltaSchema 

4777 | LiteralSchema 

4778 | MissingSentinelSchema 

4779 | EllipsisSchema 

4780 | EnumSchema 

4781 | IsInstanceSchema 

4782 | IsSubclassSchema 

4783 | CallableSchema 

4784 | ListSchema 

4785 | DequeSchema 

4786 | TupleSchema 

4787 | SetSchema 

4788 | FrozenSetSchema 

4789 | GeneratorSchema 

4790 | DictSchema 

4791 | FrozenDictSchema 

4792 | OrderedDictSchema 

4793 | CounterSchema 

4794 | AfterValidatorFunctionSchema 

4795 | BeforeValidatorFunctionSchema 

4796 | WrapValidatorFunctionSchema 

4797 | PlainValidatorFunctionSchema 

4798 | WithDefaultSchema 

4799 | NullableSchema 

4800 | UnionSchema 

4801 | TaggedUnionSchema 

4802 | ChainSchema 

4803 | LaxOrStrictSchema 

4804 | JsonOrPythonSchema 

4805 | TypedDictSchema 

4806 | ModelFieldsSchema 

4807 | ModelSchema 

4808 | DataclassArgsSchema 

4809 | DataclassSchema 

4810 | NamedTupleSchema 

4811 | ArgumentsSchema 

4812 | ArgumentsV3Schema 

4813 | CallSchema 

4814 | CustomErrorSchema 

4815 | JsonSchema 

4816 | UrlSchema 

4817 | MultiHostUrlSchema 

4818 | DefinitionsSchema 

4819 | DefinitionReferenceSchema 

4820 | UuidSchema 

4821 | ComplexSchema 

4822 ) 

4823elif False: 

4824 CoreSchema: TypeAlias = Mapping[str, Any] 

4825 

4826 

4827# to update this, call `pytest -k test_core_schema_type_literal` and copy the output 

4828CoreSchemaType: TypeAlias = Literal[ 

4829 'invalid', 

4830 'any', 

4831 'none', 

4832 'bool', 

4833 'int', 

4834 'float', 

4835 'decimal', 

4836 'fraction', 

4837 'str', 

4838 'bytes', 

4839 'date', 

4840 'time', 

4841 'datetime', 

4842 'timedelta', 

4843 'literal', 

4844 'missing-sentinel', 

4845 'ellipsis', 

4846 'enum', 

4847 'is-instance', 

4848 'is-subclass', 

4849 'callable', 

4850 'list', 

4851 'deque', 

4852 'tuple', 

4853 'set', 

4854 'frozenset', 

4855 'generator', 

4856 'dict', 

4857 'frozendict', 

4858 'ordered-dict', 

4859 'counter', 

4860 'function-after', 

4861 'function-before', 

4862 'function-wrap', 

4863 'function-plain', 

4864 'default', 

4865 'nullable', 

4866 'union', 

4867 'tagged-union', 

4868 'chain', 

4869 'lax-or-strict', 

4870 'json-or-python', 

4871 'typed-dict', 

4872 'model-fields', 

4873 'model', 

4874 'dataclass-args', 

4875 'dataclass', 

4876 'named-tuple', 

4877 'arguments', 

4878 'arguments-v3', 

4879 'call', 

4880 'custom-error', 

4881 'json', 

4882 'url', 

4883 'multi-host-url', 

4884 'definitions', 

4885 'definition-ref', 

4886 'uuid', 

4887 'complex', 

4888] 

4889 

4890CoreSchemaFieldType: TypeAlias = Literal[ 

4891 'model-field', 'dataclass-field', 'typed-dict-field', 'named-tuple-field', 'computed-field' 

4892] 

4893 

4894 

4895# used in _pydantic_core/__init__.pyi::PydanticKnownError 

4896# to update this, call `pytest -k test_all_errors` and copy the output 

4897ErrorType: TypeAlias = Literal[ 

4898 'no_such_attribute', 

4899 'json_invalid', 

4900 'json_type', 

4901 'needs_python_object', 

4902 'recursion_loop', 

4903 'missing', 

4904 'frozen_field', 

4905 'frozen_instance', 

4906 'extra_forbidden', 

4907 'invalid_key', 

4908 'get_attribute_error', 

4909 'model_type', 

4910 'model_attributes_type', 

4911 'dataclass_type', 

4912 'dataclass_exact_type', 

4913 'named_tuple_type', 

4914 'default_factory_not_called', 

4915 'none_required', 

4916 'greater_than', 

4917 'greater_than_equal', 

4918 'less_than', 

4919 'less_than_equal', 

4920 'multiple_of', 

4921 'finite_number', 

4922 'too_short', 

4923 'too_long', 

4924 'iterable_type', 

4925 'iteration_error', 

4926 'string_type', 

4927 'string_unicode', 

4928 'string_too_short', 

4929 'string_too_long', 

4930 'string_pattern_mismatch', 

4931 'string_not_ascii', 

4932 'enum', 

4933 'dict_type', 

4934 'frozen_dict_type', 

4935 'ordered_dict_type', 

4936 'counter_type', 

4937 'mapping_type', 

4938 'list_type', 

4939 'deque_type', 

4940 'tuple_type', 

4941 'set_type', 

4942 'set_item_not_hashable', 

4943 'bool_type', 

4944 'bool_parsing', 

4945 'int_type', 

4946 'int_parsing', 

4947 'int_parsing_size', 

4948 'int_from_float', 

4949 'float_type', 

4950 'float_parsing', 

4951 'bytes_type', 

4952 'bytes_too_short', 

4953 'bytes_too_long', 

4954 'bytes_invalid_encoding', 

4955 'value_error', 

4956 'assertion_error', 

4957 'literal_error', 

4958 'missing_sentinel_error', 

4959 'ellipsis_error', 

4960 'date_type', 

4961 'date_parsing', 

4962 'date_from_datetime_parsing', 

4963 'date_from_datetime_inexact', 

4964 'date_past', 

4965 'date_future', 

4966 'time_type', 

4967 'time_parsing', 

4968 'datetime_type', 

4969 'datetime_parsing', 

4970 'datetime_object_invalid', 

4971 'datetime_from_date_parsing', 

4972 'datetime_past', 

4973 'datetime_future', 

4974 'timezone_naive', 

4975 'timezone_aware', 

4976 'timezone_offset', 

4977 'time_delta_type', 

4978 'time_delta_parsing', 

4979 'frozen_set_type', 

4980 'is_instance_of', 

4981 'is_subclass_of', 

4982 'callable_type', 

4983 'union_tag_invalid', 

4984 'union_tag_not_found', 

4985 'arguments_type', 

4986 'missing_argument', 

4987 'unexpected_keyword_argument', 

4988 'missing_keyword_only_argument', 

4989 'unexpected_positional_argument', 

4990 'missing_positional_only_argument', 

4991 'multiple_argument_values', 

4992 'url_type', 

4993 'url_parsing', 

4994 'url_syntax_violation', 

4995 'url_too_long', 

4996 'url_scheme', 

4997 'uuid_type', 

4998 'uuid_parsing', 

4999 'uuid_version', 

5000 'decimal_type', 

5001 'decimal_parsing', 

5002 'decimal_max_digits', 

5003 'decimal_max_places', 

5004 'decimal_whole_digits', 

5005 'fraction_type', 

5006 'fraction_parsing', 

5007 'complex_type', 

5008 'complex_str_parsing', 

5009] 

5010 

5011 

5012def _dict_not_none(**kwargs: Any) -> Any: 

5013 return {k: v for k, v in kwargs.items() if v is not None} 

5014 

5015 

5016def iter_union_choices(union_schema: UnionSchema) -> Generator[CoreSchema]: 

5017 """Iterate over the choices of a `'union'` schema.""" 

5018 for choice in union_schema['choices']: 

5019 if isinstance(choice, tuple): 

5020 yield choice[0] 

5021 else: 

5022 yield choice 

5023 

5024 

5025############################################################################### 

5026# All this stuff is deprecated by #980 and will be removed eventually 

5027# They're kept because some code external code will be using them 

5028 

5029 

5030@deprecated('`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.') 

5031def field_before_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs): 

5032 return with_info_before_validator_function(function, schema, field_name=field_name, **kwargs) 

5033 

5034 

5035@deprecated('`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.') 

5036def general_before_validator_function(*args, **kwargs): 

5037 return with_info_before_validator_function(*args, **kwargs) 

5038 

5039 

5040@deprecated('`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.') 

5041def field_after_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs): 

5042 return with_info_after_validator_function(function, schema, field_name=field_name, **kwargs) 

5043 

5044 

5045@deprecated('`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.') 

5046def general_after_validator_function(*args, **kwargs): 

5047 return with_info_after_validator_function(*args, **kwargs) 

5048 

5049 

5050@deprecated('`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.') 

5051def field_wrap_validator_function( 

5052 function: WithInfoWrapValidatorFunction, field_name: str, schema: CoreSchema, **kwargs 

5053): 

5054 return with_info_wrap_validator_function(function, schema, field_name=field_name, **kwargs) 

5055 

5056 

5057@deprecated('`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.') 

5058def general_wrap_validator_function(*args, **kwargs): 

5059 return with_info_wrap_validator_function(*args, **kwargs) 

5060 

5061 

5062@deprecated('`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.') 

5063def field_plain_validator_function(function: WithInfoValidatorFunction, field_name: str, **kwargs): 

5064 return with_info_plain_validator_function(function, field_name=field_name, **kwargs) 

5065 

5066 

5067@deprecated('`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.') 

5068def general_plain_validator_function(*args, **kwargs): 

5069 return with_info_plain_validator_function(*args, **kwargs) 

5070 

5071 

5072_deprecated_import_lookup = { 

5073 'FieldValidationInfo': ValidationInfo, 

5074 'FieldValidatorFunction': WithInfoValidatorFunction, 

5075 'GeneralValidatorFunction': WithInfoValidatorFunction, 

5076 'FieldWrapValidatorFunction': WithInfoWrapValidatorFunction, 

5077} 

5078 

5079if TYPE_CHECKING: 

5080 FieldValidationInfo = ValidationInfo 

5081 

5082 

5083def __getattr__(attr_name: str) -> object: 

5084 new_attr = _deprecated_import_lookup.get(attr_name) 

5085 if new_attr is None: 

5086 raise AttributeError(f"module 'pydantic_core' has no attribute '{attr_name}'") 

5087 else: 

5088 import warnings 

5089 

5090 msg = f'`{attr_name}` is deprecated, use `{new_attr.__name__}` instead.' 

5091 warnings.warn(msg, DeprecationWarning, stacklevel=1) 

5092 return new_attr