为返回参数类型的 Python 函数指定类型注释

pal*_*asb 6 python dependent-type python-typing

如何正确键入注释下面的函数?

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

# Example usage:
assert f(int) == 0
assert f(list) == []
assert f(tuple) == ()
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以???使用涉及的内容进行类型注释cls,而不仅仅是Any或省略返回类型注释?如果我必须更改参数的类型注释也可以cls

Car*_*ate 5

Callable使用orType和 a的混合TypeVar来指示返回类型与参数类型的对应关系:

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
Run Code Online (Sandbox Code Playgroud)

第一种选择接受任何可调用对象;不仅仅是创建对象的调用。


感谢您的更正@chepner