Skip to content

Implicit optional is not respected #645

Open
@hrist0stoichev

Description

@hrist0stoichev

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

  • 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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions