Last Updated: August 12, 2019
·
1.513K
· Gabriel Falcão

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)

2 Responses
Add your response

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 ·