Skip to content

Commit d8785b4

Browse files
Merge pull request #10 from qix/master
Fix serialization of dataclass constructor parameters
2 parents 45e7a30 + d7559c2 commit d8785b4

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

betterproto/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,9 @@ class Message(ABC):
430430
_group_map: Dict[str, dict]
431431

432432
def __post_init__(self) -> None:
433+
# Keep track of whether every field was default
434+
all_sentinel = True
435+
433436
# Set a default value for each field in the class after `__init__` has
434437
# already been run.
435438
group_map: Dict[str, dict] = {"fields": {}, "groups": {}}
@@ -446,6 +449,7 @@ def __post_init__(self) -> None:
446449

447450
if getattr(self, field.name) != PLACEHOLDER:
448451
# Skip anything not set to the sentinel value
452+
all_sentinel = False
449453

450454
if meta.group:
451455
# This was set, so make it the selected value of the one-of.
@@ -456,7 +460,7 @@ def __post_init__(self) -> None:
456460
setattr(self, field.name, self._get_field_default(field, meta))
457461

458462
# Now that all the defaults are set, reset it!
459-
self.__dict__["_serialized_on_wire"] = False
463+
self.__dict__["_serialized_on_wire"] = not all_sentinel
460464
self.__dict__["_unknown_fields"] = b""
461465
self.__dict__["_group_map"] = group_map
462466

betterproto/tests/test_features.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,21 @@ class Foo(betterproto.Message):
3333
assert betterproto.serialized_on_wire(foo.bar) == False
3434

3535

36+
def test_class_init():
37+
@dataclass
38+
class Bar(betterproto.Message):
39+
name: str = betterproto.string_field(1)
40+
41+
@dataclass
42+
class Foo(betterproto.Message):
43+
name: str = betterproto.string_field(1)
44+
child: Bar = betterproto.message_field(2)
45+
46+
foo = Foo(name="foo", child=Bar(name="bar"))
47+
48+
assert foo.to_dict() == {"name": "foo", "child": {"name": "bar"}}
49+
50+
3651
def test_enum_as_int_json():
3752
class TestEnum(betterproto.Enum):
3853
ZERO = 0

0 commit comments

Comments
 (0)