liveBook · Manning

Type hints

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A type hint is optional Python syntax that annotates the expected types of variables, parameters, or return values without enforcing them during ordinary execution.

Type hints are optional Python annotations for variable values, function parameters, and return values. Python ignores them during ordinary execution; tools such as Mypy use them to detect incompatible types before running the program. section 22.1.3 section 22.4

A typed Tic-Tac-Toe state can describe both fields and their defaults:

  • Use NamedTuple fields such as board: List[str], player: str, quit: bool, and winner: Optional[str]. section 22.1.3
  • Annotate functions with parameter types and return types, such as format_board(board: List[str]) -> str. section 22.1.6
  • Use custom types such as State in function signatures so Mypy can check the values passed between functions. section 22.1.6

Runtime acceptance, static rejection

State(quit='True') still runs and stores the string because Python does not enforce the annotation. Running Mypy instead reports that quit expects bool; changing the value to True produces no issues. section 22.1.4

$ mypy typehints.py
typehints.py:16: error: Argument "quit" to "State" has incompatible type "str"; expected "bool"
Found 1 error in 1 file (checked 1 source file)

The diagnostic output makes the practical role of type hints visible: Mypy identifies the incompatible argument and expected type. section 22.1.4

Type hints work especially well with structured state. NamedTuple supplies named, immutable fields, while TypedDict and NamedTuple can define reusable types for later function annotations. section 22.1.1 section 22.4

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains variable and function annotations through a typed game state, but stops short of runtime enforcement.
Examples
Demonstrates a Tic-Tac-Toe State, Optional fields, annotated board functions, and Mypy diagnostics for an incorrectly typed quit value.
What it assumes
Assumes Python data structures and functions, while introducing typing syntax, Optional, NamedTuple, TypedDict, and static checking.
What you can do after
Diagnose/debug with Mypy by annotating data and function interfaces, then correct incompatible values before running the program.
How it connects
Connects type hints with Mypy, NamedTuple, TypedDict, tuples, function signatures, and unit testing.

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 Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.