【Python✨】VS Code 秒开 Python 类型检查:一招 mypy + settings.json 让你的 Bug 原地现形!

不需要跑程序,就能发现类型对不上。

核心工具:mypy(官方推荐,pip 就能装)


1. 安装 & 一条命令

bash 复制代码
pip install -U mypy          # 装
mypy demo.py                 # 查

绿色提示 = 没毛病
有红色提示 = 改完再上线


2. 举个最小例子

代码 (文件 demo.py

python 复制代码
def add(a: int, b: int) -> int:
    return a + b

add("3", 4)        # 故意传字符串

运行 mypy

bash 复制代码
$ mypy demo.py
demo.py:4: error: Argument 1 to "add" has incompatible type "str"; expected "int"

还没执行 Python 就告诉你第 4 行传错了类型,提前止损


3. VS Code 打开 Python 类型检查

(1)打开设置

(2)打开setting.json 文件

搜索setting --> 点击setting.json

(3)在setting.json加入

bash 复制代码
{
    "python.analysis.typeCheckingMode": "basic", // python类型检查模式设为基本

}

CTRL + S保存后,就会生效,如果没有生效就把VS Code 关闭重新打开;demo.py 可以在文件保存后就可以直接类型检查,无需运行即可爆红

相关推荐
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama