Project

General

Profile

1
# Dictionaries
2

    
3
import itertools
4
import UserDict
5

    
6
def is_dict(value): return hasattr(value, 'keys')
7

    
8
class DictProxy(UserDict.DictMixin):
9
    '''A proxy that forwards all accesses to an inner dict.'''
10
    
11
    def __init__(self, inner=None):
12
        if inner == None: inner = {}
13
        self.inner = inner
14
    
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
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
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
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
class MergeDict:
58
    '''A dict that checks each of several dicts'''
59
    
60
    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

    
68
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
import util
80

    
81
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

    
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
        try: out_value = dict1.get(in_, in_) # use in_ if no match found
93
        except TypeError: out_value = in_ # unhashable type
94
        new_dict[out] = out_value
95
    return new_dict
(12-12/42)