When a class attribute should hold a list of consistently typed objects, use typing.List with square brackets. List by itself permits any element type; List[Scoop] communicates that the list contains Scoop objects, while remaining distinct from the built-in list type. section 9.10
Use the annotation to distinguish the intended element type:
- List describes a list whose elements may have any type. section 9.10
- List[Scoop] describes a list whose elements are Scoop objects. section 9.10
- For a mutable dataclass list attribute, pair the annotation with field(default_factory=list) so each instance receives a new list. 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)
The complete Bowl example combines typing.List[Scoop] with a dataclass field factory, an add_scoops method, and a representation built from the stored objects. section 9.10
