如何在 for 循环中注释类型 [英] How do I annotate types in a for-loop

查看:29
本文介绍了如何在 for 循环中注释类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 for 循环中注释变量的类型.我试过这个:

I want to annotate a type of a variable in a for-loop. I tried this:

for i: int in range(5):
    pass

但显然没有用.

我期望在 PyCharm 2016.3.2 中自动完成.像这样的预注释:

What I expect is working autocomplete in PyCharm 2016.3.2. Pre-annotation like this:

i: int
for i in range(5):
    pass

没有帮助.

附言PyCharm 的预注释 >= 2017.1

P.S. Pre-annotation works for PyCharm >= 2017.1

推荐答案

根据 PEP 526,这是不允许的:

According to PEP 526, this is not allowed:

此外,不能注释forwith中使用的变量声明;它们可以以类似的方式提前注释元组解包

In addition, one cannot annotate variables used in a for or with statement; they can be annotated ahead of time, in a similar manner to tuple unpacking

在循环之前注释:

i: int
for i in range(5):
    pass

<小时>

PyCharm 2018.1 及更高版本 现在可以识别循环内变量的类型.较旧的 PyCharm 版本不支持此功能.


PyCharm 2018.1 and up now recognizes the type of the variable inside the loop. This was not supported in older PyCharm versions.

这篇关于如何在 for 循环中注释类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆