mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
Run dataclass' original __post_init__ before validation (#560)
* Run dataclass' original __post_init__ before validation * Add unit test * Update HISTORY.rst
This commit is contained in:
committed by
Samuel Colvin
parent
4263258207
commit
79ed78fda0
@@ -6,6 +6,8 @@ History
|
||||
v0.xx (xxxx-xx-xx)
|
||||
..................
|
||||
* fix JSON Schema for ``list``, ``tuple``, and ``set``, #540 by @tiangolo
|
||||
* Change `_pydantic_post_init` to execute dataclass' original `__post_init__` before
|
||||
validation, #560 by @HeavenVolkoff
|
||||
|
||||
v0.26 (2019-05-22)
|
||||
..................
|
||||
|
||||
@@ -25,11 +25,11 @@ if TYPE_CHECKING: # pragma: no cover
|
||||
|
||||
|
||||
def _pydantic_post_init(self: 'DataclassType') -> None:
|
||||
if self.__post_init_original__:
|
||||
self.__post_init_original__()
|
||||
d = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__)[0]
|
||||
object.__setattr__(self, '__dict__', d)
|
||||
object.__setattr__(self, '__initialised__', True)
|
||||
if self.__post_init_original__:
|
||||
self.__post_init_original__()
|
||||
|
||||
|
||||
def _validate_dataclass(cls: Type['DataclassType'], v: Any) -> 'DataclassType':
|
||||
|
||||
@@ -107,6 +107,25 @@ def test_post_init():
|
||||
assert post_init_called
|
||||
|
||||
|
||||
def test_post_init_assignment():
|
||||
from dataclasses import field
|
||||
|
||||
# Based on: https://docs.python.org/3/library/dataclasses.html#post-init-processing
|
||||
@pydantic.dataclasses.dataclass
|
||||
class C:
|
||||
a: float
|
||||
b: float
|
||||
c: float = field(init=False)
|
||||
|
||||
def __post_init__(self):
|
||||
self.c = self.a + self.b
|
||||
|
||||
c = C(0.1, 0.2)
|
||||
assert c.a == 0.1
|
||||
assert c.b == 0.2
|
||||
assert c.c == 0.30000000000000004
|
||||
|
||||
|
||||
def test_inheritance():
|
||||
@pydantic.dataclasses.dataclass
|
||||
class A:
|
||||
|
||||
Reference in New Issue
Block a user