Chapter 15. More About Type Hints
I learned a painful lesson that for small programs, dynamic typing is great. For large programs you need a more disciplined approach. And it helps if the language gives you that discipline rather than telling you “Well, you can do whatever you want”.
Guido van Rossum, a fan of Monty Python1
This chapter is a sequel to Chapter 8, covering more of Python’s gradual type system. The main topics are:
-
Overloaded function signatures
-
typing.TypedDict
for type hintingdicts
used as records -
Type casting
-
Runtime access to type hints
-
Generic types
-
Declaring a generic class
-
Variance: invariant, covariant, and contravariant types
-
Generic static protocols
-
What’s New in This Chapter
This chapter is new in the second edition of Fluent Python. Let’s start with overloads.
Overloaded Signatures
Python functions may accept different combinations of arguments.
The @typing.overload
decorator allows annotating those different combinations.
This is particularly important when the return type of the function
depends on the type of two or more parameters.
Consider the sum
built-in function. This is the text of help(sum)
:
>>> help(sum) sum(iterable, /, start=0) Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.
The sum
built-in is written in C, but typeshed has overloaded ...
Get Fluent Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.