Default value based on other field

35 views Asked by At

Is there a way to have the following:

from dataclasses import dataclass, fields

@dataclass
class ExampleCls:
    category: str
    subcategory: str = f"{category} level 2"
  1. ExampleCls(category="hi")
    • works with field(init=False) and returns ExampleCls(category="hi", subcategory=f"{category} level 2")
  2. ExampleCls(category="hi", subcategory="greetings")
    • here I expect ExampleCls(category="hi", subcategory="greetings")
    • with field(init=False), I will get an error: got an unexpected keyword argument 'subcategory'

the field(default_factory) does not accept arguments from the other fields

0

There are 0 answers