如何正确键入以下函数的注释?
def f(cls: type) -> ???:
return cls()
# Example usage:
assert f(int) == 0
assert f(list) == []
assert f(tuple) == ()
有没有一种办法型注释???
的东西,涉及到价值的cls
,而不是仅仅Any
或省略返回类型的注释?如果必须更改cls
参数的类型注释,可以。
使用Callable
或Type
和的混合使用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
第一种选择接受任何可调用的对象;不只是创建对象的调用。
感谢您的更正@chepner
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句