Home > other >  Python dataclass call parent field from constructor
Python dataclass call parent field from constructor

Time:01-28

Is it possible to inherit data class and use parent field in child constructor?

import dataclasses


def get_id():
    return "some unique id"

@dataclasses.dataclass
class Parent:
    name: str
    uid: str = dataclasses.field(default_factory=lambda: get_id())

@dataclasses.dataclass
class Child(Parent):
    dependent_on_id: str = dataclasses.field(default_factory=lambda: f"with {super.uid}")


c = Child(name='x')
print("foo "   c.uid)
print(c.dependent_on_id)

Output:

Traceback (most recent call last):
  File "stack_questions.py", line 17, in <module>
    c = Child(name='x')
  File "<string>", line 5, in __init__
  File "stack_questions.py", line 14, in <lambda>
    dependent_on_id: str = dataclasses.field(default_factory=lambda: f"with {super.uid}")
AttributeError: type object 'super' has no attribute 'uid'

Want Output:

foo some unique id
with foo some unique id

Currently it seems to me that my best solution will be to just do it via composition rather than inhiritence

CodePudding user response:

super doesn't make sense in that context. You can use dataclass' __post_init__ method to set dependent_on_id.

@dataclasses.dataclass
class Child(Parent):
    dependent_on_id: str = None 

    def __post_init__(self):
        if not self.dependent_on_id:
            self.dependent_on_id = f"with {self.uid}" # you don't need super
  •  Tags:  
  • Related