TypeHinting tuples in Python

PythonType Hinting

Python Problem Overview


When I want to typehint a tuple in Python like:

def func(var: tuple[int, int]):
    # do something

func((1, 2))    # would be fine
func((1, 2, 3)) # would throw an error

It is required to give the exact number of items in the tuple. That's different from list typehinting:

def func(var: list[int]):
    # do something

func([1])       # would be fine
func([1, 2])    # would also be fine
func([1, 2, 3]) # would also be fine

That's consequentially, in a way, because of the type of tuples. Because they are designed not to be changed, you have to hardcode the amount of items in it.

So my question is, is there a way to make the number of items in a tuple type hint flexible? I tried something like that but it didn't work:

def func(var: tuple[*int]):

Python Solutions


Solution 1 - Python

Yes, you can make the number of items in a tuple type hint flexible:

from typing import Tuple

def func(var: Tuple[int, ...]):
    pass

From the docs: https://docs.python.org/3/library/typing.html#typing.Tuple

> To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

Solution 2 - Python

Starting with PEP 585 it is possible to use builtin typings without importing the typing module, so starting with Python 3.9, Tuple[...] has been deprecated in favor of tuple[...]. e.g.

def func(var: tuple[int, ...]):
    pass

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsaraView Question on Stackoverflow
Solution 1 - PythonaaronView Answer on Stackoverflow
Solution 2 - PythonJokeNeverSokeView Answer on Stackoverflow