Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists anymore
| 90 | |
| 91 | |
| 92 | class WeakValueDictionary(_collections_abc.MutableMapping): |
| 93 | """Mapping class that references values weakly. |
| 94 | |
| 95 | Entries in the dictionary will be discarded when no strong |
| 96 | reference to the value exists anymore |
| 97 | """ |
| 98 | # We inherit the constructor without worrying about the input |
| 99 | # dictionary; since it uses our .update() method, we get the right |
| 100 | # checks (if the other dictionary is a WeakValueDictionary, |
| 101 | # objects are unwrapped on the way out, and we always wrap on the |
| 102 | # way in). |
| 103 | |
| 104 | def __init__(self, other=(), /, **kw): |
| 105 | def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref): |
| 106 | self = selfref() |
| 107 | if self is not None: |
| 108 | if self._iterating: |
| 109 | self._pending_removals.append(wr.key) |
| 110 | else: |
| 111 | # Atomic removal is necessary since this function |
| 112 | # can be called asynchronously by the GC |
| 113 | _atomic_removal(self.data, wr.key) |
| 114 | self._remove = remove |
| 115 | # A list of keys to be removed |
| 116 | self._pending_removals = [] |
| 117 | self._iterating = set() |
| 118 | self.data = {} |
| 119 | self.update(other, **kw) |
| 120 | |
| 121 | def _commit_removals(self, _atomic_removal=_remove_dead_weakref): |
| 122 | pop = self._pending_removals.pop |
| 123 | d = self.data |
| 124 | # We shouldn't encounter any KeyError, because this method should |
| 125 | # always be called *before* mutating the dict. |
| 126 | while True: |
| 127 | try: |
| 128 | key = pop() |
| 129 | except IndexError: |
| 130 | return |
| 131 | _atomic_removal(d, key) |
| 132 | |
| 133 | def __getitem__(self, key): |
| 134 | if self._pending_removals: |
| 135 | self._commit_removals() |
| 136 | o = self.data[key]() |
| 137 | if o is None: |
| 138 | raise KeyError(key) |
| 139 | else: |
| 140 | return o |
| 141 | |
| 142 | def __delitem__(self, key): |
| 143 | if self._pending_removals: |
| 144 | self._commit_removals() |
| 145 | del self.data[key] |
| 146 | |
| 147 | def __len__(self): |
| 148 | if self._pending_removals: |
| 149 | self._commit_removals() |