Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I annotate types in a for-loop

People also ask

What are type annotations?

Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.

How do you write a for loop in Python?

Let's go over the syntax of the for loop: It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case). Then, the in keyword is followed by the name of the sequence that we want to iterate. The initializer section ends with “ : ”.

What does it mean to annotate a variable?

Variable Annotation is basically an enhancement of type hinting, which was introduced in Python 3.5. The full explanation behind Variable Annotation is explained in PEP 526. In this article, we give have a quick refresher on type hinting and then introduce the new Variable Annotation syntax.


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.


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


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

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