Type hint to return an instance of a class, where typevar is the class type

Viewed 210

How to write the return type hints to indicate that the function returns an instance of class "Class_" ?

Class_ = TypeVar("Class_", bound=type)

def make_class(class_: Class_) -> Class_:
    return class_()
1 Answers

What you want is to use Type from typing. This is the generic implementation of what you are trying to define with TypeVar("Class_", bound=type).

So all you need to do is provide a generic variable to represent an instance of the class returned, and then you can use the generic Type to specify the input argument.

from typing import Type, TypeVar


T = TypeVar("T")


def make_class(class_: Type[T]) -> T:
    return class_()
Related