Skip to content

Instantly share code, notes, and snippets.

@jjmontesl
Created September 12, 2017 14:19
Show Gist options
  • Save jjmontesl/d4079af6646bd92bdafc4ae657f51f62 to your computer and use it in GitHub Desktop.
Save jjmontesl/d4079af6646bd92bdafc4ae657f51f62 to your computer and use it in GitHub Desktop.
Automatic generation of python Enum from Protobuf enumerations
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