1+ import typing
2+
13import betterproto2
24
35from 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
0 commit comments