How do I annotate types in a for-loop?

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.

Leave a Comment