为 Python 函数返回参数类型指定类型注释
Specify type annotation for Python function returning type of argument
如何正确地键入注释下面的函数?
def f(cls: type) -> ???:
return cls()
# Example usage:
assert f(int) == 0
assert f(list) == []
assert f(tuple) == ()
有没有一种方法可以使用涉及 cls
的 value 而不仅仅是 Any
的内容对 ???
进行类型注释,或者省略 return 类型注释?如果我必须更改 cls
参数的类型注释也没关系。
混合使用Callable
or Type
and a TypeVar
表示return类型如何对应参数类型:
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 的更正
如何正确地键入注释下面的函数?
def f(cls: type) -> ???:
return cls()
# Example usage:
assert f(int) == 0
assert f(list) == []
assert f(tuple) == ()
有没有一种方法可以使用涉及 cls
的 value 而不仅仅是 Any
的内容对 ???
进行类型注释,或者省略 return 类型注释?如果我必须更改 cls
参数的类型注释也没关系。
混合使用Callable
or Type
and a TypeVar
表示return类型如何对应参数类型:
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 的更正