Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

Zeroes are not serialized with bytes() in proto2 syntax with required field

未关闭
#676 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
38/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
api

调研方向

先使用生成的 MyMessage 和 MyEnum.FOOBAR 示例重现该问题,然后比较所需 proto2 枚举的 bytes()、to_json() 和 to_dict()。当二进制表示包含零值枚举且不需要 include_default_values=True 时,即表示完成。

由索引模型根据 Issue 内容生成。

描述

bug investigation needed
Summary

There should be an alternative bytes method that allows to serialize zeroes for proto2 syntax. Currently zeroes enums are skipped as they are "default" values which is incorrect because unless the field is optional, it must be present in encoded form.

Reproduction Steps
  1. Create a simple proto2 file:
message MyMessage {
    enum MyEnum {
        FOOBAR = 0;
        BAZ = 1;
    }
}
  1. Compile to python:
@dataclass
class MyMessage(betterproto.Message):
	# @required
	action: "MyEnum" = betterproto.enum_field(1)

class MyEnum(betterproto.Enum):
	FOOBAR = 0
	BAZ = 1
  1. Use the FOOBAR value (0):
print(
	MyMessage(
		action=MyEnum.FOOBAR,
	)
)

You can see the MyEnum.FOOBAR here. However when you try to serialize it, the encoder skips this value incorrectly thinking it's default and hence shouldn't be added:

print(
	MyMessage(
		action=MyEnum.FOOBAR,
	).to_json()
)
# or
print(
	MyMessage(
		action=MyEnum.FOOBAR,
	).to_dict()
)
# or
print(
	bytes(MyMessage(
		action=MyEnum.FOOBAR,
	))
)

This can only be "fixed" by passing include_default_values=True in to_json or to_dict:

print(
	MyMessage(
		action=MyEnum.FOOBAR,
	).to_json(include_default_values=True)
)

But I need binary representation of the MyMessage class

Expected Results

N/A

Actual Results

N/A

System Information

Latest beta version

Checklist
  • I have searched the issues for duplicates.
  • I have shown the entire traceback, if possible.
  • I have verified this issue occurs on the latest prelease of betterproto which can be installed using pip install -U --pre betterproto, if possible.
主要语言
Python
星标
1.8k
派生
235
PR 合并指标
30 天内没有已合并 PR

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

danielgtaylor/python-betterproto 的其他 Issue

查看 danielgtaylor/python-betterproto 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。