File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 2020
2121from 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+
2330import betterproto2 .validators as validators
2431from betterproto2 .message_pool import MessagePool
2532from 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.
You can’t perform that action at this time.
0 commit comments