When a Generic class has a default value in an init parameter, MyPy complains about the possibility of a type mismatch even though the init parameter defines the type.
Consider the following minimal example
class IntOrStrReplicator(Generic[IntStrType]):
def __init__(self, a: IntStrType) -> None:
self.a = a
def produce(self) -> IntStrType:
return self.a
We expect the following
reveal_type(IntOrStrReplicator(4)) # IntOrStrReplicator[int]
reveal_type(IntOrStrReplicator("Hello")) # IntOrStrReplicator[str]
reveal_type(IntOrStrReplicator(4).produce()) # int
reveal_type(IntOrStrReplicator("Hello").produce()) # str
Sure enough, we get that if IntStrType
is either
TypeVar("IntStrType", bound=Union[int, str])
or
TypeVar("IntStrType", int, str)
Now, all I want to add is a default value of a
. For example def __init__(self, a: IntStrType = 4) -> None:
Clearly there's no problem with creating one of these classes with a=4. However the line then complains. If the TypeVar is given as a Union, it says:
Incompatible default for argument "a" (default has type "int", argument has type "T1")
and if the TypeVar is given as two different options it says
Incompatible default for argument "a" (default has type "int", argument has type "str")