Skip to content

Commit

Permalink
Documentation sprint chunk (pydantic#8646)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle authored Jan 26, 2024
1 parent b2092e8 commit b785d5b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/concepts/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
35 changes: 35 additions & 0 deletions docs/concepts/validators.md
Original file line number Diff line number Diff line change
Expand Up @@ -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')
```

0 comments on commit b785d5b

Please sign in to comment.