Created
June 3, 2013 22:13
-
-
Save mitsuhiko/5701932 to your computer and use it in GitHub Desktop.
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
import sys | |
class EnumType(type): | |
@staticmethod | |
def __prepare__(name, bases, **kwargs): | |
rv = {} | |
rv['max_val'] = 0 | |
def iota(): | |
rv['max_val'] += 1 | |
return rv['max_val'] | |
rv['iota'] = iota | |
return rv | |
def __new__(cls, name, bases, d): | |
d['__slots__'] = () | |
rv = type.__new__(cls, name, bases, d) | |
reverse_mapping = dict(getattr(rv, '__values__', None) or {}) | |
for key, value in d.items(): | |
if isinstance(value, int): | |
val = rv(value) | |
setattr(rv, key, val) | |
reverse_mapping[val] = key | |
rv.__values__ = reverse_mapping | |
return rv | |
class Enum(int, metaclass=EnumType): | |
__slots__ = () | |
def __str__(self): | |
return '%s.%s' % ( | |
self.__class__.__name__, | |
self.__class__.__values__[self] | |
) | |
def __repr__(self): | |
return str(self) | |
class Colors(Enum): | |
red = iota() | |
blue = iota() | |
green = iota() | |
print(Colors.red) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment