pythonpython-typingunion-typespyright

Type annotations: tuple type vs union type


def func(df_a: pd.DataFrame, df_b: pd.DataFrame) -> (pd.DataFrame, pd.DataFrame):

Pylance is advising to modify this line with two solution proposed. What would be the pros and cons of each one if there is any significant difference?

Tuple expression not allowed in type annotation

Use Tuple[T1, ..., Tn] to indicate a tuple type or Union[T1, T2] to indicate a union type


Solution

  • 2023 edit

    In newer versions of Python (>=3.10), you should use:

    The answer itself is still relevant, even if the newer style makes the difference between Tuple/tuple and Union/| more apparent.

    Original answer

    They mean different things:

    def f() -> Tuple[str, int, float]:
        return 'hello', 10, 3.33
    
    import random 
    
    def f() -> Union[str, int]:
        if random.random() > 0.5:
            return 'hello'
        else:
            return 10
    

    In your case, it looks like you want to use Tuple[pd.DataFrame, pd.DataFrame].