【问题标题】:How to use a function parameter as a type hint?如何使用函数参数作为类型提示?
【发布时间】:2018-11-30 00:28:28
【问题描述】:

我有一个check_value 函数,它需要参数valuevalue_type,将type(value)value_type 进行比较,并根据结果返回值或引发Exception。现在我想使用类型提示来注释参数和返回类型。

def check_value(value: "value_type", value_type: type) -> "value_type":
    if type(value) is value_type:
        return value
    else:
        raise Exception(f"Value '{value}' should be of type '{value_type}' instead of type '{type(value)}'.")


if __name__ == '__main__':
    print(check_value(2, int)) # works, returns
    print(check_value(2, str)) # works, raises Exception

参数value_type的注解工作正常,但是forward referencingvalue_type作为类型提示(因为value/the returned value的类型是value_type类型)会在Pycharm_2018中引起警告。 1.4(见下图)。

这是 Pycharm 中的错误吗?我做错什么了吗?不能这样使用类型提示吗?

谢谢!

【问题讨论】:

    标签: python python-3.x pycharm type-hinting


    【解决方案1】:

    我认为 Python 的静态类型检查系统无法支持您所展示的功能。那是因为value_type 的值根本不是静态的,而是在运行时确定的。我认为,你能做的最好的事情是这样的:

    T = typing.TypeName("T")
    
    def check_value(value: T, value_type: type) -> T:
        ...
    

    value_type 参数应该绑定到 T 所代表的同一类型这一事实不能用类型注释来表示。

    但是,如果您正在执行静态类型检查,则不需要这种功能。如果你已经正确地注释了value 的来源和使用的地方,静态类型检查器应该已经知道它是否是合适的类型,而不需要有一个函数在运行时检查它。它在您的示例中不会真正起作用,因为 print 接受 Any 参数,但是对于特别期望 ints 或 strs 的函数,您应该只传递值并让类型检查器发现问题:

    def source_of_ints() -> int:
        return 2
    
    def function_that_takes_an_int(value: int) -> None:
        print(value) # or whatever
    
    def function_that_takes_a_str(value: str) -> None:
        print(value) # or whatever
    
    if __name__ == '__main__':
        value = source_of_ints()           # value's type can be inferred by static type checker
        function_that_takes_an_int(value)  # works and passes type check too
        function_that_takes_a_str(value)   # works at runtime, but type checker will see an error
    

    【讨论】:

    • 函数签名可以注释如下:def check_value(value: T, value_type: Type[T]) -> T:
    猜你喜欢
    • 2022-01-16
    • 2018-08-27
    • 2023-04-06
    • 2015-09-04
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2021-12-01
    • 2018-10-10
    相关资源
    最近更新 更多