Skip to content

Instantly share code, notes, and snippets.

@bluven
Created January 25, 2016 00:48
Show Gist options
  • Save bluven/7590f7b5483e033a5238 to your computer and use it in GitHub Desktop.
Save bluven/7590f7b5483e033a5238 to your computer and use it in GitHub Desktop.
A base class which make choices class.
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