Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 399
tscunami Avatar asked Nov 15 '25 16:11

tscunami


1 Answers

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

like image 123
joel Avatar answered Nov 17 '25 09:11

joel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!