For example:
How to set the argument type to: list, which contains ints and floats, or tuple, which contains ints and floats?
tried:
from typing import List, Tuple, Union
def some(arg: Union[List, Tuple][int, float]): ...
Raises
TypeError: typing.Union[typing.List, typing.Tuple] is not a generic class
The general question is for any iterables’ types’ combinations and any content types.
5
Since your function accepts a tuple, I assume you don’t need to modify arg
. Therefore, I will skip possible solutions with MutableSequence
.
Python 3.10+
Use collections.abc.Iterable
or collections.abc.Sequence
:
from collections.abc import Iterable, Sequence
def some_iterable(arg: Iterable[int | float]):
...
def some_sequence(arg: Sequence[int | float]):
...
Python 3.9
In Python 3.9, you have to use typing.Union
:
from collections.abc import Iterable, Sequence
from typing import Union
def some_iterable(arg: Iterable[Union[int, float]]):
...
def some_sequence(arg: Sequence[Union[int, float]]):
...
before Python 3.9
Use typing.Iterable
or typing.Sequence
in combination with typing.Union
:
from typing import Iterable, Sequence, Union
def some_iterable(arg: Iterable[Union[int, float]]):
...
def some_sequence(arg: Sequence[Union[int, float]]):
...
Iterable
vs Sequence
If you are unsure wether to use Iterable
or Sequence
, consider which operations you need to do with arg
. I highly recommend this overview to see which abstract base class supports which operations.
For example, if you need to do arg[0]
, use Sequence
. This means arg
can also be a bytes
or even a range
object.
If you don’t need to index arg
, but you need len(arg)
, use Collection
. Here, arg
can also be a set
.
If you just need to loop over arg
, use Iterable
. Now you can also pass generator expressions or other iterators as returned by map
or itertools
functions.