Micael Jarniac <mic...@jarniac.com> added the comment:

I'm trying to think of an example, and what I've thought of so far is having a 
base dataclass that has a `__post_init__` method, and another dataclass that 
inherits from it and also has a `__post_init__` method.

In that case, the subclass might need to call `super().__post_init__()` inside 
its own `__post_init__` method, because otherwise, that wouldn't get called 
automatically.

Something along those lines:

>>> from dataclasses import dataclass, field
>>>
>>> @dataclass
... class A:
...     x: int
...     y: int
...     xy: int = field(init=False)
...
...     def __post_init__(self) -> None:
...         self.xy = self.x * self.y
...
>>> @dataclass
... class B(A):
...     m: int
...     n: int
...     mn: int = field(init=False)
...
...     def __post_init__(self) -> None:
...         super().__post_init__()
...         self.mn = self.m * self.n
...
>>> b = B(x=2, y=4, m=3, n=6)
>>> b
B(x=2, y=4, xy=8, m=3, n=6, mn=18)

In this example, if not for the `super().__post_init__()` call inside B's 
`__post_init__`, we'd get an error `AttributeError: 'B' object has no attribute 
'xy'`.

I believe this could be an actual pattern that could be used when dealing with 
dataclasses.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44365>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to