1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class django_choices(tuple):
'''
Creates a choices data type like what django needs for models.
'''
def __new__(self, *args, **kwargs):
self.choices = []
if kwargs:
for val in kwargs.values():
for key in kwargs.keys():
if kwargs[key] == val:
self.choices.append((val, key))
return tuple.__new__(self, self.choices or args)
def to_dict(self):
'''
Automatically converts the choices to a dictionary. Useful for type lookups.
'''
d = {}
for choice in self:
d[choice[1].lower()] = choice[0]
return d
|
Comments
The old syntax is also supported if you just want the methods:
django_choices( (0,'Manual'), (1,'Automatic'), )
#