| 1129 | ################################################################################ |
| 1130 | |
| 1131 | class UserDict(_collections_abc.MutableMapping): |
| 1132 | |
| 1133 | # Start by filling-out the abstract methods |
| 1134 | def __init__(self, dict=None, /, **kwargs): |
| 1135 | self.data = {} |
| 1136 | if dict is not None: |
| 1137 | self.update(dict) |
| 1138 | if kwargs: |
| 1139 | self.update(kwargs) |
| 1140 | |
| 1141 | def __len__(self): |
| 1142 | return len(self.data) |
| 1143 | |
| 1144 | def __getitem__(self, key): |
| 1145 | if key in self.data: |
| 1146 | return self.data[key] |
| 1147 | if hasattr(self.__class__, "__missing__"): |
| 1148 | return self.__class__.__missing__(self, key) |
| 1149 | raise KeyError(key) |
| 1150 | |
| 1151 | def __setitem__(self, key, item): |
| 1152 | self.data[key] = item |
| 1153 | |
| 1154 | def __delitem__(self, key): |
| 1155 | del self.data[key] |
| 1156 | |
| 1157 | def __iter__(self): |
| 1158 | return iter(self.data) |
| 1159 | |
| 1160 | # Modify __contains__ and get() to work like dict |
| 1161 | # does when __missing__ is present. |
| 1162 | def __contains__(self, key): |
| 1163 | return key in self.data |
| 1164 | |
| 1165 | def get(self, key, default=None): |
| 1166 | if key in self: |
| 1167 | return self[key] |
| 1168 | return default |
| 1169 | |
| 1170 | |
| 1171 | # Now, add the methods in dicts but not in MutableMapping |
| 1172 | def __repr__(self): |
| 1173 | return repr(self.data) |
| 1174 | |
| 1175 | def __or__(self, other): |
| 1176 | if isinstance(other, UserDict): |
| 1177 | return self.__class__(self.data | other.data) |
| 1178 | if isinstance(other, dict): |
| 1179 | return self.__class__(self.data | other) |
| 1180 | return NotImplemented |
| 1181 | |
| 1182 | def __ror__(self, other): |
| 1183 | if isinstance(other, UserDict): |
| 1184 | return self.__class__(other.data | self.data) |
| 1185 | if isinstance(other, dict): |
| 1186 | return self.__class__(other | self.data) |
| 1187 | return NotImplemented |
| 1188 |
no outgoing calls