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 | # Atomic removal is necessary since this function |
| 109 | # can be called asynchronously by the GC |
| 110 | _atomic_removal(self.data, wr.key) |
| 111 | self._remove = remove |
| 112 | self.data = {} |
| 113 | self.update(other, **kw) |
| 114 | |
| 115 | def __getitem__(self, key): |
| 116 | o = self.data[key]() |
| 117 | if o is None: |
| 118 | raise KeyError(key) |
| 119 | else: |
| 120 | return o |
| 121 | |
| 122 | def __delitem__(self, key): |
| 123 | del self.data[key] |
| 124 | |
| 125 | def __len__(self): |
| 126 | return len(self.data) |
| 127 | |
| 128 | def __contains__(self, key): |
| 129 | try: |
| 130 | o = self.data[key]() |
| 131 | except KeyError: |
| 132 | return False |
| 133 | return o is not None |
| 134 | |
| 135 | def __repr__(self): |
| 136 | return "<%s at %#x>" % (self.__class__.__name__, id(self)) |
| 137 | |
| 138 | def __setitem__(self, key, value): |
| 139 | self.data[key] = KeyedRef(value, self._remove, key) |
| 140 | |
| 141 | def copy(self): |
| 142 | new = WeakValueDictionary() |
| 143 | for key, wr in self.data.copy().items(): |
| 144 | o = wr() |
| 145 | if o is not None: |
| 146 | new[key] = o |
| 147 | return new |
| 148 | |
| 149 | __copy__ = copy |
no outgoing calls
no test coverage detected
searching dependent graphs…