Search code examples
pythonprotocol-bufferstype-hinting

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?


Solution

  • 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