Writing list-related type hints
The typing
module provides a few essential type definitions for describing the contents of a list
object. The primary type definition is List
, which we can parameterize with the types of items in the list.
There are two common patterns to the types of items in lists in Python:
- Homogenous: Each item in the
list
has a common type or protocol. A common superclass is also a kind of homogeneity. A list of mixed integer and floating-point values can be described as a list of float values, because bothint
andfloat
support the same numeric protocols. - Heterogenous: The items in the
list
come from a union of a number of types with no commonality. This is less common, and requires more careful programming to support it. This will often involve theUnion
type definition from thetyping
module.
Getting ready
We'll look at a list that has two kinds of tuples. Some tuples are simple RGB colors. Other tuples are RGB...