Skip to content
This repository was archived by the owner on Jun 9, 2025. It is now read-only.

Commit 6c61ce9

Browse files
committed
Fix errors on empty any
1 parent 87da841 commit 6c61ce9

File tree

1 file changed

+12
-2
lines changed
  • src/betterproto2_compiler/known_types

1 file changed

+12
-2
lines changed

src/betterproto2_compiler/known_types/any.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,34 @@ def pack(self, message: betterproto2.Message, message_pool: "betterproto2.Messag
2020
self.type_url = message_pool.type_to_url[type(message)]
2121
self.value = bytes(message)
2222

23-
def unpack(self, message_pool: "betterproto2.MessagePool | None" = None) -> betterproto2.Message:
23+
def unpack(self, message_pool: "betterproto2.MessagePool | None" = None) -> betterproto2.Message | None:
2424
"""
2525
Return the message packed inside the `Any` object.
2626
2727
The target message type must be registered in the message pool, which is done automatically when the module
2828
defining the message type is imported.
2929
"""
30+
if not self.type_url:
31+
return None
32+
3033
message_pool = message_pool or default_message_pool
3134

32-
message_type = message_pool.url_to_type[self.type_url]
35+
try:
36+
message_type = message_pool.url_to_type[self.type_url]
37+
except KeyError:
38+
raise TypeError(f"Can't unpack unregistered type: {self.type_url}")
3339

3440
return message_type().parse(self.value)
3541

3642
def to_dict(self, **kwargs) -> dict[str, typing.Any]:
43+
# TODO allow passing a message pool to `to_dict`
3744
output: dict[str, typing.Any] = {"@type": self.type_url}
3845

3946
value = self.unpack()
4047

48+
if value is None:
49+
return output
50+
4151
if type(value).to_dict == betterproto2.Message.to_dict:
4252
output.update(value.to_dict(**kwargs))
4353
else:

0 commit comments

Comments
 (0)