I noticed Python 3.5 and Python 3.6 added a lot of features about static type checking, so I tried with the following code (in python 3.6, stable version).
from typing import List
a: List[str] = []
a.append('a')
a.append(1)
print(a)
What surprised me was that, Python didn't give me an error or warning, although 1
was appended to a list
which should only contain strings. Pycharm
detected the type error and gave me a warning about it, but it was not obvious and it was not shown in the output console, I was afraid sometimes I might miss it. I would like the following effects:
- If it's obvious that I used the wrong type just as shown above, throw out a warning or error.
- If the compiler couldn't reliably check if the type I used was right or wrong, ignore it.
Is that possible? Maybe mypy
could do it, but I'd prefer to use Python-3.6-style type checking (like a: List[str]
) instead of the comment-style (like # type List[str]
) used in mypy
. And I'm curious if there's a switch in native python 3.6 to achieve the two points I said above.
There's no way Python will do this for you; you can use
mypy
to get type checking (and PyCharms built-in checker should do it too). In addition to that,mypy
also doesn't restrict you to only type comments# type List[str]
, you can use variable annotations as you do in Python 3.6 soa: List[str]
works equally well.With
mypy
as is, because the release is fresh, you'll need to installtyped_ast
and executemypy
with--fast-parser
and--python-version 3.6
as documented in mypy's docs. This will probably change soon but for now you'll need them to get it running smoothlyUpdate:
--fast-parser
and--python-version 3.6
aren't needed now.After you do that, mypy detects the incompatibility of the second operation on your
a: List[str]
just fine. Let's say your file is calledtp_check.py
with statements:Running
mypy
with the aforementioned arguments (you must firstpip install -U typed_ast
):catches the error:
As noted in many other answers on type hinting with Python,
mypy
andPyCharm
s' type-checkers are the ones performing the validation, not Python itself. Python doesn't use this information currently, it only stores it as metadata and ignores it during execution.