python 语法提示_Python类型提示语法如何/为什么工作?

这里没有类型的提示.你所做的只是提供注释;这些引入了

PEP 3107(仅在Python 3中,在Python 2中没有对此支持);它们允许您注释参数并返回带有任意信息的值以供以后检查:

>>> greeting.__annotations__

{'name': , 'return': }

否则,它们在这里不会被咨询.相反,您收到的错误消息是尝试在函数正文中连接字符串和整数值:

>>> 'Hello ' + 1

Traceback (most recent call last):

File "", line 1, in

TypeError: Can't convert 'int' object to str implicitly

这是一个自定义类型错误,旨在提供关于为什么str int连接失败的其他信息;对于不是str的任何类型,它被str .__ add__方法抛出:

>>> ''.__add__(1)

Traceback (most recent call last):

File "", line 1, in

TypeError: Can't convert 'int' object to str implicitly

>>> ''.__add__(True)

Traceback (most recent call last):

File "", line 1, in

TypeError: Can't convert 'bool' object to str implicitly

然后,PEP 484提出利用这些注释来使用附加工具进行实际的静态类型检查,但是随着PEP的引入,

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter.

强调原来的.

mypy显然支持Python 2,通过预处理注释,在为您编译源代码之前删除它们,但是否则通常不能使用Python代码在Python 2中工作的语法.

PEP 484还描述了使用stub files,它坐在普通的Python文件旁边;这些使用.pyi扩展名,只包含签名(带有类型提示),留下主要的.py文件注释,因此可以在Python 2中使用(否则你写了Polyglot Python代码).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值