类型提示适合函数参数而不是 return 类型
type hinting pitches a fit about function arguments but not the return type
我是 Python 的新手,很高兴发现 Python3 中的类型提示功能。我通读了 PEP 484 and found ,其中提出问题的人想知道为什么 return 类型的函数没有被检查。响应者指出了 PEP 484 中的一个部分,该部分声明检查不会在 运行 时间发生,其目的是类型提示将由外部程序解析。
我启动了 python3 REPL 并决定尝试一下
>>> def greeting() -> str: return 1
>>> greeting()
1
到目前为止一切顺利。我对函数参数很好奇,所以我尝试了这个:
>>> def greeting2(name: str) -> str: return 'hi ' + name
>>> greeting2(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in greeting2
TypeError: Can't convert 'int' object to str implicitly
现在这就是轮子似乎脱落的地方,因为看起来,至少在函数参数方面,有检查。我的问题是为什么要检查参数而不是 return 类型?
Python 在运行时不使用类型提示(不适用于函数参数或 return 类型)。与以下内容没有区别:
>>> def greeting3(name): return 'hi ' + name
...
>>> greeting3(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in greeting3
TypeError: Can't convert 'int' object to str implicitly
您收到 TypeError 是因为您试图连接一个字符串和一个整数:
>>> 'hi ' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
如前所述,类型提示不会在运行时检查,它们旨在供您的编辑器/工具在开发期间使用。
我是 Python 的新手,很高兴发现 Python3 中的类型提示功能。我通读了 PEP 484 and found
我启动了 python3 REPL 并决定尝试一下
>>> def greeting() -> str: return 1
>>> greeting()
1
到目前为止一切顺利。我对函数参数很好奇,所以我尝试了这个:
>>> def greeting2(name: str) -> str: return 'hi ' + name
>>> greeting2(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in greeting2
TypeError: Can't convert 'int' object to str implicitly
现在这就是轮子似乎脱落的地方,因为看起来,至少在函数参数方面,有检查。我的问题是为什么要检查参数而不是 return 类型?
Python 在运行时不使用类型提示(不适用于函数参数或 return 类型)。与以下内容没有区别:
>>> def greeting3(name): return 'hi ' + name
...
>>> greeting3(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in greeting3
TypeError: Can't convert 'int' object to str implicitly
您收到 TypeError 是因为您试图连接一个字符串和一个整数:
>>> 'hi ' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
如前所述,类型提示不会在运行时检查,它们旨在供您的编辑器/工具在开发期间使用。