Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add type hint for all protocol buffer objects in python functions?

I want to add type hints for arguments in functions that accept any google protocol buffer object.

def do_something(protobuf_obj: WHAT_IS_HERE):
    # protobuf_obj can be any protocol buffer instance
    pass

What class should I put there from the google.protobuf library?

like image 425
hazrmard Avatar asked Jun 21 '26 15:06

hazrmard


1 Answers

I ended up using the Message abstract base class. From the docs:

class google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

So, now it looks like:

from google.protobuf.message import Message

def do_something(protobuf_obj: Message):
    # protobuf_obj can be any protocol buffer instance
    pass

like image 170
hazrmard Avatar answered Jun 23 '26 04:06

hazrmard