Project

General

Profile

1 1876 aaronmk
# Dictionaries
2
3 1885 aaronmk
import itertools
4 2651 aaronmk
import UserDict
5 1876 aaronmk
6 2657 aaronmk
def is_dict(value): return hasattr(value, 'keys')
7 2649 aaronmk
8 2651 aaronmk
class DictProxy(UserDict.DictMixin):
9
    '''A proxy that forwards all accesses to an inner dict.'''
10
11 3720 aaronmk
    def __init__(self, inner=None):
12
        if inner == None: inner = {}
13
        self.inner = inner
14 2651 aaronmk
15
    def keys(self): return self.inner.keys()
16
17
    def __getitem__(self, key): return self.inner[key]
18
19
    def __setitem__(self, key, value): self.inner[key] = value
20
21 3717 aaronmk
class KeyExistsError(KeyError):
22
    def __init__(self, key):
23
        KeyError.__init__(self, key)
24
25
        self.key = key
26
27
class OnceOnlyDict(DictProxy):
28
    '''A dict that only allows each key to be assigned once (no overwriting).'''
29
30
    def __setitem__(self, key, value):
31
        if key in self.inner: raise KeyExistsError(key)
32
        DictProxy.__setitem__(self, key, value)
33
34 2670 aaronmk
class IdCompared:
35
    '''A value that's compared using `is` instead of ==.
36
    Do not use this for strings as they are interned, causing `is` to have the
37
    same meaning as ==.
38
    '''
39
40
    def __init__(self, value): self.value = value
41
42
    def __eq__(self, other):
43
        return (other != None and other.__class__ == self.__class__
44
            and other.value is self.value)
45
46
    def __hash__(self): return id(self.value)
47
48 1885 aaronmk
class IdDict(dict):
49
    '''A dict that stores objects by id()'''
50
51
    def add(self, *values):
52
        for value in values: self[id(value)] = value
53
        return self
54
55
    def add_vars(self, vars_): return self.add(*vars_.values())
56
57 1876 aaronmk
class MergeDict:
58
    '''A dict that checks each of several dicts'''
59 1885 aaronmk
60 1876 aaronmk
    def __init__(self, *dicts): self.dicts = dicts
61
62
    def __getitem__(self, key):
63
        for dict_ in self.dicts:
64
            try: return dict_[key]
65
            except KeyError: pass
66
        raise # reraise last KeyError
67 1907 aaronmk
68 1911 aaronmk
class AttrsDictView:
69
    '''A dict view of an object's attributes
70
    @pre If you want __iter__() to work, value must have a __dict__
71
    '''
72
73
    def __init__(self, value): self.value = value
74
75
    def __iter__(self): return iter(self.value.__dict__)
76
77
    def __getitem__(self, key): return getattr(self.value, key)
78
79 2817 aaronmk
import util
80
81 1907 aaronmk
def make_hashable(value):
82
    if isinstance(value, list): value = tuple(value)
83
    elif isinstance(value, dict): value = util.NamedTuple(**value)
84
    return value
85 2384 aaronmk
86
def join(dict0, dict1):
87
    '''Joins dict0 (A->B mapping) to dict1 (B->C mapping) SQL-style.
88
    If a value in dict0 has no key in dict1, uses the value itself.
89
    '''
90
    new_dict = {}
91
    for out, in_ in dict0.iteritems():
92
        new_dict[out] = dict1.get(in_, in_) # use in_ if no match found
93
    return new_dict