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.
Python無法爲您做到這一點;你可以使用mypy
得到類型檢查(和PyCharms內置檢查器也應該這樣做)。除此之外,mypy
也不限制你只輸入評論# type List[str]
,因爲你在Python 3.6這麼做a: List[str]
作品同樣可以使用變量註解。
隨着mypy
的是,因爲釋放是新鮮的,你需要安裝typed_ast
與--fast-parser
和--python-version 3.6
as documented in mypy's docs執行mypy
。這可能會改變很快,但現在你需要他們得到它順利運行
更新:現在不需要--fast-parser
和--python-version 3.6
。
這樣做後,mypy檢測到a: List[str]
上的第二個操作的不兼容性就好了。比方說,你的文件被稱爲tp_check.py
with語句:
from typing import List
a: List[str] = []
a.append('a')
a.append(1)
print(a)
運行mypy
與上述參數(你必須首先pip install -U typed_ast
):
python -m mypy --fast-parser --python-version 3.6 tp_check.py
捕獲錯誤:
tp_check.py:5: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
如前所述在許多其他的答案類型提示與Python,mypy
和PyCharm
s'類型檢查器是執行驗證的類型,不是Python本身。 Python目前不使用這些信息,它只是將其存儲爲元數據並在執行期間忽略它。
mypy已經支持Python 3.6變量註釋。 – user2357112
相關的,如果不是欺騙:[什麼是Python 3.5中的類型提示](http://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5/32558710#32558710)和[什麼是Python 3.6中的變量註釋?](http://stackoverflow.com/questions/39971929/what-are-variable-annotations-in-python-3-6?noredirect=1&lq=1) –
爲了保持簡短:類型註釋並不意味着類型強制。該語言仍然是動態輸入的。 – jsbueno