Search code examples
pythontuplespython-typingmypy

Type hint for Tuple, if the number of arguments can be 2 or 3


I would like to ask, how to write correctly type hints for *args variable in my situation.

I have this method:

def insert(self, *args) -> None:

*args is in format Union[Tuple[My_Class, str, ?], Iterable[Tuple[My_class, str, ?]]], where the third argument may be or doesn't have to be given. It's marked with a question sign.

I call this method with this statement:

form.insert(
            (first_field, "John", "Doe"),
            (date_field, "12251996"),
)

In summary *args can be Tuple, with 2 or 3 values inside, where the third argument is str, or is not given to this method
or it can be Iterable of Tuples, where the Tuple has the same values as in the previous case.

A tried these type hints, but it didn't give me what I need.

Union[Tuple[My_Class, str, Optional[str]], Iterable[Tuple[My_class, str, Optional[str]]]]
Union[Tuple[My_Class, str, ...], Iterable[Tuple[My_class, str, ...]]]
Union[Tuple[My_Class, str, Union[str, ...]], Iterable[Tuple[My_class, str, Union[str, ...]]]]

Does anyone have any idea, how to solve this, please?


Solution

  • Add both versions to your Union

    def insert(self, *args: Union[
        Tuple[X, str, str],
        Tuple[X, str],
        Iterable[Union[Tuple[X, str, str], Tuple[X, str]]]
    ]) -> None:
    

    Though the size of that type alias suggests the method's doing too much