blob: 50fee89853281c0c8509925f977786ef1adeb3be [file] [log] [blame]
Guido van Rossumae3b3a31993-11-30 13:43:54 +00001# A more or less complete user-defined wrapper around dictionary objects
2
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)