Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve initialization hooks example #6822

Merged
merged 2 commits into from
Jul 24, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 17 additions & 10 deletions docs/usage/dataclasses.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,25 +378,35 @@ class User:

@model_validator(mode='before')
def pre_root(cls, values: Dict[str, Any]) -> Dict[str, Any]:
print(values)
#> ArgsKwargs((), {'birth': {'year': 1995, 'month': 3, 'day': 2}})
print(f'First: {values}')
"""
First: ArgsKwargs((), {'birth': {'year': 1995, 'month': 3, 'day': 2}})
"""
return values

@model_validator(mode='after')
def post_root(self) -> 'User':
print(self)
#> User(birth=Birth(year=1995, month=3, day=2))
print(f'Third: {self}')
#> Third: User(birth=Birth(year=1995, month=3, day=2))
return self

def __post_init__(self):
print(self.birth)
#> Birth(year=1995, month=3, day=2)
print(f'Second: {self.birth}')
#> Second: Birth(year=1995, month=3, day=2)


user = User(**{'birth': {'year': 1995, 'month': 3, 'day': 2}})
```

The `__post_init__` in Pydantic dataclasses is called _after_ validation, rather than before.
The `__post_init__` in Pydantic dataclasses is called in the _middle_ of validators.
Here is the order:

* `model_validator(mode='before')`
* `field_validator(mode='before')`
* `field_validator(mode='after')`
* Inner validators. e.g. validation for types like `int`, `str`, ...
* `__post_init__`.
* `model_validator(mode='after')`


```py requires="3.8"
Expand Down Expand Up @@ -428,9 +438,6 @@ assert path_data.path == Path('/hello/world')

Note that the `dataclasses.dataclass` from Python stdlib implements only the `__post_init__` method since it doesn't run a validation step.

When substituting usage of `dataclasses.dataclass` with `pydantic.dataclasses.dataclass`, it is recommended to move the code executed in the `__post_init__` to
methods decorated with `model_validator`.

## JSON dumping

Pydantic dataclasses do not feature a `.model_dump_json()` function. To dump them as JSON, you will need to
Expand Down