How to use type hints in python 3.6?

前端 未结 3 1477
天涯浪人
天涯浪人 2020-11-27 17:03

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).

fr         


        
3条回答
  •  迷失自我
    2020-11-27 17:34

    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 so a: List[str] works equally well.

    With mypy as is, because the release is fresh, you'll need to install typed_ast and execute mypy 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 smoothly

    Update: --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 called tp_check.py with statements:

    from typing import List
    
    a: List[str] = []
    a.append('a')
    a.append(1)
    print(a)
    

    Running mypy with the aforementioned arguments (you must first pip install -U typed_ast):

    python -m mypy --fast-parser --python-version 3.6 tp_check.py
    

    catches the error:

    tp_check.py:5: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
    

    As noted in many other answers on type hinting with Python, mypy and PyCharms' 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.

提交回复
热议问题