Preface
I'm trying to develop a lightweight enum for Python 2.7. This question is downstream of the SO question here; for context, a streamlined version of the bulleted addendum to that question is replicated below (My desired feature set is):
How-To
To note, every form of dynamic namespace construction I've tried, in efforts to accomplish #1, has broken #2. I'm pretty sure at this point they're mutually exclusive. In any event, my current solution goes as follows, defining an enum superclass with a metaclassed type with an iterator that returns all members with string content identical to the respective member names:
- EnumBase.py
- class SuperEnum(object):
- class __metaclass__(type):
- def __iter__(self):
- for item in self.__dict__:
- if item == self.__dict__[item]:
- yield item
- class EnumMeta(type):
- def __new__(metaClz, enumClzName, supers, attrs):
- return type(enumClzName, supers, attrs)
- def __init__(self, clzName, supers, attrs):
- pass
- def GenEnum(clzName, enum_values):
- EnumClz = EnumMeta(clzName, (SuperEnum,), enum_values)
- return EnumClz
- class MyEnum(SuperEnum):
- A = "A"
- B = "B"
- C = "C"
This construction is far more concise than anything I'd set up around the time I posted the above-linked SO question, so the need to type the value name twice in the enum class definition isn't terribly bothersome. I'm still interested to know if there's any way to make #1 and #2 play nice together, though.
More generally: what might the weaknesses of this construction be? For my application, performance is of minor concern. There's always the possibility of value collisions, as described here, but using strings as the values dramatically reduces the likelihood. Security issues? Compatibility problems of some kind?
Supplement
* [ Python 文章收集 ] 深刻理解 Python 中的元類 (metaclass)
沒有留言:
張貼留言