Skip to Content
Fluent Python, 2nd Edition
book

Fluent Python, 2nd Edition

by Luciano Ramalho
April 2022
Intermediate to advanced
1014 pages
23h 59m
English
O'Reilly Media, Inc.
Book available
Content preview from Fluent Python, 2nd Edition

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 hinting dicts 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Fluent Python

Fluent Python

Luciano Ramalho

Publisher Resources

ISBN: 9781492056348Errata PageSupplemental Content