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