为Python函数指定类型注解,返回参数的类型。

问题描述 投票:0回答:1

如何正确地对下面的函数进行类型注释?

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

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

有没有一种方法可以对下面的函数进行类型注释???? 与涉及 价值cls 而不是仅仅 Any 还是省略返回类型注解?如果我必须改变类型注解的 cls 参数。

python dependent-type python-typing
1个回答
2
投票

使用混合的 CallableType 和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

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


谢谢你的纠正 @chepner

© www.soinside.com 2019 - 2024. All rights reserved.