I have a set of dataclasses say:
from dataclasses import dataclass, asdict, InitVar
@dataclass
class Item:
name: str = None
identifier: int = None
@dataclass
class Container:
item: Item
cid: int
cname: str = None
When I do:
c = Container(Item(name="item-1"), cid=10)
asdict(c)
I get:
{'item': {'name': 'item-1', 'identifier': None},'cid': 10,'cname': None}
But in my schema Item is a "choice" type so I only want to include "name" or "identifier" in "asdict" depending on which of those are actually set (ONLY for Item type).
something like:
{'item': {'name': 'item-1'},'cid': 10,'cname': None}
OR:
{'item': {'identifier': 'id-1'},'cid': 10,'cname': None}
My original code is much more complex and the relationships are more nested so I'm looking for a solution which I can apply to the specific dataclass. I tried manipulating the __dict__
to add attributes in __post_init__
but that didn't work. For e.g. I tried
from dataclasses import dataclass, asdict, InitVar
@dataclass
class Item:
name: InitVar[str] = None
identifier: InitVar[int] = None
def __post_init__(self, name, identifier):
if name:
self.name = name
elif identifier:
self.identifier = identifier
print(self.__dict__)
@dataclass
class Container:
item: Item
identifier: int
cname: str = None
c = Container(Item(name="item-1"), cid=10)
asdict(c)
but that prints
{'item': {}, 'cid': 10, 'cname': None}