Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to associate additional data with an object owned by other parts of an application without adding attributes to those
| 354 | |
| 355 | |
| 356 | class WeakKeyDictionary(_collections_abc.MutableMapping): |
| 357 | """ Mapping class that references keys weakly. |
| 358 | |
| 359 | Entries in the dictionary will be discarded when there is no |
| 360 | longer a strong reference to the key. This can be used to |
| 361 | associate additional data with an object owned by other parts of |
| 362 | an application without adding attributes to those objects. This |
| 363 | can be especially useful with objects that override attribute |
| 364 | accesses. |
| 365 | """ |
| 366 | |
| 367 | def __init__(self, dict=None): |
| 368 | self.data = {} |
| 369 | def remove(k, selfref=ref(self)): |
| 370 | self = selfref() |
| 371 | if self is not None: |
| 372 | if self._iterating: |
| 373 | self._pending_removals.append(k) |
| 374 | else: |
| 375 | try: |
| 376 | del self.data[k] |
| 377 | except KeyError: |
| 378 | pass |
| 379 | self._remove = remove |
| 380 | # A list of dead weakrefs (keys to be removed) |
| 381 | self._pending_removals = [] |
| 382 | self._iterating = set() |
| 383 | self._dirty_len = False |
| 384 | if dict is not None: |
| 385 | self.update(dict) |
| 386 | |
| 387 | def _commit_removals(self): |
| 388 | # NOTE: We don't need to call this method before mutating the dict, |
| 389 | # because a dead weakref never compares equal to a live weakref, |
| 390 | # even if they happened to refer to equal objects. |
| 391 | # However, it means keys may already have been removed. |
| 392 | pop = self._pending_removals.pop |
| 393 | d = self.data |
| 394 | while True: |
| 395 | try: |
| 396 | key = pop() |
| 397 | except IndexError: |
| 398 | return |
| 399 | |
| 400 | try: |
| 401 | del d[key] |
| 402 | except KeyError: |
| 403 | pass |
| 404 | |
| 405 | def _scrub_removals(self): |
| 406 | d = self.data |
| 407 | self._pending_removals = [k for k in self._pending_removals if k in d] |
| 408 | self._dirty_len = False |
| 409 | |
| 410 | def __delitem__(self, key): |
| 411 | self._dirty_len = True |
| 412 | del self.data[ref(key)] |
| 413 |