liveBook · Manning

Type hints

As explained in Python Workout: 50 ten-minute exercises

A type annotation is optional Python syntax that associates a name or expression with an intended type without enforcing that type at runtime.

Type hints label the values that names or expressions are intended to hold. They remain optional in ordinary Python and do not enforce types at runtime; external tools such as Mypy perform type checking. section 9.10 section 9.2

Annotating dataclass attributes

A dataclass uses annotations to describe its fields while generating boilerplate such as __init__. A simple field can be written as flavor: str. Collection annotations can be more specific, such as scoops: List[Scoop], with List imported from typing. section 9.10

@dataclass
class Scoop():
   flavor : str

Use the compact Scoop definition to see an annotation supplying the field type while @dataclass supplies the initializer. 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)

Use the Bowl definition to compare a typed list field with field(default_factory=list), which supplies each instance with a default collection. section 9.10

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines optional runtime metadata and typed collections, but stops short of runtime enforcement and detailed Mypy usage.
Examples
Uses Scoop's str field and Bowl's List[Scoop] field with a default factory.
What it assumes
Assumes familiarity with Python classes and attributes, while clarifying that annotations do not enforce types during execution.
What you can do after
Apply it via dataclasses and Mypy to document intended values and perform external type checking.
How it connects
Connects type annotations with dataclasses, the typing module, and Mypy.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.