如何在for循环中注释类型

问题:如何在for循环中注释类型

我想在for-loop中注释变量的类型。我尝试了这个:

for i: int in range(5):
    pass

但这显然没有用。

我期望在PyCharm 2016.3.2中能够自动完成工作。像这样的预注释:

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

没有帮助。

适用于PyCharm> = 2017.1的PS预注释作品

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

for i: int in range(5):
    pass

But it didn’t work, obviously.

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

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

doesn’t help.

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


回答 0

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

另外,不能注释forwith 语句中使用的变量。可以像元组拆包一样提前注释它们

在循环之前对其进行注释:

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

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

According to PEP 526, this is not allowed:

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

Annotate it before the loop:

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

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


回答 1

我不知道此解决方案是否与PEP兼容,或者仅仅是PyCharm的功能,但我使它像这样工作

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

我正在使用Pycharm Community Edition 2016.2.1

I don’t know if this solution is PEP compatible or just a feature of PyCharm but I made it work like this

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

and I’m using Pycharm Community Edition 2016.2.1


回答 2

这对我在PyCharm(使用Python 3.6)中的效果很好

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

This works well for my in PyCharm (using Python 3.6)

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

回答 3

这里的回答都没有用,只是说不能。甚至接受的答案也使用PEP 526文档中的语法,这不是有效的python语法。如果您尝试输入

x: int

您会看到这是一个语法错误。

这是一个有用的解决方法:

for __x in range(5):
    x = __x  # type: int
    print(x)

做您的工作x。PyCharm可以识别其类型,并且可以自动完成。

None of the responses here were useful, except to say that you can’t. Even the accepted answer uses syntax from the PEP 526 document, which isn’t valid python syntax. If you try to type in

x: int

You’ll see it’s a syntax error.

Here is a useful workaround:

for __x in range(5):
    x = __x  # type: int
    print(x)

Do your work with x. PyCharm recognizes its type, and autocomplete works.