How to extend protobuf objects in python

Viewed 585

I've defined a protobuf message that I'd like to create a wrapper/proxy/boilerplate/extension/anything for so I can add custom methods.

The docs for protobuf say that you are advised not to inherit directly from the protobuf as under the hood, it's actually a descriptor and metaclass that define most of the methods/attributes.

I was wondering how people go about "inheriting" a class as best as possible when inheritance is not a stable option, or if anyone has had any luck using protobuf codegen to extend/define a custom Message class and if that's a reasonable idea.

1 Answers

Never worked with protobuf, and dont know if the dir function of python will work on it. But if it does you can do something like that:

class A:
    def app(self):
        print("app")
    def bla(self):
        print("bla")

class wrapperA:
    def __init__(self,a):
        self.dict_of_functions = {x:getattr(a, x) for x in dir(A)}
    def funcA(self, func_name):
        return self.dict_of_functions[func_name]()
    
a = A()
wa = wrapperA(a)
for x in ["app", "bla"]:
    wa.funcA(x)
Related