How do I annotate types in a for-loop

前端 未结 4 1352
醉话见心
醉话见心 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:47

    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.

提交回复
热议问题