More readable Enumeration class for Django choices

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Enumeration(object):
    """
    A small helper class for more readable enumerations,
    and compatible with Django's choice convention.
    You may just pass the instance of this class as the choices
    argument of model/form fields.

    Example:
        MY_ENUM = Enumeration([
            (100, 'MY_NAME', 'My verbose name'),
            (200, 'MY_AGE', 'My verbose age'),
        ])
        assert MY_ENUM.MY_AGE == 100
        assert MY_ENUM[1] == (200, 'My verbose age')
    """

    def __init__(self, enum_list):
        self.enum_list = [(item[0], item[2]) for item in enum_list]
        self.enum_dict = {}
        for item in enum_list:
            self.enum_dict[item[1]] = item[0]

    def __contains__(self, v):
        return (v in self.enum_list)

    def __len__(self):
        return len(self.enum_list)

    def __getitem__(self, v):
        if isinstance(v, basestring):
            return self.enum_dict[v]
        elif isinstance(v, int):
            return self.enum_list[v]

    def __getattr__(self, name):
        return self.enum_dict[name]

    def __iter__(self):
        return self.enum_list.__iter__()

More like this

  1. Enumeration field by nail.xx 5 years, 9 months ago
  2. Django enumeration for model field choices by martinthenext 2 years ago
  3. Model field choices as a namedtuple by whiteinge 3 years ago
  4. Retrieve human-readable value from choices tuple or value from dict by JoeLinux 1 year, 2 months ago
  5. Choices helper by jacobian 4 years, 8 months ago

Comments

pbx (on July 23, 2009):

Nicely done.

(Someday, dict comprehension syntax will shave a couple lines off the init :)

#

daws (on December 20, 2011):

Why not

def __init__(self, *enum_list):

and skip the square brackets on init?

#

(Forgotten your password?)