Created
April 6, 2011 16:48
-
-
Save GrAndSE/906023 to your computer and use it in GitHub Desktop.
Simple python enumeration class
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 collections import namedtuple | |
class Enum(tuple): | |
def __new__(cls, *sequential, **named): | |
new_cls = namedtuple(cls.__name__, sequential + tuple(named.keys())) | |
return new_cls._make(range(len(sequential))+named.values()) | |
class ChoicedEnum(tuple): | |
def __new__(cls, *sequential, **named): | |
new_cls = namedtuple(cls.__name__, sequential + tuple(named.keys())) | |
new_cls.__items = range(len(sequential))+named.values() | |
def iter(self): | |
for item in self.__items: | |
yield item | |
new_cls.__iter__ = iter | |
instance = new_cls._make(range(len(sequential)) + | |
[type(val) is tuple and val[1] or val for val in named.values()]) | |
return instance | |
e = Enum('ZERO', 'ONE', THREE=3, FOUR=4) | |
print e, e.ZERO, e.FOUR, tuple(e) | |
sizes = ChoicedEnum(SMALL = ('s', 'Small size'), BIG = ('b', 'Big size')) | |
print sizes.SMALL, tuple(sizes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment