functional_validators.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. """This module contains related classes and functions for validation."""
  2. from __future__ import annotations as _annotations
  3. import dataclasses
  4. import sys
  5. import warnings
  6. from functools import partialmethod
  7. from typing import TYPE_CHECKING, Annotated, Any, Callable, Literal, TypeVar, Union, cast, overload
  8. from pydantic_core import PydanticUndefined, core_schema
  9. from typing_extensions import Self, TypeAlias
  10. from ._internal import _decorators, _generics, _internal_dataclass
  11. from .annotated_handlers import GetCoreSchemaHandler
  12. from .errors import PydanticUserError
  13. from .version import version_short
  14. from .warnings import ArbitraryTypeWarning, PydanticDeprecatedSince212
  15. if sys.version_info < (3, 11):
  16. from typing_extensions import Protocol
  17. else:
  18. from typing import Protocol
  19. _inspect_validator = _decorators.inspect_validator
  20. @dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
  21. class AfterValidator:
  22. """!!! abstract "Usage Documentation"
  23. [field *after* validators](../concepts/validators.md#field-after-validator)
  24. A metadata class that indicates that a validation should be applied **after** the inner validation logic.
  25. Attributes:
  26. func: The validator function.
  27. Example:
  28. ```python
  29. from typing import Annotated
  30. from pydantic import AfterValidator, BaseModel, ValidationError
  31. MyInt = Annotated[int, AfterValidator(lambda v: v + 1)]
  32. class Model(BaseModel):
  33. a: MyInt
  34. print(Model(a=1).a)
  35. #> 2
  36. try:
  37. Model(a='a')
  38. except ValidationError as e:
  39. print(e.json(indent=2))
  40. '''
  41. [
  42. {
  43. "type": "int_parsing",
  44. "loc": [
  45. "a"
  46. ],
  47. "msg": "Input should be a valid integer, unable to parse string as an integer",
  48. "input": "a",
  49. "url": "https://errors.pydantic.dev/2/v/int_parsing"
  50. }
  51. ]
  52. '''
  53. ```
  54. """
  55. func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
  56. def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  57. schema = handler(source_type)
  58. info_arg = _inspect_validator(self.func, mode='after', type='field')
  59. if info_arg:
  60. func = cast(core_schema.WithInfoValidatorFunction, self.func)
  61. return core_schema.with_info_after_validator_function(func, schema=schema)
  62. else:
  63. func = cast(core_schema.NoInfoValidatorFunction, self.func)
  64. return core_schema.no_info_after_validator_function(func, schema=schema)
  65. @classmethod
  66. def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
  67. return cls(func=decorator.func)
  68. @dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
  69. class BeforeValidator:
  70. """!!! abstract "Usage Documentation"
  71. [field *before* validators](../concepts/validators.md#field-before-validator)
  72. A metadata class that indicates that a validation should be applied **before** the inner validation logic.
  73. Attributes:
  74. func: The validator function.
  75. json_schema_input_type: The input type used to generate the appropriate
  76. JSON Schema (in validation mode). The actual input type is `Any`.
  77. Example:
  78. ```python
  79. from typing import Annotated
  80. from pydantic import BaseModel, BeforeValidator
  81. MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)]
  82. class Model(BaseModel):
  83. a: MyInt
  84. print(Model(a=1).a)
  85. #> 2
  86. try:
  87. Model(a='a')
  88. except TypeError as e:
  89. print(e)
  90. #> can only concatenate str (not "int") to str
  91. ```
  92. """
  93. func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
  94. json_schema_input_type: Any = PydanticUndefined
  95. def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  96. schema = handler(source_type)
  97. input_schema = (
  98. None
  99. if self.json_schema_input_type is PydanticUndefined
  100. else handler.generate_schema(self.json_schema_input_type)
  101. )
  102. info_arg = _inspect_validator(self.func, mode='before', type='field')
  103. if info_arg:
  104. func = cast(core_schema.WithInfoValidatorFunction, self.func)
  105. return core_schema.with_info_before_validator_function(
  106. func,
  107. schema=schema,
  108. json_schema_input_schema=input_schema,
  109. )
  110. else:
  111. func = cast(core_schema.NoInfoValidatorFunction, self.func)
  112. return core_schema.no_info_before_validator_function(
  113. func, schema=schema, json_schema_input_schema=input_schema
  114. )
  115. @classmethod
  116. def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
  117. return cls(
  118. func=decorator.func,
  119. json_schema_input_type=decorator.info.json_schema_input_type,
  120. )
  121. @dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
  122. class PlainValidator:
  123. """!!! abstract "Usage Documentation"
  124. [field *plain* validators](../concepts/validators.md#field-plain-validator)
  125. A metadata class that indicates that a validation should be applied **instead** of the inner validation logic.
  126. !!! note
  127. Before v2.9, `PlainValidator` wasn't always compatible with JSON Schema generation for `mode='validation'`.
  128. You can now use the `json_schema_input_type` argument to specify the input type of the function
  129. to be used in the JSON schema when `mode='validation'` (the default). See the example below for more details.
  130. Attributes:
  131. func: The validator function.
  132. json_schema_input_type: The input type used to generate the appropriate
  133. JSON Schema (in validation mode). The actual input type is `Any`.
  134. Example:
  135. ```python
  136. from typing import Annotated, Union
  137. from pydantic import BaseModel, PlainValidator
  138. def validate(v: object) -> int:
  139. if not isinstance(v, (int, str)):
  140. raise ValueError(f'Expected int or str, got {type(v)}')
  141. return int(v) + 1
  142. MyInt = Annotated[
  143. int,
  144. PlainValidator(validate, json_schema_input_type=Union[str, int]), # (1)!
  145. ]
  146. class Model(BaseModel):
  147. a: MyInt
  148. print(Model(a='1').a)
  149. #> 2
  150. print(Model(a=1).a)
  151. #> 2
  152. ```
  153. 1. In this example, we've specified the `json_schema_input_type` as `Union[str, int]` which indicates to the JSON schema
  154. generator that in validation mode, the input type for the `a` field can be either a [`str`][] or an [`int`][].
  155. """
  156. func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
  157. json_schema_input_type: Any = Any
  158. def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  159. # Note that for some valid uses of PlainValidator, it is not possible to generate a core schema for the
  160. # source_type, so calling `handler(source_type)` will error, which prevents us from generating a proper
  161. # serialization schema. To work around this for use cases that will not involve serialization, we simply
  162. # catch any PydanticSchemaGenerationError that may be raised while attempting to build the serialization schema
  163. # and abort any attempts to handle special serialization.
  164. from pydantic import PydanticSchemaGenerationError
  165. try:
  166. schema = handler(source_type)
  167. # TODO if `schema['serialization']` is one of `'include-exclude-dict/sequence',
  168. # schema validation will fail. That's why we use 'type ignore' comments below.
  169. serialization = schema.get(
  170. 'serialization',
  171. core_schema.wrap_serializer_function_ser_schema(
  172. function=lambda v, h: h(v),
  173. schema=schema,
  174. return_schema=handler.generate_schema(source_type),
  175. ),
  176. )
  177. except PydanticSchemaGenerationError:
  178. serialization = None
  179. input_schema = handler.generate_schema(self.json_schema_input_type)
  180. info_arg = _inspect_validator(self.func, mode='plain', type='field')
  181. if info_arg:
  182. func = cast(core_schema.WithInfoValidatorFunction, self.func)
  183. return core_schema.with_info_plain_validator_function(
  184. func,
  185. serialization=serialization, # pyright: ignore[reportArgumentType]
  186. json_schema_input_schema=input_schema,
  187. )
  188. else:
  189. func = cast(core_schema.NoInfoValidatorFunction, self.func)
  190. return core_schema.no_info_plain_validator_function(
  191. func,
  192. serialization=serialization, # pyright: ignore[reportArgumentType]
  193. json_schema_input_schema=input_schema,
  194. )
  195. @classmethod
  196. def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
  197. return cls(
  198. func=decorator.func,
  199. json_schema_input_type=decorator.info.json_schema_input_type,
  200. )
  201. @dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
  202. class WrapValidator:
  203. """!!! abstract "Usage Documentation"
  204. [field *wrap* validators](../concepts/validators.md#field-wrap-validator)
  205. A metadata class that indicates that a validation should be applied **around** the inner validation logic.
  206. Attributes:
  207. func: The validator function.
  208. json_schema_input_type: The input type used to generate the appropriate
  209. JSON Schema (in validation mode). The actual input type is `Any`.
  210. ```python
  211. from datetime import datetime
  212. from typing import Annotated
  213. from pydantic import BaseModel, ValidationError, WrapValidator
  214. def validate_timestamp(v, handler):
  215. if v == 'now':
  216. # we don't want to bother with further validation, just return the new value
  217. return datetime.now()
  218. try:
  219. return handler(v)
  220. except ValidationError:
  221. # validation failed, in this case we want to return a default value
  222. return datetime(2000, 1, 1)
  223. MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
  224. class Model(BaseModel):
  225. a: MyTimestamp
  226. print(Model(a='now').a)
  227. #> 2032-01-02 03:04:05.000006
  228. print(Model(a='invalid').a)
  229. #> 2000-01-01 00:00:00
  230. ```
  231. """
  232. func: core_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunction
  233. json_schema_input_type: Any = PydanticUndefined
  234. def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  235. schema = handler(source_type)
  236. input_schema = (
  237. None
  238. if self.json_schema_input_type is PydanticUndefined
  239. else handler.generate_schema(self.json_schema_input_type)
  240. )
  241. info_arg = _inspect_validator(self.func, mode='wrap', type='field')
  242. if info_arg:
  243. func = cast(core_schema.WithInfoWrapValidatorFunction, self.func)
  244. return core_schema.with_info_wrap_validator_function(
  245. func,
  246. schema=schema,
  247. json_schema_input_schema=input_schema,
  248. )
  249. else:
  250. func = cast(core_schema.NoInfoWrapValidatorFunction, self.func)
  251. return core_schema.no_info_wrap_validator_function(
  252. func,
  253. schema=schema,
  254. json_schema_input_schema=input_schema,
  255. )
  256. @classmethod
  257. def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
  258. return cls(
  259. func=decorator.func,
  260. json_schema_input_type=decorator.info.json_schema_input_type,
  261. )
  262. if TYPE_CHECKING:
  263. class _OnlyValueValidatorClsMethod(Protocol):
  264. def __call__(self, cls: Any, value: Any, /) -> Any: ...
  265. class _V2ValidatorClsMethod(Protocol):
  266. def __call__(self, cls: Any, value: Any, info: core_schema.ValidationInfo[Any], /) -> Any: ...
  267. class _OnlyValueWrapValidatorClsMethod(Protocol):
  268. def __call__(self, cls: Any, value: Any, handler: core_schema.ValidatorFunctionWrapHandler, /) -> Any: ...
  269. class _V2WrapValidatorClsMethod(Protocol):
  270. def __call__(
  271. self,
  272. cls: Any,
  273. value: Any,
  274. handler: core_schema.ValidatorFunctionWrapHandler,
  275. info: core_schema.ValidationInfo[Any],
  276. /,
  277. ) -> Any: ...
  278. _V2Validator = Union[
  279. _V2ValidatorClsMethod,
  280. core_schema.WithInfoValidatorFunction,
  281. _OnlyValueValidatorClsMethod,
  282. core_schema.NoInfoValidatorFunction,
  283. ]
  284. _V2WrapValidator = Union[
  285. _V2WrapValidatorClsMethod,
  286. core_schema.WithInfoWrapValidatorFunction,
  287. _OnlyValueWrapValidatorClsMethod,
  288. core_schema.NoInfoWrapValidatorFunction,
  289. ]
  290. _PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
  291. _V2BeforeAfterOrPlainValidatorType = TypeVar(
  292. '_V2BeforeAfterOrPlainValidatorType',
  293. bound=Union[_V2Validator, _PartialClsOrStaticMethod],
  294. )
  295. _V2WrapValidatorType = TypeVar('_V2WrapValidatorType', bound=Union[_V2WrapValidator, _PartialClsOrStaticMethod])
  296. FieldValidatorModes: TypeAlias = Literal['before', 'after', 'wrap', 'plain']
  297. @overload
  298. def field_validator(
  299. field: str,
  300. /,
  301. *fields: str,
  302. mode: Literal['wrap'],
  303. check_fields: bool | None = ...,
  304. json_schema_input_type: Any = ...,
  305. ) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]: ...
  306. @overload
  307. def field_validator(
  308. field: str,
  309. /,
  310. *fields: str,
  311. mode: Literal['before', 'plain'],
  312. check_fields: bool | None = ...,
  313. json_schema_input_type: Any = ...,
  314. ) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ...
  315. @overload
  316. def field_validator(
  317. field: str,
  318. /,
  319. *fields: str,
  320. mode: Literal['after'] = ...,
  321. check_fields: bool | None = ...,
  322. ) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ...
  323. def field_validator( # noqa: D417
  324. field: str,
  325. /,
  326. *fields: str,
  327. mode: FieldValidatorModes = 'after',
  328. check_fields: bool | None = None,
  329. json_schema_input_type: Any = PydanticUndefined,
  330. ) -> Callable[[Any], Any]:
  331. """!!! abstract "Usage Documentation"
  332. [field validators](../concepts/validators.md#field-validators)
  333. Decorate methods on the class indicating that they should be used to validate fields.
  334. Example usage:
  335. ```python
  336. from typing import Any
  337. from pydantic import (
  338. BaseModel,
  339. ValidationError,
  340. field_validator,
  341. )
  342. class Model(BaseModel):
  343. a: str
  344. @field_validator('a')
  345. @classmethod
  346. def ensure_foobar(cls, v: Any):
  347. if 'foobar' not in v:
  348. raise ValueError('"foobar" not found in a')
  349. return v
  350. print(repr(Model(a='this is foobar good')))
  351. #> Model(a='this is foobar good')
  352. try:
  353. Model(a='snap')
  354. except ValidationError as exc_info:
  355. print(exc_info)
  356. '''
  357. 1 validation error for Model
  358. a
  359. Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str]
  360. '''
  361. ```
  362. For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators).
  363. Args:
  364. *fields: The field names the validator should apply to.
  365. mode: Specifies whether to validate the fields before or after validation.
  366. check_fields: Whether to check that the fields actually exist on the model.
  367. json_schema_input_type: The input type of the function. This is only used to generate
  368. the appropriate JSON Schema (in validation mode) and can only specified
  369. when `mode` is either `'before'`, `'plain'` or `'wrap'`.
  370. Raises:
  371. PydanticUserError:
  372. - If the decorator is used without any arguments (at least one field name must be provided).
  373. - If the provided field names are not strings.
  374. - If `json_schema_input_type` is provided with an unsupported `mode`.
  375. - If the decorator is applied to an instance method.
  376. """
  377. if callable(field) or isinstance(field, classmethod):
  378. raise PydanticUserError(
  379. 'The `@field_validator` decorator cannot be used without arguments, at least one field must be provided. '
  380. "For example: `@field_validator('<field_name>', ...)`.",
  381. code='decorator-missing-arguments',
  382. )
  383. if mode not in ('before', 'plain', 'wrap') and json_schema_input_type is not PydanticUndefined:
  384. raise PydanticUserError(
  385. f"`json_schema_input_type` can't be used when mode is set to {mode!r}",
  386. code='validator-input-type',
  387. )
  388. if json_schema_input_type is PydanticUndefined and mode == 'plain':
  389. json_schema_input_type = Any
  390. fields = field, *fields
  391. if not all(isinstance(field, str) for field in fields):
  392. raise PydanticUserError(
  393. 'The provided field names to the `@field_validator` decorator should be strings. '
  394. "For example: `@field_validator('<field_name_1>', '<field_name_2>', ...).`",
  395. code='decorator-invalid-fields',
  396. )
  397. def dec(
  398. f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any],
  399. ) -> _decorators.PydanticDescriptorProxy[Any]:
  400. if _decorators.is_instance_method_from_sig(f):
  401. raise PydanticUserError(
  402. 'The `@field_validator` decorator cannot be applied to instance methods',
  403. code='validator-instance-method',
  404. )
  405. # auto apply the @classmethod decorator
  406. f = _decorators.ensure_classmethod_based_on_signature(f)
  407. dec_info = _decorators.FieldValidatorDecoratorInfo(
  408. fields=fields, mode=mode, check_fields=check_fields, json_schema_input_type=json_schema_input_type
  409. )
  410. return _decorators.PydanticDescriptorProxy(f, dec_info)
  411. return dec
  412. _ModelType = TypeVar('_ModelType')
  413. _ModelTypeCo = TypeVar('_ModelTypeCo', covariant=True)
  414. class ModelWrapValidatorHandler(core_schema.ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]):
  415. """`@model_validator` decorated function handler argument type. This is used when `mode='wrap'`."""
  416. def __call__( # noqa: D102
  417. self,
  418. value: Any,
  419. outer_location: str | int | None = None,
  420. /,
  421. ) -> _ModelTypeCo: # pragma: no cover
  422. ...
  423. class ModelWrapValidatorWithoutInfo(Protocol[_ModelType]):
  424. """A `@model_validator` decorated function signature.
  425. This is used when `mode='wrap'` and the function does not have info argument.
  426. """
  427. def __call__( # noqa: D102
  428. self,
  429. cls: type[_ModelType],
  430. # this can be a dict, a model instance
  431. # or anything else that gets passed to validate_python
  432. # thus validators _must_ handle all cases
  433. value: Any,
  434. handler: ModelWrapValidatorHandler[_ModelType],
  435. /,
  436. ) -> _ModelType: ...
  437. class ModelWrapValidator(Protocol[_ModelType]):
  438. """A `@model_validator` decorated function signature. This is used when `mode='wrap'`."""
  439. def __call__( # noqa: D102
  440. self,
  441. cls: type[_ModelType],
  442. # this can be a dict, a model instance
  443. # or anything else that gets passed to validate_python
  444. # thus validators _must_ handle all cases
  445. value: Any,
  446. handler: ModelWrapValidatorHandler[_ModelType],
  447. info: core_schema.ValidationInfo,
  448. /,
  449. ) -> _ModelType: ...
  450. class FreeModelBeforeValidatorWithoutInfo(Protocol):
  451. """A `@model_validator` decorated function signature.
  452. This is used when `mode='before'` and the function does not have info argument.
  453. """
  454. def __call__( # noqa: D102
  455. self,
  456. # this can be a dict, a model instance
  457. # or anything else that gets passed to validate_python
  458. # thus validators _must_ handle all cases
  459. value: Any,
  460. /,
  461. ) -> Any: ...
  462. class ModelBeforeValidatorWithoutInfo(Protocol):
  463. """A `@model_validator` decorated function signature.
  464. This is used when `mode='before'` and the function does not have info argument.
  465. """
  466. def __call__( # noqa: D102
  467. self,
  468. cls: Any,
  469. # this can be a dict, a model instance
  470. # or anything else that gets passed to validate_python
  471. # thus validators _must_ handle all cases
  472. value: Any,
  473. /,
  474. ) -> Any: ...
  475. class FreeModelBeforeValidator(Protocol):
  476. """A `@model_validator` decorated function signature. This is used when `mode='before'`."""
  477. def __call__( # noqa: D102
  478. self,
  479. # this can be a dict, a model instance
  480. # or anything else that gets passed to validate_python
  481. # thus validators _must_ handle all cases
  482. value: Any,
  483. info: core_schema.ValidationInfo[Any],
  484. /,
  485. ) -> Any: ...
  486. class ModelBeforeValidator(Protocol):
  487. """A `@model_validator` decorated function signature. This is used when `mode='before'`."""
  488. def __call__( # noqa: D102
  489. self,
  490. cls: Any,
  491. # this can be a dict, a model instance
  492. # or anything else that gets passed to validate_python
  493. # thus validators _must_ handle all cases
  494. value: Any,
  495. info: core_schema.ValidationInfo[Any],
  496. /,
  497. ) -> Any: ...
  498. ModelAfterValidatorWithoutInfo = Callable[[_ModelType], _ModelType]
  499. """A `@model_validator` decorated function signature. This is used when `mode='after'` and the function does not
  500. have info argument.
  501. """
  502. ModelAfterValidator = Callable[[_ModelType, core_schema.ValidationInfo[Any]], _ModelType]
  503. """A `@model_validator` decorated function signature. This is used when `mode='after'`."""
  504. _AnyModelWrapValidator = Union[ModelWrapValidator[_ModelType], ModelWrapValidatorWithoutInfo[_ModelType]]
  505. _AnyModelBeforeValidator = Union[
  506. FreeModelBeforeValidator, ModelBeforeValidator, FreeModelBeforeValidatorWithoutInfo, ModelBeforeValidatorWithoutInfo
  507. ]
  508. _AnyModelAfterValidator = Union[ModelAfterValidator[_ModelType], ModelAfterValidatorWithoutInfo[_ModelType]]
  509. @overload
  510. def model_validator(
  511. *,
  512. mode: Literal['wrap'],
  513. ) -> Callable[
  514. [_AnyModelWrapValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
  515. ]: ...
  516. @overload
  517. def model_validator(
  518. *,
  519. mode: Literal['before'],
  520. ) -> Callable[
  521. [_AnyModelBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
  522. ]: ...
  523. @overload
  524. def model_validator(
  525. *,
  526. mode: Literal['after'],
  527. ) -> Callable[
  528. [_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
  529. ]: ...
  530. def model_validator(
  531. *,
  532. mode: Literal['wrap', 'before', 'after'],
  533. ) -> Any:
  534. """!!! abstract "Usage Documentation"
  535. [Model Validators](../concepts/validators.md#model-validators)
  536. Decorate model methods for validation purposes.
  537. Example usage:
  538. ```python
  539. from typing_extensions import Self
  540. from pydantic import BaseModel, ValidationError, model_validator
  541. class Square(BaseModel):
  542. width: float
  543. height: float
  544. @model_validator(mode='after')
  545. def verify_square(self) -> Self:
  546. if self.width != self.height:
  547. raise ValueError('width and height do not match')
  548. return self
  549. s = Square(width=1, height=1)
  550. print(repr(s))
  551. #> Square(width=1.0, height=1.0)
  552. try:
  553. Square(width=1, height=2)
  554. except ValidationError as e:
  555. print(e)
  556. '''
  557. 1 validation error for Square
  558. Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict]
  559. '''
  560. ```
  561. For more in depth examples, see [Model Validators](../concepts/validators.md#model-validators).
  562. Args:
  563. mode: A required string literal that specifies the validation mode.
  564. It can be one of the following: 'wrap', 'before', or 'after'.
  565. Returns:
  566. A decorator that can be used to decorate a function to be used as a model validator.
  567. """
  568. def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
  569. # auto apply the @classmethod decorator. NOTE: in V3, do not apply the conversion for 'after' validators:
  570. f = _decorators.ensure_classmethod_based_on_signature(f)
  571. if mode == 'after' and isinstance(f, classmethod):
  572. warnings.warn(
  573. category=PydanticDeprecatedSince212,
  574. message=(
  575. "Using `@model_validator` with mode='after' on a classmethod is deprecated. Instead, use an instance method. "
  576. f'See the documentation at https://docs.pydantic.dev/{version_short()}/concepts/validators/#model-after-validator.'
  577. ),
  578. stacklevel=2,
  579. )
  580. dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode)
  581. return _decorators.PydanticDescriptorProxy(f, dec_info)
  582. return dec
  583. AnyType = TypeVar('AnyType')
  584. if TYPE_CHECKING:
  585. # If we add configurable attributes to IsInstance, we'd probably need to stop hiding it from type checkers like this
  586. InstanceOf = Annotated[AnyType, ...] # `IsInstance[Sequence]` will be recognized by type checkers as `Sequence`
  587. else:
  588. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  589. class InstanceOf:
  590. '''Generic type for annotating a type that is an instance of a given class.
  591. Example:
  592. ```python
  593. from pydantic import BaseModel, InstanceOf
  594. class Foo:
  595. ...
  596. class Bar(BaseModel):
  597. foo: InstanceOf[Foo]
  598. Bar(foo=Foo())
  599. try:
  600. Bar(foo=42)
  601. except ValidationError as e:
  602. print(e)
  603. """
  604. [
  605. │ {
  606. │ │ 'type': 'is_instance_of',
  607. │ │ 'loc': ('foo',),
  608. │ │ 'msg': 'Input should be an instance of Foo',
  609. │ │ 'input': 42,
  610. │ │ 'ctx': {'class': 'Foo'},
  611. │ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of'
  612. │ }
  613. ]
  614. """
  615. ```
  616. '''
  617. @classmethod
  618. def __class_getitem__(cls, item: AnyType) -> AnyType:
  619. return Annotated[item, cls()]
  620. @classmethod
  621. def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  622. from pydantic._internal._generate_schema import GENERATE_SCHEMA_ERRORS
  623. # use the generic _origin_ as the second argument to isinstance when appropriate
  624. instance_of_schema = core_schema.is_instance_schema(_generics.get_origin(source) or source)
  625. try:
  626. # Try to generate the "standard" schema, which will be used when loading from JSON
  627. original_schema = handler(source)
  628. except GENERATE_SCHEMA_ERRORS:
  629. # If that fails, just produce a schema that can validate from python
  630. return instance_of_schema
  631. else:
  632. # Use the "original" approach to serialization
  633. instance_of_schema['serialization'] = core_schema.wrap_serializer_function_ser_schema(
  634. function=lambda v, h: h(v), schema=original_schema
  635. )
  636. return core_schema.json_or_python_schema(python_schema=instance_of_schema, json_schema=original_schema)
  637. __hash__ = object.__hash__
  638. if TYPE_CHECKING:
  639. SkipValidation = Annotated[AnyType, ...] # SkipValidation[list[str]] will be treated by type checkers as list[str]
  640. else:
  641. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  642. class SkipValidation:
  643. """If this is applied as an annotation (e.g., via `x: Annotated[int, SkipValidation]`), validation will be
  644. skipped. You can also use `SkipValidation[int]` as a shorthand for `Annotated[int, SkipValidation]`.
  645. This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes,
  646. and know that it is safe to skip validation for one or more of the fields.
  647. Because this converts the validation schema to `any_schema`, subsequent annotation-applied transformations
  648. may not have the expected effects. Therefore, when used, this annotation should generally be the final
  649. annotation applied to a type.
  650. """
  651. def __class_getitem__(cls, item: Any) -> Any:
  652. return Annotated[item, SkipValidation()]
  653. @classmethod
  654. def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  655. with warnings.catch_warnings():
  656. warnings.simplefilter('ignore', ArbitraryTypeWarning)
  657. original_schema = handler(source)
  658. metadata = {'pydantic_js_annotation_functions': [lambda _c, h: h(original_schema)]}
  659. return core_schema.any_schema(
  660. metadata=metadata,
  661. serialization=core_schema.wrap_serializer_function_ser_schema(
  662. function=lambda v, h: h(v), schema=original_schema
  663. ),
  664. )
  665. __hash__ = object.__hash__
  666. _FromTypeT = TypeVar('_FromTypeT')
  667. class ValidateAs:
  668. """A helper class to validate a custom type from a type that is natively supported by Pydantic.
  669. Args:
  670. from_type: The type natively supported by Pydantic to use to perform validation.
  671. instantiation_hook: A callable taking the validated type as an argument, and returning
  672. the populated custom type.
  673. Example:
  674. ```python {lint="skip"}
  675. from typing import Annotated
  676. from pydantic import BaseModel, TypeAdapter, ValidateAs
  677. class MyCls:
  678. def __init__(self, a: int) -> None:
  679. self.a = a
  680. def __repr__(self) -> str:
  681. return f"MyCls(a={self.a})"
  682. class Model(BaseModel):
  683. a: int
  684. ta = TypeAdapter(
  685. Annotated[MyCls, ValidateAs(Model, lambda v: MyCls(a=v.a))]
  686. )
  687. print(ta.validate_python({'a': 1}))
  688. #> MyCls(a=1)
  689. ```
  690. """
  691. # TODO: make use of PEP 747
  692. def __init__(self, from_type: type[_FromTypeT], /, instantiation_hook: Callable[[_FromTypeT], Any]) -> None:
  693. self.from_type = from_type
  694. self.instantiation_hook = instantiation_hook
  695. def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  696. schema = handler(self.from_type)
  697. return core_schema.no_info_after_validator_function(
  698. self.instantiation_hook,
  699. schema=schema,
  700. )