Last active
December 6, 2018 05:13
-
-
Save reorx/b7569acda4c0275f17ca82d72c740322 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
""" | |
Usage: | |
>>> class Color(SimpleEnum): | |
>>> red = KV | |
>>> green = 'green' # same as using `KV` | |
>>> grey = 'gray' | |
>>> Color.red | |
'red' | |
>>> Color.grey | |
'gray' | |
>>> Color.keys() | |
['red', 'green', 'grey'] | |
>>> Color.values() | |
['red', 'green', 'gray'] | |
Actually, built-in `enum.Enum` could achieve the same thing: | |
>>> class Color(enum.Enum): | |
>>> red = 'red' | |
>>> green = 'green' | |
>>> grey = 'gray' | |
>>> Color.__members__.keys() | |
odict_keys(['red', 'green', 'grey']) | |
>>> list(Color.__members__.keys()) | |
['red', 'green', 'grey'] | |
>>> Color._member_names_ | |
['red', 'green', 'grey'] | |
>>> [i.value for i in Color] | |
['red', 'green', 'gray'] | |
>>> list(Color._value2member_map_) | |
['red', 'green', 'gray'] | |
Just not that intuitive and convenient tho. | |
""" | |
from six import with_metaclass | |
KV = type('KV', (object, ), {}) | |
class SimpleEnumMeta(type): | |
def __new__(mcs, name, bases, attrs): | |
keys = [] | |
values = [] | |
for k, v in attrs.items(): | |
if k.startswith('_'): | |
continue | |
if v is KV: | |
v = k | |
attrs[k] = v | |
keys.append(k) | |
values.append(v) | |
attrs['_keys'] = keys | |
attrs['_values'] = values | |
return type.__new__(mcs, name, bases, attrs) | |
class SimpleEnum(with_metaclass(SimpleEnumMeta, object)): | |
@classmethod | |
def keys(cls): | |
return cls._keys | |
@classmethod | |
def values(cls): | |
return cls._values | |
@classmethod | |
def items(cls): | |
return zip(cls._keys, cls._values) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment