brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.8 KiB · d3a2a8d Raw
61 lines · python
1class LookupDictionary(dict):2    """3    a dictionary which can lookup value by key, or keys by value4    """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_result15        return fail_value16 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_value23 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_value29 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_value36 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 = 044        else:45            self.value = v46 47    def get_enum_value(self):48        return self.value49 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.value57        return s58 59    def __repr__(self):60        return self.__str__()61