Inherit from dataclass without specifying everything in subclass' __init__?

Viewed 56

I'm building a hierarchy of dataclasses.dataclass (Python 3.10).

E.g.

import dataclasses

@dataclasses.dataclass
class A:
    a: int

@dataclasses.dataclass
class B(A):
    b: int

I now have a bunch of As, which I want to additionally specify as B without adding all of A's properties to the constructor. Something like this:

a = A(1)

b = B(a, 1)

I know I could use dataclasses.asdict

b = B(**dataclasses.asdict(a), b=1)

Is this an acceptable solution in the sense of best practice? It looks a bit inefficient and less readable than it could be.

I tried overwriting the B.__init__ (and B.__new__) but this seems like too much code is needed. And with overwriting the __init__, it's not possible to make the dataclass frozen.

1 Answers

You can define a classmethod on B to make your approach more ergonomic.

@dataclasses.dataclass
class B(A):
    b: int
    
    @classmethod
    def from_A(cls, a, **kwargs):        
        return cls(**dataclasses.asdict(a), **kwargs)

b = B.from_A(a, b=1)
Related