blob: bb2218ab6ce5d808a4016105d69b7b637d1252a6 [file] [log] [blame]
"""A more or less complete user-defined wrapper around dictionary objects."""
class UserDict:
def __init__(self, dict=None, **kwargs): = {}
if dict is not None:
if len(kwargs):
def __repr__(self): return repr(
def __cmp__(self, dict):
if isinstance(dict, UserDict):
return cmp(,
return cmp(, dict)
__hash__ = None # Avoid Py3k warning
def __len__(self): return len(
def __getitem__(self, key):
if key in
if hasattr(self.__class__, "__missing__"):
return self.__class__.__missing__(self, key)
raise KeyError(key)
def __setitem__(self, key, item):[key] = item
def __delitem__(self, key): del[key]
def clear(self):
def copy(self):
if self.__class__ is UserDict:
return UserDict(
import copy
data =
try: = {}
c = copy.copy(self)
finally: = data
return c
def keys(self): return
def items(self): return
def iteritems(self): return
def iterkeys(self): return
def itervalues(self): return
def values(self): return
def has_key(self, key): return key in
def update(self, dict=None, **kwargs):
if dict is None:
elif isinstance(dict, UserDict):
elif isinstance(dict, type({})) or not hasattr(dict, 'items'):
for k, v in dict.items():
self[k] = v
if len(kwargs):
def get(self, key, failobj=None):
if key not in self:
return failobj
return self[key]
def setdefault(self, key, failobj=None):
if key not in self:
self[key] = failobj
return self[key]
def pop(self, key, *args):
return, *args)
def popitem(self):
def __contains__(self, key):
return key in
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
class IterableUserDict(UserDict):
def __iter__(self):
return iter(
import _abcoll
class DictMixin:
# 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, progressively more efficiency comes with defining
# __contains__(), __iter__(), and iteritems().
# second level definitions support higher levels
def __iter__(self):
for k in self.keys():
yield k
def has_key(self, key):
except KeyError:
return False
return True
def __contains__(self, key):
return self.has_key(key)
# third level takes advantage of second level definitions
def iteritems(self):
for k in self:
yield (k, self[k])
def iterkeys(self):
return self.__iter__()
# fourth level uses definitions from lower levels
def itervalues(self):
for _, v in self.iteritems():
yield v
def values(self):
return [v for _, v in self.iteritems()]
def items(self):
return list(self.iteritems())
def clear(self):
for key in self.keys():
del self[key]
def setdefault(self, key, default=None):
return self[key]
except KeyError:
self[key] = default
return default
def pop(self, key, *args):
if len(args) > 1:
raise TypeError, "pop expected at most 2 arguments, got "\
+ repr(1 + len(args))
value = self[key]
except KeyError:
if args:
return args[0]
del self[key]
return value
def popitem(self):
k, v = self.iteritems().next()
except StopIteration:
raise KeyError, 'container is empty'
del self[k]
return (k, v)
def update(self, other=None, **kwargs):
# Make progressively weaker assumptions about "other"
if other is None:
elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups
for k, v in other.iteritems():
self[k] = v
elif hasattr(other, 'keys'):
for k in other.keys():
self[k] = other[k]
for k, v in other:
self[k] = v
if kwargs:
def get(self, key, default=None):
return self[key]
except KeyError:
return default
def __repr__(self):
return repr(dict(self.iteritems()))
def __cmp__(self, other):
if other is None:
return 1
if isinstance(other, DictMixin):
other = dict(other.iteritems())
return cmp(dict(self.iteritems()), other)
def __len__(self):
return len(self.keys())