Created
January 25, 2016 00:48
-
-
Save bluven/7590f7b5483e033a5238 to your computer and use it in GitHub Desktop.
A base class which make choices class.
This file contains hidden or 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 six | |
class ChoiceMeta(type): | |
def __new__(mcs, name, bases, attrs): | |
choices = [] | |
values = [] | |
labels = [] | |
for field, value in attrs.items(): | |
if field.isupper(): | |
attrs[field] = value[0] | |
values.append(value[0]) | |
labels.append(value[1]) | |
choices.append(value) | |
attrs['CHOICES'] = choices | |
attrs['KEY_LABELS'] = dict(choices) | |
attrs['VALUES'] = values | |
attrs['LABELS'] = labels | |
return super(ChoiceMeta, mcs).__new__(mcs, name, bases, attrs) | |
class Choice(six.with_metaclass(ChoiceMeta)): | |
@classmethod | |
def get_label(cls, key, default=None): | |
return cls.KEY_LABELS.get(key, default) | |
class State(Choice): | |
ENABLED = (1, "Enabled") | |
DISABLED = (0, "Disabled") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment