2000-02-02 23:10:15 +08:00
|
|
|
"""A more or less complete user-defined wrapper around dictionary objects."""
|
1993-11-30 21:43:54 +08:00
|
|
|
|
|
|
|
class UserDict:
|
1999-03-26 23:31:12 +08:00
|
|
|
def __init__(self, dict=None):
|
|
|
|
self.data = {}
|
|
|
|
if dict is not None: self.update(dict)
|
1997-06-03 22:10:01 +08:00
|
|
|
def __repr__(self): return repr(self.data)
|
|
|
|
def __cmp__(self, dict):
|
1999-03-26 23:31:12 +08:00
|
|
|
if isinstance(dict, UserDict):
|
1998-03-27 05:13:24 +08:00
|
|
|
return cmp(self.data, dict.data)
|
1999-03-26 23:31:12 +08:00
|
|
|
else:
|
|
|
|
return cmp(self.data, dict)
|
1997-06-03 22:10:01 +08:00
|
|
|
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]
|
1999-03-26 23:31:12 +08:00
|
|
|
def clear(self): self.data.clear()
|
1997-06-03 22:10:01 +08:00
|
|
|
def copy(self):
|
1999-03-26 23:31:12 +08:00
|
|
|
if self.__class__ is UserDict:
|
|
|
|
return UserDict(self.data)
|
1998-03-27 05:13:24 +08:00
|
|
|
import copy
|
2001-11-06 01:40:48 +08:00
|
|
|
data = self.data
|
|
|
|
try:
|
|
|
|
self.data = {}
|
|
|
|
c = copy.copy(self)
|
|
|
|
finally:
|
|
|
|
self.data = data
|
|
|
|
c.update(self)
|
|
|
|
return c
|
1997-06-03 22:10:01 +08:00
|
|
|
def keys(self): return self.data.keys()
|
|
|
|
def items(self): return self.data.items()
|
2001-05-03 12:54:41 +08:00
|
|
|
def iteritems(self): return self.data.iteritems()
|
|
|
|
def iterkeys(self): return self.data.iterkeys()
|
|
|
|
def itervalues(self): return self.data.itervalues()
|
1997-06-03 22:10:01 +08:00
|
|
|
def values(self): return self.data.values()
|
|
|
|
def has_key(self, key): return self.data.has_key(key)
|
1999-03-26 23:31:12 +08:00
|
|
|
def update(self, dict):
|
|
|
|
if isinstance(dict, UserDict):
|
|
|
|
self.data.update(dict.data)
|
|
|
|
elif isinstance(dict, type(self.data)):
|
|
|
|
self.data.update(dict)
|
1998-03-27 05:13:24 +08:00
|
|
|
else:
|
1999-03-26 23:31:12 +08:00
|
|
|
for k, v in dict.items():
|
2001-06-18 09:09:41 +08:00
|
|
|
self[k] = v
|
1997-10-07 01:50:04 +08:00
|
|
|
def get(self, key, failobj=None):
|
2001-06-18 09:09:41 +08:00
|
|
|
if not self.has_key(key):
|
|
|
|
return failobj
|
|
|
|
return self[key]
|
2000-08-09 00:12:54 +08:00
|
|
|
def setdefault(self, key, failobj=None):
|
2001-06-18 09:09:41 +08:00
|
|
|
if not self.has_key(key):
|
|
|
|
self[key] = failobj
|
|
|
|
return self[key]
|
2002-04-13 22:03:38 +08:00
|
|
|
def pop(self, key):
|
|
|
|
return self.data.pop(key)
|
2000-12-13 06:06:00 +08:00
|
|
|
def popitem(self):
|
|
|
|
return self.data.popitem()
|
2001-04-21 17:13:15 +08:00
|
|
|
def __contains__(self, key):
|
|
|
|
return key in self.data
|
2001-08-08 01:40:42 +08:00
|
|
|
|
|
|
|
class IterableUserDict(UserDict):
|
2001-04-21 17:13:15 +08:00
|
|
|
def __iter__(self):
|
|
|
|
return iter(self.data)
|