Created
September 12, 2017 14:19
-
-
Save jjmontesl/d4079af6646bd92bdafc4ae657f51f62 to your computer and use it in GitHub Desktop.
Automatic generation of python Enum from Protobuf enumerations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum, EnumMeta | |
class ProtobufEnumMeta(EnumMeta): | |
def __new__(metacls, cls, bases, classdict): | |
""" | |
Enum uses its EnumMeta metaclass magic method 'new' to instrument | |
the Enum class, hence we override that method in order to add | |
Protobuf attributes from the protobuf enum before. | |
""" | |
for key in metacls._protobuf_enum.keys(): | |
classdict[key] = metacls._protobuf_enum.Value(key) | |
# Call parent metaclass new | |
return EnumMeta.__new__(metacls, cls, bases, classdict) | |
@staticmethod | |
def metaclass(protobuf_enum_type): | |
return type("ProtobufEnum" + protobuf_enum_type._enum_type.name, (ProtobufEnumMeta, ), {'_protobuf_enum': protobuf_enum_type}) | |
class MyEnum(Enum): | |
__metaclass__ = ProtobufEnumMeta.metaclass(protobuf_python.MyEnum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment