diff --git a/src/betterproto/__init__.py b/src/betterproto/__init__.py index d5465791b..64f933827 100644 --- a/src/betterproto/__init__.py +++ b/src/betterproto/__init__.py @@ -1022,6 +1022,29 @@ def FromString(cls: Type[T], data: bytes) -> T: """ return cls().parse(data) + # For compatibility with Google protobuf official implementation. + def ParseFromString(self, data: bytes) -> T: + """ + Parse the binary encoded Protobuf into this message instance. This + returns the instance itself and is therefore assignable and chainable. + + .. note:: + This is a method for compatibility with other libraries, + you should really use :meth:`parse`. + + + Parameters + ----------- + data: :class:`bytes` + The data to parse the protobuf from. + + Returns + -------- + :class:`Message` + The initialized message. + """ + return self.parse(data) + def to_dict( self, casing: Casing = Casing.CAMEL, include_default_values: bool = False ) -> Dict[str, Any]: diff --git a/tests/test_features.py b/tests/test_features.py index 787520dee..011f24ded 100644 --- a/tests/test_features.py +++ b/tests/test_features.py @@ -485,3 +485,12 @@ def test_service_argument__expected_parameter(): do_thing_request_parameter = sig.parameters["do_thing_request"] assert do_thing_request_parameter.default is Parameter.empty assert do_thing_request_parameter.annotation == "DoThingRequest" + + +def test_message_parse_from_string(): + @dataclass + class SimpleMessage(betterproto.Message): + message: str = betterproto.string_field(1) + + test_message = SimpleMessage(message="test message") + assert test_message == SimpleMessage().ParseFromString(bytes(test_message))