I'm trying to set correct typehint for default type in this situation
from typing import TypeVar
class Foo:
pass
class FooBar(Foo):
pass
T = ...
def baz(type_: type[T] = Foo) -> T:
return type_()
Already tried to use
T = TypeVar("T", bound=Foo)
But mypy said:
Incompatible default for argument "type_" (default has type "type[Foo]", argument has type "type[T]") [assignment]
def baz(type_: type[T] = Foo) -> T:
^~~
Just not to leave this question unanswered: to make
mypyhappy with typevar-typed argument with default value, you needoverloaded definition due to this open issue.Implementation signature is used only for body typechecking in such case, so it can use the upper bound of type variable everywhere. External callers will see what you expect them to see
Here's a playground link with this implementation.