我刚刚在PEP 484篇文章中看到了以下例子:

def greeting(name: str) -> str:
    return 'Hello ' + name

print(greeting('Martin'))
print(greeting(1))

正如所料,这在Python 2中不起作用:

  File "test.py", line 1
    def greeting(name: str) -> str:
                     ^
SyntaxError: invalid syntax

但是,它适用于Python 3:

Hello Martin
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print(greeting(1))
  File "test.py", line 2, in greeting
    return 'Hello ' + name
TypeError: Can't convert 'int' object to str implicitly

这是出乎意料的.它还没有真正判断类型,正如下面的示例所示(它运行,但不会引发异常):

def greeting(name: str) -> int:
    return 'Hello ' + name

print(greeting('Martin'))

似乎:后面必须是函数名,但函数似乎被忽略了:

def aha(something):
    print("aha")
    return something+"!"

def greeting(name: aha, foo) -> int:
    return 'Hello ' + name + foo

print(greeting('Martin', 'ad'))

->岁之后的名字似乎也是如此.

这种类型是否暗示语法使用了其他东西(比如Java建模语言使用注释)?这种语法是什么时候引入Python的?有没有办法用这种语法进行静态类型判断?它总是 destruct Python 2的兼容性吗?

推荐答案

这里没有类型暗示.你所做的只是提供annotations;它们是在PEP 3107中引入的(仅在Python3中,在Python2中不支持);它们允许您使用任意信息注释参数和返回值,以供以后判断:

>>> greeting.__annotations__
{'name': <class 'str'>, 'return': <class 'str'>}

除此之外,这里根本不咨询他们.相反,您收到的错误消息来自try 将字符串和整数值in the body of the function串联在一起:

>>> 'Hello ' + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

这是一个自定义类型错误,旨在提供有关str+int串联失败原因的附加信息;对于不是str的任何类型,str.__add__方法都会抛出它:

>>> ''.__add__(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> ''.__add__(True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'bool' object to str implicitly

然后,PEP 484建议利用这些注释对additional tools进行实际的静态类型判断,但正如PEP的介绍所述:

而这些注释在运行时可以通过通常的__annotations__属性no type checking happens at runtime获得.相反,该提案假设存在一个单独的离线类型判断器,用户可以自动运行其源代码.本质上,这样的类型判断器充当一个非常强大的过梁.

原文的重点.

PEP的灵感来源于使用PEP 3107注释的现有工具;特别是mypy project(它通过采用PEP 484循环),还有type hinting support in the PyCharm IDEpytypedecl project.参见Guido van Rossum的original email kickstarting this effortfollow-up email.

mypy显然通过预处理注释来支持Python2,在为您编译源代码之前删除注释,但在其他方面,您通常无法使用Python2的语法Python代码.

PEP 484还描述了stub files的使用,它位于常规Python文件旁边;这些文件使用.pyi扩展名,只包含签名(带有类型提示),而主.py文件注释是免费的,因此可以在Python 2上使用(前提是您编写了Polyglot Python代码).

Python-3.x相关问答推荐

使用Polars阅读按日期键分区的最新S3镶木地板文件

Gekko优化超出了方程式的界限(由于某种原因,会产生变量)

Numpy argmin()以查找最近的元组

我无法直接在 VSCode 中运行该程序,但可以使用 VScode 中的终端运行它

公开数据中的卫星图像网页抓取优化

如何转置和 Pandas DataFrame 并命名新列?

合并问卷中多列中的稀疏问题 - Pandas

如何将虚拟变量列转换为多列?

Pandas数据单调行为

pip install mysqlclient 失败为 mysqlclient 运行 setup.py bdist_wheel ... 错误

你如何表达一个没有参数的 Python Callable?

为什么 List 不能包含多种类型?

为 python3 安装 opencv

Python过滤器函数 - 单个结果

使用逗号时,除了处理程序中的语法无效

创建日志(log)文件

如何在 Python3 中添加带有标志的命令行参数?

用于 unicode 大写单词的 Python 正则表达式

哪个更有效:Python 文档字符串还是类型提示?

print(... sep='', '\t' ) 是什么意思?