Skip to content

Commit 2ef0360

Browse files
committed
Validate the message before exporting it
1 parent 01feb5f commit 2ef0360

1 file changed

Lines changed: 9 additions & 2 deletions

File tree

src/betterproto2/__init__.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -710,11 +710,12 @@ def _is_pydantic(self) -> bool:
710710
"""
711711
return pydantic is not None and pydantic.dataclasses.is_pydantic_dataclass(type(self))
712712

713-
def validate(self) -> None:
713+
def _validate(self) -> None:
714714
"""
715715
Manually validate the message using pydantic.
716716
717-
This is useful since pydantic does not revalidate the message when fields are changed.
717+
This is useful since pydantic does not revalidate the message when fields are changed. This function doesn't
718+
validate the fields recursively.
718719
"""
719720
if not self._is_pydantic():
720721
raise TypeError("Validation is only available for pydantic dataclasses.")
@@ -746,6 +747,9 @@ def __bytes__(self) -> bytes:
746747
"""
747748
Get the binary encoded Protobuf representation of this message instance.
748749
"""
750+
if self._is_pydantic():
751+
self._validate()
752+
749753
with BytesIO() as stream:
750754
for field_name, meta in self._betterproto.meta_by_field_name.items():
751755
value = getattr(self, field_name)
@@ -1043,6 +1047,9 @@ def to_dict(
10431047
Dict[:class:`str`, Any]
10441048
The JSON serializable dict representation of this object.
10451049
"""
1050+
if self._is_pydantic():
1051+
self._validate()
1052+
10461053
kwargs = { # For recursive calls
10471054
"output_format": output_format,
10481055
"casing": casing,

0 commit comments

Comments
 (0)