diff options
author | Raymond Hettinger <python@rcn.com> | 2002-11-15 06:46:14 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2002-11-15 06:46:14 (GMT) |
commit | 7994716b6bcaeca64f47b7b3ed4e411bb6afc415 (patch) | |
tree | 0815d4b85257de2a72984d5c7026dab279b053e7 /Lib/UserDict.py | |
parent | 3a7f405f5b3388b5ba3cf807100627ae5fbf696f (diff) | |
download | cpython-7994716b6bcaeca64f47b7b3ed4e411bb6afc415.zip cpython-7994716b6bcaeca64f47b7b3ed4e411bb6afc415.tar.gz cpython-7994716b6bcaeca64f47b7b3ed4e411bb6afc415.tar.bz2 |
SF patch #520382: Expand shelve.py to have a full dictionary interface
and add a mixin to UserDict.py to make it easier to implement a full
dictionary interface.
Diffstat (limited to 'Lib/UserDict.py')
-rw-r--r-- | Lib/UserDict.py | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/Lib/UserDict.py b/Lib/UserDict.py index 91af83c..b6b36b2 100644 --- a/Lib/UserDict.py +++ b/Lib/UserDict.py @@ -60,3 +60,67 @@ class UserDict: class IterableUserDict(UserDict): def __iter__(self): return iter(self.data) + +class DictMixin: + '''Mixin defining all dictionary methods for classes that already have + a minimum dictionary interface including getitem, setitem, delitem, + and keys ''' + + # first level provided by subclass: getitem, setitem, delitem, and keys + + # second level definitions which assume only getitem and keys + def has_key(self, key): + try: + value = self[key] + except KeyError: + return False + return True + __contains__ = has_key + def __iter__(self): + for k in self.keys(): + yield k + def __len__(self): + return len(self.keys()) + + # third level uses second level instead of first + def iteritems(self): + for k in self: + yield (k, self[k]) + iterkeys = __iter__ + + # fourth level uses second and third levels instead of first + def itervalues(self): + for _, v in self.iteritems(): + yield v + def values(self): + return [self[key] for key in self.keys()] + def items(self): + return list(self.iteritems()) + def clear(self): + for key in self.keys(): + del self[key] + def setdefault(self, key, default): + if key not in self: + self[key] = default + return default + return self[key] + def pop(self, key): + value = self[key] + del self[key] + return value + def popitem(self): + try: + k, v = self.iteritems().next() + except StopIteration: + raise KeyError, 'dictionary is empty' + del self[k] + return (k, v) + def update(self, other): + for key in other.keys(): + self[key] = other[key] + def get(self, key, default=None): + if key in self: + return self[key] + return default + def __repr__(self): + return repr(dict(self.items())) |