liveBook · Manning

Type hints

As explained in Python Workout, Second Edition

A type annotation is syntax that associates a name or expression with an intended type without itself enforcing runtime type checking.

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

How Python Workout, Second Edition covers it

How deep it goes
Explains annotation syntax, dataclass requirements, collection types, and runtime limitations, but defers detailed Mypy usage.
Examples
Demonstrates str on Scoop.flavor and list[Scoop] with field(default_factory=list) on Bowl.scoops.
What you can do after
Build dataclasses with annotated scalar and collection attributes while avoiding shared mutable defaults.
How it connects
Connects type hints with dataclasses, static type checking, Mypy, and mutable default values.

Also explained in

Compare how 17 books explain type hints →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.