'Type hint for list with fixed start and end types but variable length

I'm wondering if there is a way to type hint when I expect a list that I know will end with bool and start with a variable number of ints?

What I'm effectively trying to do is

def f(xs: List[int, ..., bool]):
    pass

where ... is some variable number of ints (zero or more).



Solution 1:[1]

If the number of ints is variable up to a certain limit, you can use the union of distinct Tuples as a workaround, as in:

from typing import Tuple, Union

TupleBoolLast = Union[
 Tuple[int, bool],
 Tuple[int, int, bool],
 Tuple[int, int, int, bool],
 Tuple[int, int, int, int, bool],
 Tuple[int, int, int, int, int, bool],
]

def f(xs: TupleBoolLast):
    pass

Alternatively you could have a type that shows that your lists are a combination of ints and bools, though that does not enforce order:

ListIntBool = list[Union[int, bool]]

def f(xs: ListIntBool):
    pass

Solution 2:[2]

I side with @dangom on this one. You could restructure how you are passing the arguments to your function, or use Union instead.

from typing import List, Sequence, Union


def more_correct(ints: Sequence[int], flag: bool) -> List[int]:
    ...

def less_correct(xs: Sequence[Union[int, bool]]) -> List[int]:
    ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dangom
Solution 2 matthewking