Narrowing a collection's type

Python 3 allows us to provide extensive type hints for describing the contents of a collection. This has two benefits:

  • It helps us visualize the data structure.
  • It supports running mypy to confirm that the code uses the data structures properly.

The non-collection types (int, str, float, complex, and so on) all use the type name as their type hint. The built-in collections all have parallel type definitions in the typing module. It's common to see from typing import List, Tuple, Dict, Set to import these type names into a module. 

Each of the type hints accepts parameters to further narrow the definition:

  • The List[T] hint claims the object will be a list and all the items will be of type T. For example [1, 1, 2, 3, 5, 8] can be described as List[int].
  • A Set[T] hint is similar to the List[T] hint. It claims all items in the set will be of type T. For example, {'a', 'r', 'd'} can be described as Set[str].
  • The Dict[K, V] hint claims the object will be a dict, the keys will all have a type K, and the values will all have a type V. For example, {'A': 4, 'B' 12} can be described as Dict[str, int].

The Tuple hint is often more complex. There are two common cases for tuples:

  • A hint such as Tuple[str, int, int, int] describes a four-tuple with a string and three integer values, for example, ('crimson', 220, 20, 60).  The size is specified explicitly.
  • A hint such as Tuple[int, ...] describes a tuple of indefinite size. The items will all be type int.  The size is not specified. The ... notation is a token in the Python language, and is a first-class part of the syntax for this type hint.

To describe objects where None values may be present in a collection, the Optional type is used. We might have a type hint such as List[Optional[int]] to describe a list that is a mixture of int and None objects, for example [1, 2, None, 42].

Because of the type coercion rules for numbers, we can often summarize numerical algorithms using a float type hint, such as the following:

def mean(data: List[float]) -> float: ...

This function will also work with a list of integer values. The mypy program recognizes the type coercion rules and will recognize mean([8, 9, 10]) as a valid use of this function.

In the next section, we'll define a new kind of sequence.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset