官方 Protobuf/Grpc 生成的的 Python 对象是不带类型信息的,IDE 下无法给出准确的类型提示,代码写起来很不方便。如果知道原始的 proto 文件,可以通过 mypy-protobuf 工具来生成独立的类型信息文件(pyi),再与对应的 py 文件放在一起,IDE 就可以正常显示类型信息了。

准备 mypy-protobuf 工具环境。

conda create -n mypy python=3.7
conda activate mypy
conda install protobuf
pip install mypy-protobuf
conda install -c conda-forge grpc-cpp

给 Protobuf 生成类型信息。

# 命令形式
protoc --plugin=protoc-gen-mypy=path/to/protoc_gen_mypy.bat --python_out=output/location --mypy_out=output/location example.proto

# 示例
protoc --plugin=protoc-gen-mypy=e:\ProgramData\Miniconda3\envs\mypy\Scripts\protoc-gen-mypy.exe --python_out=. --mypy_out=. model_config.proto

给 Grpc 生成类型信息。

# 命令形式
protoc --python_out=output/location --mypy_out=output/location --grpc_out=output/location --mypy_grpc_out=output/location example.proto

# 示例
protoc --plugin=protoc-gen-grpc=e:\ProgramData\Miniconda3\envs\mypy\Library\bin\grpc_python_plugin.exe --python_out=. --mypy_out=. --grpc_out=. --mypy_grpc_out=. grpc_service.proto

发表回复

您的电子邮箱地址不会被公开。