pythonlinuxclassprotocol-buffers

Why protobuf generates python class with __metaclass__ attribute?


protobuf generates C++/Java classes, and these are static typed class, enough for encoding/decoding. Why it generates python classes with metaclass attribute: I would suppose ordinary class will be enough to do rpc, like C++/Java generated classes.

Why python should use dynamic class? Thanks.


Solution

  • Mostly, because it's easier to read.

    The code generators for C++ and Java are really hard to understand and edit, because you have to follow both the generator code and the code being generated at the same time.

    The Python code generator could have been done the same way. However, because Python is a dynamic language, it's possible to use metaclasses instead. Essentially, this allows most of the code to be constructed at runtime. The metaclass is much easier to read and edit than a code generator because it is all straight Python, with no ugly print statements.

    Now, you might argue that Java could have done something similar: Generate very simple classes, and then use reflection to read and write the fields. The problem with that is that Java is a compiled language. Compiled code will perform much better than reflection-based code. Python, however, is not compiled, so there's not much penalty for using a reflection approach (it's slow either way). In fact, because Python is designed to be dynamic, you can do a lot of neat tricks that wouldn't be possible in other languages (but, again, it's slow either way).