UserDict.py 4.93 KB
Newer Older
1
"""A more or less complete user-defined wrapper around dictionary objects."""
2 3

class UserDict:
4
    def __init__(self, dict=None, **kwargs):
5
        self.data = {}
6
        if dict is not None:
7 8 9 10 11
            if not hasattr(dict,'keys'):
                dict = type({})(dict)   # make mapping from a sequence
            self.update(dict)
        if len(kwargs):
            self.update(kwargs)
12 13
    def __repr__(self): return repr(self.data)
    def __cmp__(self, dict):
14
        if isinstance(dict, UserDict):
15
            return cmp(self.data, dict.data)
16 17
        else:
            return cmp(self.data, dict)
18 19 20 21
    def __len__(self): return len(self.data)
    def __getitem__(self, key): return self.data[key]
    def __setitem__(self, key, item): self.data[key] = item
    def __delitem__(self, key): del self.data[key]
22
    def clear(self): self.data.clear()
23
    def copy(self):
24 25
        if self.__class__ is UserDict:
            return UserDict(self.data)
26
        import copy
27 28 29 30 31 32 33 34
        data = self.data
        try:
            self.data = {}
            c = copy.copy(self)
        finally:
            self.data = data
        c.update(self)
        return c
35 36
    def keys(self): return self.data.keys()
    def items(self): return self.data.items()
37 38 39
    def iteritems(self): return self.data.iteritems()
    def iterkeys(self): return self.data.iterkeys()
    def itervalues(self): return self.data.itervalues()
40 41
    def values(self): return self.data.values()
    def has_key(self, key): return self.data.has_key(key)
42 43 44 45 46
    def update(self, dict):
        if isinstance(dict, UserDict):
            self.data.update(dict.data)
        elif isinstance(dict, type(self.data)):
            self.data.update(dict)
47
        else:
48
            for k, v in dict.items():
49
                self[k] = v
50
    def get(self, key, failobj=None):
51 52 53
        if not self.has_key(key):
            return failobj
        return self[key]
54
    def setdefault(self, key, failobj=None):
55 56 57
        if not self.has_key(key):
            self[key] = failobj
        return self[key]
58 59
    def pop(self, key):
        return self.data.pop(key)
Guido van Rossum's avatar
Guido van Rossum committed
60 61
    def popitem(self):
        return self.data.popitem()
62 63
    def __contains__(self, key):
        return key in self.data
64 65 66 67 68 69
    def fromkeys(cls, iterable, value=None):
        d = cls()
        for key in iterable:
            d[key] = value
        return d
    fromkeys = classmethod(fromkeys)
70 71

class IterableUserDict(UserDict):
72 73
    def __iter__(self):
        return iter(self.data)
74 75

class DictMixin:
Raymond Hettinger's avatar
Raymond Hettinger committed
76 77 78 79 80 81
    # Mixin defining all dictionary methods for classes that already have
    # a minimum dictionary interface including getitem, setitem, delitem,
    # and keys. Without knowledge of the subclass constructor, the mixin
    # does not define __init__() or copy().  In addition to the four base
    # methods, progessively more efficiency comes with defining
    # __contains__(), __iter__(), and iteritems().
82

Raymond Hettinger's avatar
Raymond Hettinger committed
83 84 85 86
    # second level definitions support higher levels
    def __iter__(self):
        for k in self.keys():
            yield k
87 88 89 90 91 92 93 94
    def has_key(self, key):
        try:
            value = self[key]
        except KeyError:
            return False
        return True
    __contains__ = has_key

Raymond Hettinger's avatar
Raymond Hettinger committed
95
    # third level takes advantage of second level definitions
96 97 98 99 100
    def iteritems(self):
        for k in self:
            yield (k, self[k])
    iterkeys = __iter__

Raymond Hettinger's avatar
Raymond Hettinger committed
101
    # fourth level uses definitions from lower levels
102 103 104 105
    def itervalues(self):
        for _, v in self.iteritems():
            yield v
    def values(self):
Raymond Hettinger's avatar
Raymond Hettinger committed
106
        return [v for _, v in self.iteritems()]
107 108 109 110 111 112
    def items(self):
        return list(self.iteritems())
    def clear(self):
        for key in self.keys():
            del self[key]
    def setdefault(self, key, default):
Raymond Hettinger's avatar
Raymond Hettinger committed
113 114 115
        try:
            return self[key]
        except KeyError:
116
            self[key] = default
Raymond Hettinger's avatar
Raymond Hettinger committed
117
        return default
118 119 120 121 122 123 124 125
    def pop(self, key):
        value = self[key]
        del self[key]
        return value
    def popitem(self):
        try:
            k, v = self.iteritems().next()
        except StopIteration:
Raymond Hettinger's avatar
Raymond Hettinger committed
126
            raise KeyError, 'container is empty'
127 128 129
        del self[k]
        return (k, v)
    def update(self, other):
Raymond Hettinger's avatar
Raymond Hettinger committed
130 131 132 133 134 135 136 137 138 139
        # Make progressively weaker assumptions about "other"
        if hasattr(other, 'iteritems'):  # iteritems saves memory and lookups
            for k, v in other.iteritems():
                self[k] = v
        elif hasattr(other, '__iter__'): # iter saves memory
            for k in other:
                self[k] = other[k]
        else:
            for k in other.keys():
                self[k] = other[k]
140
    def get(self, key, default=None):
Raymond Hettinger's avatar
Raymond Hettinger committed
141
        try:
142
            return self[key]
Raymond Hettinger's avatar
Raymond Hettinger committed
143 144
        except KeyError:
            return default
145
    def __repr__(self):
Raymond Hettinger's avatar
Raymond Hettinger committed
146 147 148 149 150 151 152
        return repr(dict(self.iteritems()))
    def __cmp__(self, other):
        if isinstance(other, DictMixin):
            other = dict(other.iteritems())
        return cmp(dict(self.iteritems()), other)
    def __len__(self):
        return len(self.keys())