Python类型签入VS Cod

2024-05-21 18:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近在Python(https://docs.python.org/3/library/typing.html)中学习了输入模块,并期望将其用于静态类型检查和VS代码中更好的智能感知,就像它与TypeScript一起工作一样,但我似乎找不到任何真正做到这一点的工具/插件。

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


Tags: 模块工具代码httpsorgdocstyping类型
2条回答

我添加了以下代码

{
    "name": "mypy",
    "type": "python",
    "request": "launch",
    "module": "mypy",
    "args": [
        "${file}"
    ],
    "console": "integratedTerminal"
}

在VS Code launch.json中,现在它在“调试”窗口中可见。只要按F5键,就可以得到当前文件的完整静态分析。

从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 ./

安装插件

然后在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
}

./.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"
            ]
        }
    ]
}

天哪,这只是Python3!

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

Yes, so is mypy. Relax, you can run Flake8 with all popular plugins
as a tool perfectly fine under Python 3.5+ even if you want to analyze
Python 2 code. This way you’ll be able to parse all of the new syntax
supported on Python 3 but also effectively all the Python 2 syntax at
the same time.

By making the code exclusively Python 3.5+, I’m able to focus on the
quality of the checks and re-use all the nice features of the new
releases (check out pathlib) instead of wasting cycles on Unicode
compatibility, etc.

IDE和Linter集成

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

IDE & Linter Integrations

Mypy can be integrated into popular IDEs:

  • Vim: vim-mypy
  • Emacs: using Flycheck and Flycheck-mypy
  • Sublime Text: SublimeLinter-contrib-mypy
  • Atom: linter-mypy
  • PyCharm: PyCharm integrates its own implementation of PEP 484.

Mypy can also be integrated into Flake8 using flake8-mypy.

相关问题 更多 >