liveBook · Manning

Typing module

As explained in Python Workout: 50 ten-minute exercises

The typing module is Python's standard-library module providing constructs for expressing and inspecting type annotations.

Python’s typing module provides objects for type annotations. List describes a list, while List[Scoop] indicates that every element should be a Scoop. section 9.10

Annotating a mutable dataclass attribute

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 scoop in new_scoops: self.scoops.append(scoop) section 9.10

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains List and List[Scoop] through a complete Bowl example, without surveying the wider typing module.
Examples
Uses a Bowl containing List[Scoop] values and a default_factory that creates a fresh list for each instance.
What it assumes
Assumes familiarity with Python classes, attributes, lists, and dataclass definitions.
What you can do after
Apply it via List[T] annotations to describe the expected element type of a collection attribute.
How it connects
Connects type annotations with dataclasses, mutable default values, default_factory, lists, and custom classes.

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.