liveBook · Manning

Type hints

As explained in The Quick Python Book, Fourth Edition

A type hint is syntax that annotates the intended type of a value associated with a variable, parameter, return value, or similar program element.

Python associates types with objects, not variables. A name can refer to objects of different types, but an unexpected type may cause a failure only when the code runs. Type hints optionally state the intended types of variables, function parameters, and return values. Python does not enforce them at runtime; type checkers and IDEs can use them to flag mismatches earlier. section 1.3.2 section 4.4

def add_ints(x: int, y: int) -> int:       #1
     return x + y
 
p: int = 2.3                               #2
z = add_ints(1, 2)
w = add_ints(1.5, 2.5)                     #3

A colon annotates a variable or parameter; an arrow annotates a return value. Here, the hints say that both arguments and the result of `add_ints` should be integers. Python runs the code, but mypy flags three mismatches: assigning a float to `p` and passing two floats to `add_ints`. section 4.4

Hints are most useful where an expected type is otherwise unclear or a mismatch would be hard to trace through a large codebase. They can be added progressively, starting where type information helps most. In a small informal script, the extra notation may not be worth the effort; annotating everything can also make definitions harder to read. Type hints offer a way to check expectations without requiring every piece of Python code to be typed. section 4.4.1 section 4.4.2 section 4.4.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through variable, parameter, and return annotations with mypy errors, but does not develop advanced annotation forms.
Examples
Shows an integer-addition function, a float assigned to an int-annotated variable, and three mypy errors.
What it assumes
Assumes familiarity with variables, functions, and numeric types while introducing annotation syntax through a small example.
What you can do after
Apply type hints with mypy to flag incompatible assignments and function arguments before runtime.
How it connects
Relates type hints to dynamic typing, duck typing, type checkers, and IDE warnings.

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 The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.