Skip to content

Instantly share code, notes, and snippets.

@arthuralvim
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthuralvim/b31a2ab82ee1cae66e59 to your computer and use it in GitHub Desktop.
Save arthuralvim/b31a2ab82ee1cae66e59 to your computer and use it in GitHub Desktop.
The way I organize my choices on my Django Projects.
class ChoicesEnum(object):
@classmethod
def choices(cls):
descriptions = cls.get_descriptions()
keys = descriptions.keys()
attrs = cls.get_atributes(keys)
return tuple([(attrs[k], descriptions[k]) for k in keys])
@classmethod
def get_descriptions(cls):
description = {}
for attr, val in cls.__dict__.iteritems():
if attr.lower().endswith('_text'):
description.update({attr[:-5]: val})
return description
@classmethod
def get_atributes(cls, keys):
attrs = {}
for attr, val in cls.__dict__.iteritems():
if attr in keys:
attrs.update({attr: val})
return attrs
@classmethod
def get_text(cls, key):
try:
return dict(cls.choices())[key]
except KeyError:
return None
except Exception, e:
raise e
class ExampleChoices(ChoicesEnum):
Option1 = 1
Option1_text = 'Description 1'
Option2 = 2
Option2_text = 'Description 2'
Option3 = 3
Option3_text = 'Description 3'
ExampleChoices.get_text(1)
ExampleChoices.get_text(ExampleChoices.Option1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment