1
2class LookupDictionary(dict):
3    """
4    a dictionary which can lookup value by key, or keys by value
5    """
6
7    def __init__(self, items=[]):
8        """items can be a list of pair_lists or a dictionary"""
9        dict.__init__(self, items)
10
11    def get_keys_for_value(self, value, fail_value=None):
12        """find the key(s) as a list given a value"""
13        list_result = [item[0] for item in self.items() if item[1] == value]
14        if len(list_result) > 0:
15            return list_result
16        return fail_value
17
18    def get_first_key_for_value(self, value, fail_value=None):
19        """return the first key of this dictionary given the value"""
20        list_result = [item[0] for item in self.items() if item[1] == value]
21        if len(list_result) > 0:
22            return list_result[0]
23        return fail_value
24
25    def get_value(self, key, fail_value=None):
26        """find the value given a key"""
27        if key in self:
28            return self[key]
29        return fail_value
30
31
32class Enum(LookupDictionary):
33
34    def __init__(self, initial_value=0, items=[]):
35        """items can be a list of pair_lists or a dictionary"""
36        LookupDictionary.__init__(self, items)
37        self.value = initial_value
38
39    def set_value(self, v):
40        v_typename = typeof(v).__name__
41        if v_typename == 'str':
42            if str in self:
43                v = self[v]
44            else:
45                v = 0
46        else:
47            self.value = v
48
49    def get_enum_value(self):
50        return self.value
51
52    def get_enum_name(self):
53        return self.__str__()
54
55    def __str__(self):
56        s = self.get_first_key_for_value(self.value, None)
57        if s is None:
58            s = "%#8.8x" % self.value
59        return s
60
61    def __repr__(self):
62        return self.__str__()
63