Type Hints Reference

This page serves as a reference to various type hints you might see during the course.

This is a living list that will expand over the course of the semester.

Basic Types

Type Hint

Description

int

An integer

float

A floating-point (real) number

str

A string

bool

A Boolean (True or False)

None

None (useful on return types)

Advanced Types

These type hints all come from the typing package and can be imported with:

from typing import ...

Warning

Type hinting in later versions of Python has changed to support easier syntax and to separate many of the type hints provided by typing to more relevant packages like collections.abc.

Special Typing Primitives and Forms

  • typing.Any: compatible with every type

  • typing.Union: one of multiple types

    • Parameterized as Union[Type1, Type2, etc.]`

  • typing.Optional: either the specified type or None

    • Optional[X] is equivalent to Union[X, None]

  • typing.Literal: value will be one of provided values

    • Literal[1, 2, "hello"] means the value will either be 1, 2, or "hello". This is most useful on function parameters or outputs.

    • I don’t know if we’ll use this in this class

Collections Type Hints

Note

Technically, tuple, list, set, frozenset, and dict can all be parameterized directly instead of having to use their typing counterpart shown below.

  • typing.List, parameterized as List[ItemType]

  • typing.Set, parameterized as Set[ItemType]

  • typing.FrozenSet, parameterized as FrozenSet[ItemType]

  • typing.Dict, parameterized as Dict[KeyType, ValueType]

  • typing.Tuple, parameterized as Tuple[Item1Type, Item2Type, etc.]

    • Because a tuple has a fixed size, you need to explicitly state the types of each item.

    • To specify an unknown-length tuple of homogeneous type, you can do Tuple[ItemType, ...] with the ellipses after the ItemType.

    • To specify an empty tuple, use Tuple[()]

  • typing.Collection, parameterized as Collection[ItemType]

  • typing.Container, parameterized as Container[ItemType]

    • Supports containment checks with in and not in

  • typing.Iterable, parameterized as Iterable[ItemType]

    • Supports iteration with a for loop

  • typing.Sequence, parameterized as Sequence[ItemType]

    • Supports subscripting with integers and reversed()