I have a parent class, that contains a child class. Both are implemented with python dataclasses. The classes look like this:
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Parent:
name: str
child: Child
@dataclass
class Child:
parent: Parent
The goal is, to access the child class from the parent class, but also the parent class from the child class. At the same time I don't want to have to annotate either of the references as Optional.
Since the child object only exist with a parent object, this would possible:
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Parent:
name: str
child: Child
def __post_init__(self):
self.child.parent = self
@dataclass
class Child:
parent: Parent = None
Parent(name="foo", child=Child())
However, since I am using mypy, it complains that Child.parent should be annotated with Optional[Parent]. In practice this is only true until after the __post_init__ call. How could I get around this issue?
__post_init__, rather than expecting an incompletely-initialized child be passed toParent.__init__.