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

Commit b87c132

Browse files
Improve to_dict for any (#47)
* Improve to_dict for any * Fix errors on empty any * Remove generated code to pass typechecking
1 parent 94a7999 commit b87c132

File tree

3 files changed

+26
-34
lines changed

3 files changed

+26
-34
lines changed

src/betterproto2_compiler/known_types/any.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import typing
2+
13
import betterproto2
24

35
from betterproto2_compiler.lib.google.protobuf import Any as VanillaAny
@@ -18,19 +20,37 @@ def pack(self, message: betterproto2.Message, message_pool: "betterproto2.Messag
1820
self.type_url = message_pool.type_to_url[type(message)]
1921
self.value = bytes(message)
2022

21-
def unpack(self, message_pool: "betterproto2.MessagePool | None" = None) -> betterproto2.Message:
23+
def unpack(self, message_pool: "betterproto2.MessagePool | None" = None) -> betterproto2.Message | None:
2224
"""
2325
Return the message packed inside the `Any` object.
2426
2527
The target message type must be registered in the message pool, which is done automatically when the module
2628
defining the message type is imported.
2729
"""
30+
if not self.type_url:
31+
return None
32+
2833
message_pool = message_pool or default_message_pool
2934

30-
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}")
3139

3240
return message_type().parse(self.value)
3341

34-
def to_dict(self) -> dict: # pyright: ignore [reportIncompatibleMethodOverride]
35-
# TOOO improve when dict is updated
36-
return {"@type": self.type_url, "value": self.unpack().to_dict()}
42+
def to_dict(self, **kwargs) -> dict[str, typing.Any]:
43+
# TODO allow passing a message pool to `to_dict`
44+
output: dict[str, typing.Any] = {"@type": self.type_url}
45+
46+
value = self.unpack()
47+
48+
if value is None:
49+
return output
50+
51+
if type(value).to_dict == betterproto2.Message.to_dict:
52+
output.update(value.to_dict(**kwargs))
53+
else:
54+
output["value"] = value.to_dict(**kwargs)
55+
56+
return output

src/betterproto2_compiler/lib/google/protobuf/__init__.py

Lines changed: 0 additions & 29 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/betterproto2_compiler/templates/header.py.j2

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import builtins
2222
import datetime
2323
import warnings
2424
from collections.abc import AsyncIterable, AsyncIterator, Iterable
25+
import typing
2526
from typing import TYPE_CHECKING
2627

2728
{% if output_file.settings.pydantic_dataclasses %}

0 commit comments

Comments
 (0)