The example provided outputs an error at run time.
body_measurement: Optional[NamedTuple('height': List, 'weight': List)] = None
^
SyntaxError: invalid syntax
To fix it you need
from typing import NamedTuple, List, Optional
class BabyData(NamedTuple):
name: str
age: int
body_measurement: Optional[
NamedTuple("BodyMeasurement", [("height", List), ("weight", List)])
] = None
if __name__ == "__main__":
baby = BabyData(
name="john", age=1, body_measurement={"height": [50, 51], "weight": [3, 3.5]}
)
print(baby)
# BabyData(name='john', age=1, body_measurement={'height': [50, 51], 'weight': [3, 3.5]})
In fact you try to mix two ways of defining NamedTuple
. As per the documentation.
class Employee(NamedTuple):
name: str
id: int
# This is equivalent to:
Employee = collections.namedtuple('Employee', ['name', 'id'])
You should also consider using dataclasses
, see the foxyblue's answer.