Search code examples
pythonprotocol-buffersisinstance

How to programmatically find if the object type is of Google Protobuf?


I have a case where I receive objects from another module. The object type can be JSON String, dict or of Google Protobuf. I can use isinstance in python to determine whether it is JSON String or dict, but finding it difficult to use isinstance to check if it is protobuf. I am not even sure if isinstance can be used for non-primitive types like Google Protobuf.

So, Is there a way to check the given object is of Google Protobuf type in Python?


Solution

  • Are you receiving Protobuf objects or serialized (binary) strings?

    If you're receiving objects then these should be subclasses of Message and isinstance using your object for Message should be true for protobufs.

    If your incoming object is o and:

    assert isinstance(json.loads(o), dict)
    assert isinstance(o, dict)
    
    from google.protobuf.message import Message
    assert isinstance(o, Message)
    assert issubclass(o, Message)
    

    Even though it's more effort to test for each type (JSON, dict, proto), I think it would be better to confirm the object's type before proceeding.

    You can short-circuit the tests by only testing until you find a match but you want to avoid some 4th type being added in the future and your code assuming that anything that's not JSON or dict is a proto.