A minimal dict-like class that also supports unhashable keys, storing them in a list of key-value pairs. This class only implements the interface needed for `CallbackRegistry`, and tries to minimize the overhead for the hashable case.
| 145 | |
| 146 | |
| 147 | class _UnhashDict: |
| 148 | """ |
| 149 | A minimal dict-like class that also supports unhashable keys, storing them |
| 150 | in a list of key-value pairs. |
| 151 | |
| 152 | This class only implements the interface needed for `CallbackRegistry`, and |
| 153 | tries to minimize the overhead for the hashable case. |
| 154 | """ |
| 155 | |
| 156 | def __init__(self, pairs): |
| 157 | self._dict = {} |
| 158 | self._pairs = [] |
| 159 | for k, v in pairs: |
| 160 | self[k] = v |
| 161 | |
| 162 | def __setitem__(self, key, value): |
| 163 | try: |
| 164 | self._dict[key] = value |
| 165 | except TypeError: |
| 166 | for i, (k, v) in enumerate(self._pairs): |
| 167 | if k == key: |
| 168 | self._pairs[i] = (key, value) |
| 169 | break |
| 170 | else: |
| 171 | self._pairs.append((key, value)) |
| 172 | |
| 173 | def __getitem__(self, key): |
| 174 | try: |
| 175 | return self._dict[key] |
| 176 | except TypeError: |
| 177 | pass |
| 178 | for k, v in self._pairs: |
| 179 | if k == key: |
| 180 | return v |
| 181 | raise KeyError(key) |
| 182 | |
| 183 | def pop(self, key, *args): |
| 184 | try: |
| 185 | if key in self._dict: |
| 186 | return self._dict.pop(key) |
| 187 | except TypeError: |
| 188 | for i, (k, v) in enumerate(self._pairs): |
| 189 | if k == key: |
| 190 | del self._pairs[i] |
| 191 | return v |
| 192 | if args: |
| 193 | return args[0] |
| 194 | raise KeyError(key) |
| 195 | |
| 196 | def __iter__(self): |
| 197 | yield from self._dict |
| 198 | for k, v in self._pairs: |
| 199 | yield k |
| 200 | |
| 201 | |
| 202 | class CallbackRegistry: |
no outgoing calls
no test coverage detected
searching dependent graphs…