Exquisite enums in python
Using the enum below you can create django model choises pretty easily
Enum = type('Enum', (tuple, ), {
'__init__': lambda s, i: [
setattr(s, k, 1 << x)
for x, k in enumerate(i)
] and tuple.__init__(s, i)
})
USER_TYPES = Enum(["Person", "Robot", "Company"])
Usage with django models
from django.db import models
class Person(models.Model):
name = models.CharField()
kind = models.IntegerField(choices=USER_TYPES, default=USER_TYPES.Person)
Written by Gabriel Falcão
Related protips
2 Responses
Maybe, just:
choices=tuple(enumerate(["Person", "Robot", "Company"]))
?
over 1 year ago
·
Please look at the code again, it's a different situation. There is usage of dotted notation.
Also, because it's fun :)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#