Skip to content

Commit

Permalink
Improve initialization hooks example (#6822)
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Jul 24, 2023
1 parent 5514cbe commit 2c44911
Showing 1 changed file with 17 additions and 10 deletions.
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

0 comments on commit 2c44911

Please sign in to comment.