Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36843

What type-hint contains both list and tuple?

I have a function that can accept as input any variable that can be indexed, such as a list or a tuple. How do I indicate this in the type-hint of the function?

Upvotes: 63

Views: 19543

Answers (2)

Peyman
Peyman

Reputation: 4209

Martijns answer is great, but if you want to specifically indicate that only list and tuple are allowed (and not any other sequence, like str) you'd better use list|tuple for Python 3.10 and later:

def foo(bar: list|tuple):
    ...

For older Pythons you have to use Union[list, tuple]:

from typing import Union

def foo(bar: Union[list, tuple]):
    ...

See the Union Type documentation for details.

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1124748

Your method is accepting a sequence, so use typing.Sequence. That's a generic, so you can specify what type of object(s) the sequence must contain:

from typing import Sequence

def foo(bar: Sequence[int]):
    # bar is a sequence of integers

Quoting the Python glossary:

An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and bytes.

Upvotes: 85

Related Questions