blob: b642db73b57e480c55dbd4af7474d0983d77e126 [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""A more or less complete user-defined wrapper around dictionary objects."""
Guido van Rossumae3b3a31993-11-30 13:43:54 +00002
3class UserDict:
Guido van Rossum1697b9c1999-03-26 15:31:12 +00004 def __init__(self, dict=None):
5 self.data = {}
6 if dict is not None: self.update(dict)
Guido van Rossumb94cd961997-06-03 14:10:01 +00007 def __repr__(self): return repr(self.data)
8 def __cmp__(self, dict):
Guido van Rossum1697b9c1999-03-26 15:31:12 +00009 if isinstance(dict, UserDict):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000010 return cmp(self.data, dict.data)
Guido van Rossum1697b9c1999-03-26 15:31:12 +000011 else:
12 return cmp(self.data, dict)
Guido van Rossumb94cd961997-06-03 14:10:01 +000013 def __len__(self): return len(self.data)
14 def __getitem__(self, key): return self.data[key]
15 def __setitem__(self, key, item): self.data[key] = item
16 def __delitem__(self, key): del self.data[key]
Guido van Rossum1697b9c1999-03-26 15:31:12 +000017 def clear(self): self.data.clear()
Guido van Rossumb94cd961997-06-03 14:10:01 +000018 def copy(self):
Guido van Rossum1697b9c1999-03-26 15:31:12 +000019 if self.__class__ is UserDict:
20 return UserDict(self.data)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000021 import copy
22 return copy.copy(self)
Guido van Rossumb94cd961997-06-03 14:10:01 +000023 def keys(self): return self.data.keys()
24 def items(self): return self.data.items()
25 def values(self): return self.data.values()
26 def has_key(self, key): return self.data.has_key(key)
Guido van Rossum1697b9c1999-03-26 15:31:12 +000027 def update(self, dict):
28 if isinstance(dict, UserDict):
29 self.data.update(dict.data)
30 elif isinstance(dict, type(self.data)):
31 self.data.update(dict)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000032 else:
Guido van Rossum1697b9c1999-03-26 15:31:12 +000033 for k, v in dict.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000034 self.data[k] = v
Barry Warsawfc3e61c1997-10-06 17:50:04 +000035 def get(self, key, failobj=None):
Guido van Rossum1697b9c1999-03-26 15:31:12 +000036 return self.data.get(key, failobj)
Guido van Rossum164452c2000-08-08 16:12:54 +000037 def setdefault(self, key, failobj=None):
38 if not self.data.has_key(key):
39 self.data[key] = failobj
40 return self.data[key]
Guido van Rossum1072c382000-12-12 22:06:00 +000041 def popitem(self):
42 return self.data.popitem()