I would like the param to be a class type and return an instance of that class, how do I use TypeVar so that there are Type Hints like this

# Like this, but it doesn't work. :(
def foo(param:Type[T])->T:...

class ABaseClass:...

# if T is ABaseClass
def foo(param:Type[ABaseClass]) -> ABaseClass:...

# I've tried this too and it still doesn't work
def foo(param:T)->T.__args__[0]:...

Your example should work: mypy Playground

1 Like

Indeed, your first signature should work. I use that pattern a lot! Usually with some base class as a bound on the type var, but it works without. The trick is you need to pass the type as an argument at runtime:

class SomeBaseType:
    …

T = TypeVar(“T”, bound=SomeBaseType)
def fn(cls: Type[T], example_arg: …) -> T:
    # do stuff
    # can use the type argument as a constructor
    return cls(example_arg)

class SomeClass(SomeBaseType):
    …

x = fn(SomeClass, …)
# x has inferred type SomeClass
1 Like