Adapting the code from Mark Tolonen to create actual Python Enums:
# import the dependencies
from enum import EnumMeta, IntEnum
from pyparsing import Group, Optional, Suppress, Word, ZeroOrMore
from pyparsing import alphas, alphanums, nums
The first step is to create a new EnumMeta
type (note that this is one of the times when subclassing EnumMeta
is a good idea):
CPPEnum = None
class CPPEnumType(EnumMeta):
#
@classmethod
def __prepare__(metacls, clsname, bases, **kwds):
# return a standard dictionary for the initial processing
return {}
#
def __init__(clsname, *args , **kwds):
super(CPPEnumType, clsname).__init__(*args)
#
def __new__(metacls, clsname, bases, clsdict, **kwds):
if CPPEnum is None:
# first time through, ignore the rest
enum_dict = super(CPPEnumType, metacls).__prepare__(
clsname, bases, **kwds
)
enum_dict.update(clsdict)
return super(CPPEnumType, metacls).__new__(
metacls, clsname, bases, enum_dict, **kwds,
)
members = []
#
# remove _file and _name using `pop()` as they will
# cause problems in EnumMeta
try:
file = clsdict.pop('_file')
except KeyError:
raise TypeError('_file not specified')
cpp_enum_name = clsdict.pop('_name', clsname.lower())
with open(file) as fh:
file_contents = fh.read()
#
# syntax we don't want to see in the final parse tree
LBRACE, RBRACE, EQ, COMMA = map(Suppress, "{}=,")
_enum = Suppress("enum")
identifier = Word(alphas, alphanums + "_")
integer = Word(nums)
enumValue = Group(identifier("name") + Optional(EQ + integer("value")))
enumList = Group(enumValue + ZeroOrMore(COMMA + enumValue))
enum = _enum + identifier("enum") + LBRACE + enumList("names") + RBRACE
#
# find the cpp_enum_name ignoring other syntax and other enums
for item, start, stop in enum.scanString(file_contents):
if item.enum != cpp_enum_name:
continue
id = 0
for entry in item.names:
if entry.value != "":
id = int(entry.value)
members.append((entry.name.upper(), id))
id += 1
#
# get the real EnumDict
enum_dict = super(CPPEnumType, metacls).__prepare__(clsname, bases, **kwds)
# transfer the original dict content, names starting with '_' first
items = list(clsdict.items())
items.sort(key=lambda p: (0 if p[0][0] == '_' else 1, p))
for name, value in items:
enum_dict[name] = value
# add the members
for name, value in members:
enum_dict[name] = value
return super(CPPEnumType, metacls).__new__(
metacls, clsname, bases, enum_dict, **kwds,
)
Once the new type is created, we can create the new base class:
class CPPEnum(IntEnum, metaclass=CPPEnumType):
pass
Once you have the new CPPEnum
base class, using it is as simple as:
class Hello(CPPEnum):
_file = 'some_header.h'
class Blah(CPPEnum):
_file = 'some_header.h'
_name = 'blah' # in case the name in the file is not the lower-cased
# version of the Enum class name (so not needed in
# in this case)
And in use:
>>> list(Hello)
[
<Hello.ZERO: 0>, <Hello.ONE: 1>, <Hello.TWO: 2>, <Hello.THREE: 3>,
<Hello.FIVE: 5>, <Hello.SIX: 6>, <Hello.TEN: 10>,
]
Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.