Login

More readable Enumeration class for Django choices

Author:
achimnol
Posted:
July 22, 2009
Language:
Python
Version:
1.0
Tags:
choices model orm enumeration enum
Score:
4 (after 4 ratings)

We currently use two-level tuples to specify choices of a field in models or forms.

But, because it has only (value, verbose name) pair, the readability is bad whenever we indicate a specific choice value in our Python codes.

So I made a small class that does "magic" for this: A Named Enumeration.

Instead of myobj.status == 0, use myobj.status == STATUS.UNREVIEWED, for example.

 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 6 years, 12 months ago
  2. Django enumeration for model field choices by martinthenext 3 years, 3 months ago
  3. Model field choices as a namedtuple by whiteinge 4 years, 3 months ago
  4. Retrieve human-readable value from choices tuple or value from dict by JoeLinux 2 years, 4 months ago
  5. Choices helper by jacobian 5 years, 11 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?

#

Please login first before commenting.