Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用函数参数作为类型提示?_Python_Python 3.x_Pycharm_Type Hinting - Fatal编程技术网

Python 如何使用函数参数作为类型提示?

Python 如何使用函数参数作为类型提示?,python,python-3.x,pycharm,type-hinting,Python,Python 3.x,Pycharm,Type Hinting,我有一个check\u value函数,它需要参数value和value\u type,比较type(value)和value\u type,并根据结果返回值或引发异常。现在我想使用类型提示来注释参数和返回类型 def check_value(value: "value_type", value_type: type) -> "value_type": if type(value) is value_type: return value else:

我有一个
check\u value
函数,它需要参数
value
value\u type
,比较
type(value)
value\u type
,并根据结果返回值或引发
异常。现在我想使用类型提示来注释参数和返回类型

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\u type
的注释工作正常,但是
value\u type
作为类型提示(因为
value
/
的类型返回的值属于
value\u type
)会在Pycharm\u 2018.1.4中引起警告(见下图)

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


谢谢

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

T = typing.TypeName("T")

def check_value(value: T, value_type: type) -> T:
    ...
value\u type
参数应该绑定到
T
所表示的相同类型,这一事实不能用类型注释来表示

但是,如果您正在进行静态类型检查,那么这种函数应该是不必要的。如果您已经正确地注释了
value
的来源和将使用它的位置,静态类型检查器应该已经知道它是否属于适当的类型,而不需要在运行时有一个函数来检查它。在您的示例中,它实际上不起作用,因为
print
接受
任何
参数,但是对于特别需要
int
s或
str
s的函数,您应该只传入值,让类型检查器发现问题:

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\u value(value:T,value\u type:type[T])->T: