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