Skip to content

Commit

Permalink
feat: added ParseFromString method to message for compatibility with …
Browse files Browse the repository at this point in the history
…official protobuf method
  • Loading branch information
simon-saliba committed Feb 12, 2022
1 parent 8c727d9 commit cb9161b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

0 comments on commit cb9161b

Please sign in to comment.