Correct way to typehint an argument that only accepts list, set, or tuple

is Union[set[T], tuple[T, ...], list[T]] correct? If so, what would be the “correct” alias for such a type? Or is there already a type in stdlib that I should use instead?

T = TypeVar('T')

CollectionT = Union[set[T], tuple[T, ...], list[T]]

You can also make it an explicit alias:

CollectionT: TypeAlias = Union[set[T], tuple[T, ...], list[T]]

Or in Python 3.12+

type CollectionT = Union[set[T], tuple[T, ...], list[T]]

In all cases:

>>> coll[int]
typing.Union[set[int], tuple[int, ...], list[int]]
1 Like

Yes, that union will do what you describe. There is no such exact alias in the standard library, but you might want to explore whether Iterable is sufficient, or some of the other abstract types in collections.abc.

1 Like

Thank you!

Not quite, it should be

type Collection[T] = Union[set[T], tuple[T, ...], list[T]]

(with no definition of T = TypeVar('T'))

4 Likes