Baptiste Fontaine’s Blog  (back to the website)

Typing Tuples in Python

Python added support for type hints in 3.5. These are not typing as you may be used to in other languages since they have no effect on the compilation to bytecode nor at runtime, but rather hints for the (tools of the) developer.

def print_int(n: int):


The code above doesn’t fail when you call print_int("foo") even though n is “typed” as an int. This is because this n: int is just a hint.

While you can check for type issues by running mypy by hand, type hints become really powerful when your editor/IDE supports them.

Types for collections can specify the inner types: a list (List) that contains strings (str) would be List[str].

from typing import List

stuff: list = []  # a list of anything (equivalent to List[Any])

offsets: List[int] = []  # a list of ints

In the snippet above, the last line is highlighted as an error in any good IDE, and mypy would complain about it.

Other container types exist as well, and they can be nested:

from typing import List, Dict, Iterable

# a dictionary where keys are str and values are List[str], i.e. lists of strings
friends: Dict[str, List[str]] = {}
friends["Alice"] = ["Sam", "Maria"]

# a function that takes an iterable of ints. It can be a list, a tuple, a generator, a set, etc
def average(s: Iterable[int]):
    total = 0
    count = 0
    for element in s:
        total += element
        count += 1

    return total / count

Given List[x], Collection[x], Sequence[x] and other Set[x], one would expect Tuple[x] to be a hint for a tuple that contains x. Well… no.

This is confusing at first, but Tuple[str] types a tuple of a single element of type str. To add more elements, you need to type them as well: a pair of ints would be Tuple[int, int], while a triplet of a string, a float and a boolean would be Tuple[str, int, bool].

While tuples can be used as sequences (e.g. for immutable/hashable equivalents to lists), I’d argue that their primary use is for fixed-length representations, such as pairs of results:

def match_object(data: bytes):
    # example code
    distances = [0.99, 0.97, 0.96]
    indices = [432, 12, 3923]
    return distances, indices

In this snippet, match_object returns a tuple of a list of floats and a list of integers (aka Tuple[List[float], List[int]]).

If you still want to type arbitrary-length homogeneous tuples, there’s a syntax for that: Tuple[int, ...] types a tuple of any length, including 0, that contains only int elements (and yes, ... is valid in Python).

For this and other interrogations (how to type a generator?), Mypy has a useful type hints cheat sheet.

TL;DR: if you know the size of the tuple, use Tuple[x], Tuple[x, x], Tuple[x, x, x], etc. If you don’t, use Tuple[x, ...], but all elements must be of type x.