A type annotation associates a name or expression with an intended type; it does not enforce runtime type checking. External tools such as Mypy perform that checking. section 10.12
Dataclasses use annotations to identify instance attributes and generate boilerplate such as __init__, comparisons, and repr. Unlike ordinary annotations, dataclass attributes require types. section 10.12
Annotating nested data
In a Bowl dataclass, list[Scoop] states that scoops contains Scoop objects. Because the list is mutable, field(default_factory=list) gives each Bowl its own list. section 10.12
from dataclasses import dataclass
@dataclass
class Scoop():
flavor : str
See the minimal dataclass annotation that declares flavor as a string. section 10.12
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)
Compare a collection annotation with a per-instance mutable default. section 10.12
















