Skip to content

__post_init__ is not triggered for descendant dataclass  #739

@krassowski

Description

@krassowski

The __post_init__ method of parent is not called in child classes.

  • OS: Ubuntu
  • Python version import sys; print(sys.version): **3.7.2 (default, Mar 25 2019, 19:29:53) **
  • Pydantic version import pydantic; print(pydantic.VERSION): 0.32.1
from dataclasses import dataclass, field
from typing import Any

# comment the pydantinc import below to see the expected result
from pydantic.dataclasses import dataclass

@dataclass
class Base:
    x: float
    y: float

    def __post_init__(self):
        print('Called!')
        self.z = self.x + self.y

@dataclass
class Child(Base):
    a: int

obj = Child(a=0, x=1.5, y=2.5)
print(obj.z)

Everything works fine when using the dataclass from standard library. After looking through the code I expected that an easy workaround would be to add simple __post_init__ in child:

@dataclass
class Child(Base):
    a: int

    def __post_init__(self):
        super().__post_init__()

Now I do get 'Called!' message, but the 'z' attribute is not preserved anyway...

Do I miss something obvious in the usage of pydantic?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions