IDE可以智能提示protobuf-python成员
我想要在Python中使用protobuf生成的类的智能提示功能。但是,生成的protobuf类的实现方式有点特别,代码看起来像这样:
class X(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _X
大多数Python的开发工具只能识别__metaclass__
和DESCRIPTOR
这两个成员,而不能识别在.proto文件中定义的其他成员。
那该怎么做呢?
1 个回答
6
如果你在使用较新的Python版本(3.7及以上),那么你可以试试我的这个项目:https://github.com/danielgtaylor/python-betterproto。这个项目可以生成带有正确类型的数据类,VSCode、PyCharm等工具可以利用这些类型来提供提示和智能补全功能。
比如,给定这样的输入:
syntax = "proto3";
// Some documentation about the Test message.
message Test {
// Some documentation about the count.
int32 count = 1;
}
你会得到这样的输出:
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: int32.proto
# plugin: python-betterproto
from dataclasses import dataclass
import betterproto
@dataclass
class Test(betterproto.Message):
"""Some documentation about the Test message."""
# Some documentation about the count.
count: int = betterproto.int32_field(1)
这个输出比官方生成的描述类要容易读得多。