VS代码中的Python类型检查

Ale*_*ned 15 python visual-studio-code

我最近学习了如何在Python中键入模块(https://docs.python.org/3/library/typing.html),并期望将其用于静态类型检查以及在VS Code中更好的智能感知,就像它可以使用TypeScript,但我似乎无法找到任何实际上这样做的工具/插件.

我有什么选择,如果有的话?

小智 16

来自bash

mkdir test
cd test
python3 -m venv .env
source .env/bin/activate
python -m pip install flake8
python -m pip install flake8-mypy
code ./
Run Code Online (Sandbox Code Playgroud)

安装插件

然后在VSCode中安装它 https://marketplace.visualstudio.com/items?itemName=donjayamanne.python
并配置

设置

./.vscode/settings.json

{
    "python.envFile": "${workspaceRoot}/.env",
    "python.pythonPath": "${workspaceRoot}/.env/bin/python",
    "python.linting.flake8Enabled": true,
    "python.linting.pylintEnabled": false
}
Run Code Online (Sandbox Code Playgroud)

./.vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "pythonPath": "${config:python.pythonPath}",
            "program": "${file}",
            "cwd": "${workspaceRoot}",
            "env": {},
            "envFile": "${workspaceRoot}/.env",
            "debugOptions": [
                "WaitOnAbnormalExit",
                "WaitOnNormalExit",
                "RedirectOutput"
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

OMG,这只是Python 3!

https://pypi.python.org/pypi/flake8-mypy/17.3.3

是的,mypy也是.放松一下,
即使你想分析
Python 2代码,你也可以在Python 3.5+下使用所有流行的插件运行Flake8 作为一个完美的工具.通过这种方式,您将能够解析
Python 3上支持的所有新语法,同时还能够有效地解析所有Python 2语法
.

通过使代码专用于Python 3.5+,我能够专注于
检查的质量并重新使用新
版本的所有优秀功能(检查pathlib),而不是浪费Unicode
兼容性等周期.

IDE和Linter集成

https://github.com/python/mypy#ide--linter-integrations

IDE和Linter集成

Mypy可以集成到流行的IDE中:

  • Vim:vim-mypy
  • Emacs:使用Flycheck和Flycheck-mypy
  • Sublime Text:SublimeLinter-contrib-mypy
  • 原子:linter-mypy
  • PyCharm:PyCharm集成了自己的PEP 484实现.

Mypy也可以使用flake8-mypy集成到Flake8中.