24

I am using mypy on my python 3.5 code, and I got a lot of messages which look like this:

file:line number: error: Need type annotation for variable

But I read about the new features in python 3.6 that it introduced the syntax for variable annotations only in python 3.6:

PEP 484 introduced the standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables...

And if I am trying to add variable type annotations to my variables in the python 3.5 program, It throws SyntaxError.

What should I do? Ignore this messages? Update to python 3.6? Why the mypy compiles my code like it's written in python 3.6?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67

4 Answers4

40

Use comments to annotate variable type

x = 5  # type: int
my_list = []  # type: List[str]

Check cheat sheet

https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html

jOOsko
  • 608
  • 6
  • 9
  • Exactly what I was looking for. One note, on Python 3.6, `flake8` says that 2 spaces are needed before an inline comment, so (for example) I had to change `x = 5 # type: int` (single space before `#`) to `x = 5 # type: int` (double space before `#`). – edesz Aug 08 '19 at 02:16
  • Pylance asks for the same – demberto Sep 26 '21 at 10:16
10

Your code is confusing the type inference that mypy tries to do. For example, redefining a name as in the following snippet, doesn't allow mypy to deduce the type of f:

f = []
f = {}

Since it can't understand what the type of f is supposed to be, it complains and tells you that it needs an annotation for the variable. You can explicitly provide a type-hint with:

  • A type comment for Python 3.5.
  • A variable annotation for Python 3.6

mypy isn't compiling in 3.6, this error exists in both versions. The difference is in how you can tackle it.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • 2
    @YuvalPruss If you plan on using variable annotations, take a look here https://stackoverflow.com/questions/39971929/what-are-variable-annotations-in-python-3-6/39973133#39973133 for a bit more on it. – Dimitris Fasarakis Hilliard Jun 18 '17 at 19:26
3

If you are having blank value, you must define the type of variable. For example:

my_val: str = ""
my_val1: dict = {}
my_val2: list = []

etc. In your case, I will consider changing the version of python to 3.6 and update code is required.

porto
  • 555
  • 4
  • 7
1

The mypy docs mention that empty collections often need to have type annotations for certain complex cases.

https://mypy.readthedocs.io/en/stable/common_issues.html#types-of-empty-collections

Medhat Gayed
  • 2,585
  • 20
  • 12