bored-monitor-99026
04/11/2022, 2:22 AMtype Team struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Slug string `yaml:"slug"`
ParentTeamId int
Teams []Team `yaml:"teams"`
}
here is what i have:
@dataclass
class Team:
name: str
slug: str
description: str
...
subteams: Optional[list[Team]]
parent_team_id: Optional[int] = None
the team data is read from a yaml file
here are several issues:
1. in order to use .
refence , you have to do Team(**team)
to create the object, where team
is a python dict read from YAML. however, this will be flagged by type checker: Arguments missing for parameters "name", "slug", "description
2. there is a nested field subteams
, when reading from yaml, it's not automatically deserialized, so you have to create the object again Team(**sub_team)
to use .
reference
3. since not every team entry has subteam
field, you have to assign empty list as default value. but when you iterate over the entries in yaml, you will have type error Object of type "None" cannot be used as iterable value
when you do parent_team.subteams
prehistoric-activity-61023
04/11/2022, 7:07 AMclass Team(BaseModel):
name: str
slug: str
description: str
parent_team_id: Optional[int]
subteams: Optional[List["Team"]]
team = Team.parse_obj(your_python_dict)
subteams: List["Team"] = []
vs
subteams: Optional[List["Team"]]
Ensure that you really want to have an optional here ๐.breezy-painter-29573
04/11/2022, 1:22 PMprehistoric-activity-61023
04/11/2022, 2:16 PMbored-monitor-99026
04/12/2022, 3:45 AMpydantic
solved my problem nicely!!๐prehistoric-activity-61023
04/12/2022, 5:28 AM@dataclass
class Team:
subteams: List["Team"] = field(default_factory=lambda: [])
...
shy-arm-32391
04/18/2022, 4:05 PM