3

What is the right way to convert between dataclasses in python that inherit from each other (without repetitive code)?

Example:

from dataclasses import dataclass

@dataclass
class Parent:
    p1: int
    # …

@dataclass
class Child(Parent):
    c1: int
    # …

My attempt:

# Fail: How to call the parent constructor (like in C++)?
def make_child(parent: Parent, c1: int, …) -> Child:
    return Child(
        p1=parent.p1,
        # …
        c1=c1,
        # …
    )

# Fail: How to implicitly cast to parent (like in C++)?
def get_parent(child: Child) -> Parent:
    return Parent(
        p1=child.p1,
        # …
    )

I know that this would be easy with composition instead of inheritance, but that's not my question.

user2394284
  • 5,520
  • 4
  • 32
  • 38
  • How do these examples fail? They look fine to me. – tzaman Feb 09 '21 at 14:54
  • 1
    what you want is not possible in a general sense, since dataclasses can have init-only parameters. Because of that, passing an instance of Parent to a Child constructor would be lacking that information. For simple cases without InitVars you can use this pattern: https://stackoverflow.com/questions/54824893/python-dataclass-that-inherits-from-base-dataclass-how-do-i-upgrade-a-value-fr/55065215#55065215, and change the signature and call to something like `def from_instance(cls, instance, **kwargs): return cls(**dataclasses.asdict(instance), **kwargs)` for adding custom child attributes. – Arne Feb 10 '21 at 11:30

0 Answers0