How do I annotate types in a for-loop?

Question:

I want to annotate a type of a variable in a for-loop. I tried this but it didn’t work:

for i: int in range(5):
    pass

What I expect is working autocomplete in PyCharm 2016.3.2, but using
pre-annotation didn’t work:

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

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

Asked By: grepcake

||

Answers:

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.

Answered By: alecxe

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.

Answered By: Edward Ned Harvey

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

Answered By: David Vasquez

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

for i in range(5):
    i: int = i
    pass
Answered By: Samir

Although I prefer to use type hints when possible, using assert isinstance(...) could be an alternative solution/work-around to achieve the same benefits (that is: proper syntax highlighting and auto-completion in the IDE).
I don’t know if this works in PyCharm, but it does work in Visual Studio Code.

for x, y, z in range(5):
    assert isinstance(i, int)
    # Now VS Code knows the type of `i`, so syntax highlighting
    # and auto-completion do work as intended :-)

Obviously, adding the assert has an effect on the code, and this might be a Good Thing or a Bad Thing, depending on your use case.
It is definitely not the same as type-hinting, but as a side effect it seems to have the same benefits.

Answered By: wovano