Home > front end >  How to pass parameters to nestting @dataclass
How to pass parameters to nestting @dataclass

Time:04-22

I got 2 data classes. I want to pass parameters to One and be able to get it on Two.

@dataclass
class One:

    id: int = 0
    text: str = "New York"
    a: str = ""
    b: str = ""

    def __post_init__(self):
        self.params = [self.a, Two(name=self.b)]
    params: List = field(default_factory=list)


@dataclass
class Two:
    home: List = field(default_factory=list)
    name: str = ""

somehow -> One(a = "test1", b = "text2")

Result what I want to get:

{
   "id":0,
   "text":"abc",
   "params":[
      "test1",
      {
         "home":[],
         "name":"text2"
      }
   ]
}

CodePudding user response:

Use InitVar to only mark a field as "init-only", it's passed to __post_init__ and is not stored as a regular field

from dataclasses import dataclass, field, InitVar, asdict


@dataclass
class Two:
    home: list = field(default_factory=list)
    name: str = ""


@dataclass
class One:

    id: int = 0
    text: str = "New York"
    params: list = field(default_factory=list)

    a: InitVar[str] = ""
    b: InitVar[str] = ""

    def __post_init__(self, a, b):
        self.params = [a, Two(name=b)]


print(asdict(One(a="test1", b="text2")))
# {'id': 0, 'text': 'New York', 'params': ['test1', {'home': [], 'name': 'text2'}]}
  • Related