Specify type annotation for Python function returning type of argument

Viewed 1525

How do I correctly type-annotate the function below?

def f(cls: type) -> ???:
    return cls()

# Example usage:
assert f(int) == 0
assert f(list) == []
assert f(tuple) == ()

Is there a way to type-annotate ??? with something that involves the value of cls instead of just Any or to omit the return type annotation? It is OK if I have to change the type annotation of the cls parameter.

1 Answers

Using a mix of Callable or Type and a TypeVar to indicate how the return type corresponds to the parameter type:

from typing import Callable, TypeVar, Type

T = TypeVar("T")


# Alternative 1, supporting any Callable object
def f(cls: Callable[[], T]) -> T:
    return cls()

ret_f = f(int)
print(ret_f)  # It knows ret_f is an int


# Alternative 2, supporting only types
def g(cls: Type[T]) -> T:
    return cls()

ret_g = f(int)
print(ret_g)  # It knows ret_g is an int

The 1st alternative accepts any callable object; not just calls that create objects.


Thanks for the corrections @chepner

Related