From b785d5b1db4eccb922dd2bf17faea5fc842e6a57 Mon Sep 17 00:00:00 2001 From: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com> Date: Fri, 26 Jan 2024 12:30:19 -0600 Subject: [PATCH] Documentation sprint chunk (#8646) --- docs/concepts/performance.md | 2 +- docs/concepts/validators.md | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/docs/concepts/performance.md b/docs/concepts/performance.md index 61b92f5398..501fa812c5 100644 --- a/docs/concepts/performance.md +++ b/docs/concepts/performance.md @@ -7,7 +7,7 @@ In most cases Pydantic won't be your bottle neck, only follow this if you're sur On `model_validate(json.loads(...))`, the JSON is parsed in Python, then converted to a dict, then it's validated internally. On the other hand, `model_validate_json()` already performs the validation internally. -There are a few cases where `model_validate(json.loads(...))` may be faster. Specifically, when using a `'before'` validator +There are a few cases where `model_validate(json.loads(...))` may be faster. Specifically, when using a `'before'` or `'wrap'` validator on a model, validation may be faster with the two step method. You can read more about these special cases in [this discussion](https://github.com/pydantic/pydantic/discussions/6388#discussioncomment-8193105). diff --git a/docs/concepts/validators.md b/docs/concepts/validators.md index 5879ee8d12..c6364c54a0 100644 --- a/docs/concepts/validators.md +++ b/docs/concepts/validators.md @@ -754,3 +754,38 @@ with init_context({'multiplier': 3}): print(Model(my_number=2)) #> my_number=2 ``` + +## Reusing Validators + +Occasionally, you will want to use the same validator on multiple fields/models (e.g. to normalize some input data). +The "naive" approach would be to write a separate function, then call it from multiple decorators. +Obviously, this entails a lot of repetition and boiler plate code. +The following approach demonstrates how you can reuse a validator so that redundancy is minimized and the models become again almost declarative. + +```py +from pydantic import BaseModel, field_validator + + +def normalize(name: str) -> str: + return ' '.join((word.capitalize()) for word in name.split(' ')) + + +class Producer(BaseModel): + name: str + + _normalize_name = field_validator('name')(normalize) + + +class Consumer(BaseModel): + name: str + + _normalize_name = field_validator('name')(normalize) + + +jane_doe = Producer(name='JaNe DOE') +print(repr(jane_doe)) +#> Producer(name='Jane Doe') +john_doe = Consumer(name='joHN dOe') +print(repr(john_doe)) +#> Consumer(name='John Doe') +```