MCPcopy
hub / github.com/pydantic/pydantic / BeforeValidator

Class BeforeValidator

pydantic/functional_validators.py:90–153  ·  view source on GitHub ↗

!!! abstract "Usage Documentation" [field *before* validators](../concepts/validators.md#field-before-validator) A metadata class that indicates that a validation should be applied **before** the inner validation logic. Attributes: func: The validator function. json

Source from the content-addressed store, hash-verified

88
89@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
90class BeforeValidator:
91 """!!! abstract "Usage Documentation"
92 [field *before* validators](../concepts/validators.md#field-before-validator)
93
94 A metadata class that indicates that a validation should be applied **before** the inner validation logic.
95
96 Attributes:
97 func: The validator function.
98 json_schema_input_type: The input type used to generate the appropriate
99 JSON Schema (in validation mode). The actual input type is `Any`.
100
101 Example:
102 ```python
103 from typing import Annotated
104
105 from pydantic import BaseModel, BeforeValidator
106
107 MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)]
108
109 class Model(BaseModel):
110 a: MyInt
111
112 print(Model(a=1).a)
113 #> 2
114
115 try:
116 Model(a='a')
117 except TypeError as e:
118 print(e)
119 #> can only concatenate str (not "int") to str
120 ```
121 """
122
123 func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
124 json_schema_input_type: Any = PydanticUndefined
125
126 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
127 schema = handler(source_type)
128 input_schema = (
129 None
130 if self.json_schema_input_type is PydanticUndefined
131 else handler.generate_schema(self.json_schema_input_type)
132 )
133
134 info_arg = _inspect_validator(self.func, mode='before', type='field')
135 if info_arg:
136 func = cast(core_schema.WithInfoValidatorFunction, self.func)
137 return core_schema.with_info_before_validator_function(
138 func,
139 schema=schema,
140 json_schema_input_schema=input_schema,
141 )
142 else:
143 func = cast(core_schema.NoInfoValidatorFunction, self.func)
144 return core_schema.no_info_before_validator_function(
145 func, schema=schema, json_schema_input_schema=input_schema
146 )
147

Calls

no outgoing calls