4

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.

Dash Winterson
  • 1,197
  • 8
  • 19
  • The manual suggest you make a wrapper https://developers.google.com/protocol-buffers/docs/pythontutorial#parsing-and-serialization – paiv May 26 '21 at 12:17
  • I guess more to the point, I'm looking for something that "presents" as the protobuf so I can run things like `instanceof` and built in protobuf methods. Of course you can do this by hand by writing a proxy, but I'm wondering if there's a more automatic way of doing it without needing to go method-for-method defining a boilerplate. – Dash Winterson May 26 '21 at 12:39

1 Answers1

0

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)
Avizipi
  • 502
  • 6
  • 16