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¶
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 typetyping.Union: one of multiple typesParameterized as
Union[Type1, Type2, etc.]`
typing.Optional: either the specified type orNoneOptional[X]is equivalent toUnion[X, None]
typing.Literal: value will be one of provided valuesLiteral[1, 2, "hello"]means the value will either be1,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 asList[ItemType]typing.Set, parameterized asSet[ItemType]typing.FrozenSet, parameterized asFrozenSet[ItemType]typing.Dict, parameterized asDict[KeyType, ValueType]typing.Tuple, parameterized asTuple[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 theItemType.To specify an empty tuple, use
Tuple[()]
typing.Collection, parameterized asCollection[ItemType]Supports
len()
typing.Container, parameterized asContainer[ItemType]Supports containment checks with
inandnot in
typing.Iterable, parameterized asIterable[ItemType]Supports iteration with a
forloop
typing.Sequence, parameterized asSequence[ItemType]Supports subscripting with integers and
reversed()