Project

General

Profile

1 1876 aaronmk
# Dictionaries
2
3 1885 aaronmk
import itertools
4 1876 aaronmk
5 1907 aaronmk
import util
6
7 1885 aaronmk
class IdDict(dict):
8
    '''A dict that stores objects by id()'''
9
10
    def add(self, *values):
11
        for value in values: self[id(value)] = value
12
        return self
13
14
    def add_vars(self, vars_): return self.add(*vars_.values())
15
16 1876 aaronmk
class MergeDict:
17
    '''A dict that checks each of several dicts'''
18 1885 aaronmk
19 1876 aaronmk
    def __init__(self, *dicts): self.dicts = dicts
20
21
    def __getitem__(self, key):
22
        for dict_ in self.dicts:
23
            try: return dict_[key]
24
            except KeyError: pass
25
        raise # reraise last KeyError
26 1907 aaronmk
27 1911 aaronmk
28
class AttrsDictView:
29
    '''A dict view of an object's attributes
30
    @pre If you want __iter__() to work, value must have a __dict__
31
    '''
32
33
    def __init__(self, value): self.value = value
34
35
    def __iter__(self): return iter(self.value.__dict__)
36
37
    def __getitem__(self, key): return getattr(self.value, key)
38
39 1907 aaronmk
def make_hashable(value):
40
    if isinstance(value, list): value = tuple(value)
41
    elif isinstance(value, dict): value = util.NamedTuple(**value)
42
    return value