Skip to content

Commit d0b5cd2

Browse files
committed
feat: added ParseFromString method to message for compatibility with official protobuf method
1 parent 8c727d9 commit d0b5cd2

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/betterproto/__init__.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,6 +1022,29 @@ def FromString(cls: Type[T], data: bytes) -> T:
10221022
"""
10231023
return cls().parse(data)
10241024

1025+
# For compatibility with Google protobuf official implementation.
1026+
def ParseFromString(self, data: bytes) -> T:
1027+
"""
1028+
Parse the binary encoded Protobuf into this message instance. This
1029+
returns the instance itself and is therefore assignable and chainable.
1030+
1031+
.. note::
1032+
This is a method for compatibility with other libraries,
1033+
you should really use :meth:`parse`.
1034+
1035+
1036+
Parameters
1037+
-----------
1038+
data: :class:`bytes`
1039+
The data to parse the protobuf from.
1040+
1041+
Returns
1042+
--------
1043+
:class:`Message`
1044+
The initialized message.
1045+
"""
1046+
return self.parse(data)
1047+
10251048
def to_dict(
10261049
self, casing: Casing = Casing.CAMEL, include_default_values: bool = False
10271050
) -> Dict[str, Any]:

tests/test_features.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,3 +485,13 @@ def test_service_argument__expected_parameter():
485485
do_thing_request_parameter = sig.parameters["do_thing_request"]
486486
assert do_thing_request_parameter.default is Parameter.empty
487487
assert do_thing_request_parameter.annotation == "DoThingRequest"
488+
489+
490+
def test_message_parse_from_string():
491+
@dataclass
492+
class SimpleMessage(betterproto.Message):
493+
message: str = betterproto.string_field(1)
494+
495+
test_message = SimpleMessage(message="test message")
496+
497+
assert test_message == test_message.ParseFromString(bytes(test_message))

0 commit comments

Comments
 (0)