Type hinting Generic Class with Fallback types

Viewed 15

Consider the following example

from typing import Generic, Optional, TypeVar

T = TypeVar("T", int, tuple[int, ...])
S = TypeVar("S", int, tuple[int, ...])


class Foo(Generic[S, T]):
    fallback_int: S
    fallback_tuple: T

    def __init__(self, x: Optional[S] = None, y: Optional[T] = None):
        if x is None:
            # Incompatible types in assignment (expression has type "int", variable has type "Tuple[int, ...]")
            self.fallback_int = 0  
        else:
            self.fallback_int = x

        if y is None:
            # Incompatible types in assignment (expression has type "Tuple[]", variable has type "int")
            self.fallback_tuple = () 
        else:
            self.fallback_tuple = y

I understand why mypy raises the error, as in both code-paths, either then T is int or when T is tuple[int, ...], the type of Foo.x must be equal to T.

How can I properly type hint Foo to avoid this error?

0 Answers
Related