Python中如何在vim中读写文件并添加typing lints支持?

Python PEP 484PEP 526 加入了类型注释,然而现在网上 vim 的插件都没到位。

语法检查插件各种小 bug 不说,就是基本的 highlight 支持也没搜索到解决方案。

请问大家是怎么解决这个问题的?

换 IDE 什么的就不说了,编辑服务端文件为主,vim 是刚需。


另外 Guido 似乎花了不少精力在推 typing 这个事情,后面的 PEP 563 改进更加彻底。所以还是像遵循 PEP 8 去适应新的规则吧,免得几年后又得像 2to3 那样改代码。


Python中如何在vim中读写文件并添加typing lints支持?

4 回复

Kenneth 大神新的项目也全部上类型注释了。

https://github.com/kennethreitz/requests-html


要在Vim中读写Python文件并添加类型检查支持,可以这样配置:

首先安装必要的插件。在~/.vimrc中添加:

" 使用vim-plug管理插件
call plug#begin('~/.vim/plugged')
Plug 'dense-analysis/ale'          " 异步语法检查
Plug 'vim-scripts/python.vim'      " Python语法高亮
Plug 'tpope/vim-fugitive'          " Git集成(可选)
call plug#end()

" ALE配置
let g:ale_linters = {
\   'python': ['mypy', 'pylint'],
\}
let g:ale_fixers = {
\   'python': ['black', 'isort'],
\}
let g:ale_fix_on_save = 1
let g:ale_completion_enabled = 1

然后安装Python工具:

pip install mypy pylint black isort

现在打开Python文件时,ALE会自动检查类型注解。比如写个带类型提示的文件:

def read_file(path: str) -> str:
    with open(path, 'r') as f:
        return f.read()

def write_file(path: str, content: str) -> None:
    with open(path, 'w') as f:
        f.write(content)

# 使用示例
text = read_file("input.txt")
write_file("output.txt", text.upper())

保存文件时,ALE会自动运行mypy检查类型错误,并用black格式化代码。在Vim中可以用:ALEInfo查看检查详情,用:ALEFix手动修复。

总结:配好ALE加mypy就能在Vim里实时检查类型。

搜索 highlight,你说的是实时高亮搜索结果吗?这个 Vim 原生支持的啊,:set hlsearch


是说 typing annotation 的 highlight

没搜索到解决方案。。。
汗。。。

回到顶部