Type hints label the values that names or expressions are intended to hold. They remain optional in ordinary Python and do not enforce types at runtime; external tools such as Mypy perform type checking. section 9.10 section 9.2
Annotating dataclass attributes
A dataclass uses annotations to describe its fields while generating boilerplate such as __init__. A simple field can be written as flavor: str. Collection annotations can be more specific, such as scoops: List[Scoop], with List imported from typing. section 9.10
@dataclass class Scoop(): flavor : str
Use the compact Scoop definition to see an annotation supplying the field type while @dataclass supplies the initializer. section 9.10
from typing import List
from dataclasses import dataclass, field
@dataclass
class Bowl():
scoops: List[Scoop] = field(default_factory=list)
def add_scoops(self, *new_scoops):
for one_scoop in new_scoops:
self.scoops.append(one_scoop)
def __repr__(self):
return '\n'.join(s.flavor for s in self.scoops)
Use the Bowl definition to compare a typed list field with field(default_factory=list), which supplies each instance with a default collection. section 9.10
















