How do I annotate types in a for-loop

前端 未结 4 1268
醉话见心
醉话见心 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.

    0 讨论(0)
  • 2020-12-24 11:56

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 12:02

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

    for i in range(5):
        i: int = i
        pass
    
    0 讨论(0)
提交回复
热议问题