How to use tuple type hints in Python

Dec 12, 2023#python#tuples

A tuple in Python is a collection of ordered and unchangeable items in a single variable. Tuples are written with round brackets and can store any data type. Tuples are similar to lists, but they cannot be modified once created.

# Create a tuple
my_tuple = ("apple", "banana", "cherry")

# Access elements
print(my_tuple[0])  # Output: apple
print(my_tuple[1])  # Output: banana
print(my_tuple[-1])  # Output: cherry

# Looping through a tuple
for fruit in my_tuple:
    print(fruit)

# Tuple unpacking
a, b, c = my_tuple
print(a)  # Output: apple
print(b)  # Output: banana
print(c)  # Output: cherry

# Tuples are immutable
try:
    my_tuple[0] = "grapefruit"
except TypeError:
    print("Tuples are immutable")

While Python is dynamically typed, meaning you don’t have to explicitly declare the type of a variable, type hints are a form of static typing that can help catch certain types of errors early in development and provide documentation.

In Python, tuple type hints are optional but strongly recommended for improved code quality. Python 3.8 and earlier require importing Tuple from the typing module. Python 3.9+ allows using tuple directly without importing.

If you want to use type hints to check the types of your code before running it, you need to use a tool like Mypy, which is a static type checker for Python. Mypy can analyze your code and report any type errors or inconsistencies based on the type hints you provide. Mypy can also check the types of unannotated code by using type inference and default rules.

Using typing.Tuple class

The typing module in Python provides support for type hints. The Tuple class in the typing module is used to represent a fixed-size immutable sequence, which can be a tuple of multiple types.

from typing import Tuple

def get_coordinates() -> Tuple[float, float]:
    # This function returns a tuple of two floats
    return (1.5, 2.3)

def distance(p1: Tuple[float, float], p2: Tuple[float, float]) -> float:
    # This function takes two tuples of two floats and returns a float
    x1, y1 = p1
    x2, y2 = p2
    return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5

If you want to annotate a tuple type that can have any length, but all the elements must be of the same type, you can use an ellipsis (...) after the type, such as:

from typing import Tuple

def sum_numbers(numbers: Tuple[int, ...]) -> int:
    # This function takes a tuple of any length of ints and returns an int
    return sum(numbers)

Using built-in tuple type

Since Python 3.9, you can directly use the built-in tuple type to annotate tuples. This is a simpler and more concise way to specify the type of a tuple variable, compared to the older method of using the typing.Tuple class.

Unlike most other Python containers, however, it is common in idiomatic Python code for tuples to have elements which are not all of the same type. For this reason, tuples are special-cased in Python’s typing system. tuple accepts any number of type arguments.

my_tuple: tuple[int, str, float] = (42, "hello", 3.14)

def example_function() -> tuple[int, str]:
    return 42, "hello"

you can use the built-in tuple class with square brackets and an ellipsis to annotate tuple types that can have any length, but all the elements must be of the same type. For example, tuple[int, ...] means a tuple of integers of any length.

def print_tuple(t: tuple[str, ...]) -> None:
    # This function takes a tuple of any length of strings and prints them
    for item in t:
        print(item)