danielgtaylor / danielgtaylor/python-betterproto
Implicit optional is not respected
- Dominant language
- Python
- Stars
- 1.8k
- Forks
- 234
- PR merge metrics
- No merged PRs in 30d
Description
### Summary
When you don't add an explicit `optional`, fields are not serialized properly if they happen to be set to the default value.
### Reproduction Steps
```
message Sample {
bool foo = 1
}
```
generates
```
[
{
"name": "foo",
"type": "BOOLEAN",
"mode": "NULLABLE",
}
]
```
but the python code generated is
```
@dataclass(eq=False, repr=False)
class Sample(betterproto.Message):
foo: bool = betterproto.string_field(1)
```
which implies that the boolean is non-nullable.
Then, if we do
```
bytes(Sample(foo=False))
```
it will be serialized to
```
b''
```
and actually treated as null.
If we change the proto to
```
message Sample {
optional bool foo = 1
}
```
then the correct code is generated and the message is serialized as expected.
### Actual Results
The protobuf documentation suggests that not setting `optional` should be treated in the same way as setting it.
### System Information
libprotoc 28.3
Python 3.10.11
betterproto 2.0.0b7
### Checklist
- [X] I have searched the issues for duplicates.
- [X] I have shown the entire traceback, if possible.
- [X] I have verified this issue occurs on the latest prelease of betterproto which can be installed using `pip install -U --pre betterproto`, if possible.
Contributor guide
Assessment
This issue has not been assessed yet.