Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 1 | """A more or less complete user-defined wrapper around dictionary objects.""" |
Guido van Rossum | ae3b3a3 | 1993-11-30 13:43:54 +0000 | [diff] [blame] | 2 | |
| 3 | class UserDict: |
Guido van Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 4 | def __init__(self, dict=None): |
| 5 | self.data = {} |
| 6 | if dict is not None: self.update(dict) |
Guido van Rossum | b94cd96 | 1997-06-03 14:10:01 +0000 | [diff] [blame] | 7 | def __repr__(self): return repr(self.data) |
| 8 | def __cmp__(self, dict): |
Guido van Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 9 | if isinstance(dict, UserDict): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 10 | return cmp(self.data, dict.data) |
Guido van Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 11 | else: |
| 12 | return cmp(self.data, dict) |
Guido van Rossum | b94cd96 | 1997-06-03 14:10:01 +0000 | [diff] [blame] | 13 | 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 Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 17 | def clear(self): self.data.clear() |
Guido van Rossum | b94cd96 | 1997-06-03 14:10:01 +0000 | [diff] [blame] | 18 | def copy(self): |
Guido van Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 19 | if self.__class__ is UserDict: |
| 20 | return UserDict(self.data) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 21 | import copy |
| 22 | return copy.copy(self) |
Guido van Rossum | b94cd96 | 1997-06-03 14:10:01 +0000 | [diff] [blame] | 23 | 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 Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 27 | 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 Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 32 | else: |
Guido van Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 33 | for k, v in dict.items(): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 34 | self.data[k] = v |
Barry Warsaw | fc3e61c | 1997-10-06 17:50:04 +0000 | [diff] [blame] | 35 | def get(self, key, failobj=None): |
Guido van Rossum | 1697b9c | 1999-03-26 15:31:12 +0000 | [diff] [blame] | 36 | return self.data.get(key, failobj) |