Welcome, guest | Sign In | My Account | Store | Cart

True immutable symbolic enumeration with qualified value access.

Python, 78 lines
 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python


def enum(*names):
    """A true immutable symbolic enumeration with qualified value access."""

    class EnumValue(object):

        __slots__ = ("type", "value",)

        def __init__(self, type, value):
            self.type = type
            self.value = value

        def __hash__(self):
            return hash(self.value)

        def __cmp__(self, other):
            return cmp(self.value, other.value)

        def __invert__(self):
            return self.type.values[(len(self.type) - 1) - self.value]

        def __nonzero__(self):
            return bool(self.value)

        def __repr__(self):
            return str(self.type.names[self.value])

    class EnumClass(object):

        __slots__ = ("names", "mapping", "values",)

        def __init__(self, *names):
            self.names = names
            self.values = dict(
                (i, EnumValue(self, i)) for i in range(len(names))
            )
            self.mapping = dict(
                (names[i], value) for i, value in self.values.items()
            )

        def __getattr__(self, attr):
            try:
                return self.mapping[attr]
            except KeyError:
                raise AttributeError(attr)

        def __iter__(self):
            return iter(self.values.values())

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

        def __getitem__(self, i):
            return self.values[i]

        def __repr__(self):
            return "<Enum {0:s}>".format(str(self.names))

        def __str__(self):
            return "enum {0:s}".format(str(self.values))

    return EnumClass(*names)


Days = enum("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
print Days
print Days.Mon
print Days.Fri
print Days.Mon < Days.Fri
print list(Days)
for day in Days:
    print "Day: {0:s}".format(repr(day))

Confirmation = enum("No", "Yes")
answer = Confirmation.No
print "Your answer is not", ~answer