Skip to content

Commit 01feb5f

Browse files
committed
Pydantic validation method
1 parent b2ce674 commit 01feb5f

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/betterproto2/__init__.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@
2020

2121
from typing_extensions import Self
2222

23+
try:
24+
import pydantic
25+
import pydantic_core
26+
except ImportError:
27+
pydantic = None
28+
pydantic_core = None
29+
2330
import betterproto2.validators as validators
2431
from betterproto2.message_pool import MessagePool
2532
from betterproto2.utils import unwrap
@@ -697,6 +704,25 @@ def _betterproto(cls: type[Self]) -> ProtoClassMetadata: # type: ignore
697704
cls._betterproto_meta = ProtoClassMetadata(cls)
698705
return cls._betterproto_meta
699706

707+
def _is_pydantic(self) -> bool:
708+
"""
709+
Check if the message is a pydantic dataclass.
710+
"""
711+
return pydantic is not None and pydantic.dataclasses.is_pydantic_dataclass(type(self))
712+
713+
def validate(self) -> None:
714+
"""
715+
Manually validate the message using pydantic.
716+
717+
This is useful since pydantic does not revalidate the message when fields are changed.
718+
"""
719+
if not self._is_pydantic():
720+
raise TypeError("Validation is only available for pydantic dataclasses.")
721+
722+
dict = self.__dict__.copy()
723+
del dict["_unknown_fields"]
724+
pydantic_core.SchemaValidator(self.__pydantic_core_schema__).validate_python(dict)
725+
700726
def dump(self, stream: SupportsWrite[bytes], delimit: bool = False) -> None:
701727
"""
702728
Dumps the binary encoded Protobuf message to the stream.

0 commit comments

Comments
 (0)