MCPcopy
hub / github.com/pydantic/pydantic / WrapValidator

Class WrapValidator

pydantic/functional_validators.py:257–328  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

255
256@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
257class WrapValidator:
258 """!!! abstract "Usage Documentation"
259 [field *wrap* validators](../concepts/validators.md#field-wrap-validator)
260
261 A metadata class that indicates that a validation should be applied **around** the inner validation logic.
262
263 Attributes:
264 func: The validator function.
265 json_schema_input_type: The input type used to generate the appropriate
266 JSON Schema (in validation mode). The actual input type is `Any`.
267
268 ```python
269 from datetime import datetime
270 from typing import Annotated
271
272 from pydantic import BaseModel, ValidationError, WrapValidator
273
274 def validate_timestamp(v, handler):
275 if v == 'now':
276 # we don't want to bother with further validation, just return the new value
277 return datetime.now()
278 try:
279 return handler(v)
280 except ValidationError:
281 # validation failed, in this case we want to return a default value
282 return datetime(2000, 1, 1)
283
284 MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
285
286 class Model(BaseModel):
287 a: MyTimestamp
288
289 print(Model(a='now').a)
290 #> 2032-01-02 03:04:05.000006
291 print(Model(a='invalid').a)
292 #> 2000-01-01 00:00:00
293 ```
294 """
295
296 func: core_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunction
297 json_schema_input_type: Any = PydanticUndefined
298
299 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
300 schema = handler(source_type)
301 input_schema = (
302 None
303 if self.json_schema_input_type is PydanticUndefined
304 else handler.generate_schema(self.json_schema_input_type)
305 )
306
307 info_arg = _inspect_validator(self.func, mode='wrap', type='field')
308 if info_arg:
309 func = cast(core_schema.WithInfoWrapValidatorFunction, self.func)
310 return core_schema.with_info_wrap_validator_function(
311 func,
312 schema=schema,
313 json_schema_input_schema=input_schema,
314 )

Callers 4

ModelClass · 0.90
MyModelClass · 0.90

Calls

no outgoing calls

Tested by 1