How do I annotate types in a for-loop

前端 未结 4 1270
醉话见心
醉话见心 2020-12-24 11:05

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

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 11:58

    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.

提交回复
热议问题