【问题标题】:type hinting pitches a fit about function arguments but not the return type类型提示适合函数参数,但不适合返回类型
【发布时间】:2017-05-26 23:17:47
【问题描述】:

我对 Python 还很陌生,很高兴发现 Python3 中的类型提示功能。我通读了PEP 484 并找到了this question on SO,其中提出问题的人想知道为什么没有检查函数的返回类型。受访者指出了 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

现在这似乎是轮子脱落的地方,因为看起来,至少在函数参数方面,正在检查。我的问题是为什么要检查参数而不是返回类型?

【问题讨论】:

  • 这不是类型检查,如果没有类型提示,您会收到此错误。 Python 是一种强类型语言。
  • 它不检查函数参数的类型,因为它允许您使用整数而不是字符串调用greeting2

标签: python python-3.5 type-hinting


【解决方案1】:

Python 在运行时不使用类型提示(不用于函数参数或返回类型)。与以下没有什么不同:

>>> 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

如上所述,类型提示不会在运行时检查,它们旨在供您的编辑器/工具在开发期间使用。

【讨论】:

  • 啊啊啊啊。好的,这更有意义。我应该更加注意错误的文本。 t/y 快速响应!
猜你喜欢
  • 2016-08-23
  • 2022-01-16
  • 2014-07-16
  • 1970-01-01
  • 2020-10-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多