| 1106 | ################################################################################ |
| 1107 | |
| 1108 | class UserDict(_collections_abc.MutableMapping): |
| 1109 | |
| 1110 | # Start by filling-out the abstract methods |
| 1111 | def __init__(self, dict=None, /, **kwargs): |
| 1112 | self.data = {} |
| 1113 | if dict is not None: |
| 1114 | self.update(dict) |
| 1115 | if kwargs: |
| 1116 | self.update(kwargs) |
| 1117 | |
| 1118 | def __len__(self): |
| 1119 | return len(self.data) |
| 1120 | |
| 1121 | def __getitem__(self, key): |
| 1122 | if key in self.data: |
| 1123 | return self.data[key] |
| 1124 | if hasattr(self.__class__, "__missing__"): |
| 1125 | return self.__class__.__missing__(self, key) |
| 1126 | raise KeyError(key) |
| 1127 | |
| 1128 | def __setitem__(self, key, item): |
| 1129 | self.data[key] = item |
| 1130 | |
| 1131 | def __delitem__(self, key): |
| 1132 | del self.data[key] |
| 1133 | |
| 1134 | def __iter__(self): |
| 1135 | return iter(self.data) |
| 1136 | |
| 1137 | # Modify __contains__ to work correctly when __missing__ is present |
| 1138 | def __contains__(self, key): |
| 1139 | return key in self.data |
| 1140 | |
| 1141 | # Now, add the methods in dicts but not in MutableMapping |
| 1142 | def __repr__(self): |
| 1143 | return repr(self.data) |
| 1144 | |
| 1145 | def __or__(self, other): |
| 1146 | if isinstance(other, UserDict): |
| 1147 | return self.__class__(self.data | other.data) |
| 1148 | if isinstance(other, dict): |
| 1149 | return self.__class__(self.data | other) |
| 1150 | return NotImplemented |
| 1151 | |
| 1152 | def __ror__(self, other): |
| 1153 | if isinstance(other, UserDict): |
| 1154 | return self.__class__(other.data | self.data) |
| 1155 | if isinstance(other, dict): |
| 1156 | return self.__class__(other | self.data) |
| 1157 | return NotImplemented |
| 1158 | |
| 1159 | def __ior__(self, other): |
| 1160 | if isinstance(other, UserDict): |
| 1161 | self.data |= other.data |
| 1162 | else: |
| 1163 | self.data |= other |
| 1164 | return self |
| 1165 | |