liveBook · Manning

Typing.List

As explained in Python Workout: 50 ten-minute exercises

typing.List is a generic type-annotation construct describing lists whose elements have a specified type.

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

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines bare and parameterized List forms, then addresses mutable dataclass defaults with default_factory.
Examples
Uses Bowl.scoops as a List[Scoop] and implements it with field(default_factory=list).
What you can do after
Apply it via Python's typing module to communicate list element types in class definitions.
How it connects
Connects generic type annotations, dataclasses, mutable defaults, and default_factory.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.