Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 1 | """Weak reference support for Python. |
| 2 | |
| 3 | This module is an implementation of PEP 205: |
| 4 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 5 | http://www.python.org/dev/peps/pep-0205/ |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 6 | """ |
| 7 | |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 8 | # Naming convention: Variables named "wr" are weak reference objects; |
| 9 | # they are called this instead of "ref" to avoid name collisions with |
| 10 | # the module-global ref() function imported from _weakref. |
| 11 | |
Andrew M. Kuchling | 33ad28b | 2004-08-31 11:38:12 +0000 | [diff] [blame] | 12 | from _weakref import ( |
| 13 | getweakrefcount, |
| 14 | getweakrefs, |
| 15 | ref, |
| 16 | proxy, |
| 17 | CallableProxyType, |
| 18 | ProxyType, |
| 19 | ReferenceType) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 20 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 21 | from _weakrefset import WeakSet, _IterationGuard |
Fred Drake | e029242 | 2001-10-05 21:54:09 +0000 | [diff] [blame] | 22 | |
Brett Cannon | 663fffa | 2009-03-25 23:31:22 +0000 | [diff] [blame] | 23 | import collections # Import after _weakref to avoid circular import. |
Richard Oudkerk | 7a3dae05 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 24 | import sys |
| 25 | import itertools |
| 26 | import atexit |
Brett Cannon | 663fffa | 2009-03-25 23:31:22 +0000 | [diff] [blame] | 27 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 28 | ProxyTypes = (ProxyType, CallableProxyType) |
| 29 | |
Fred Drake | 9a9d219 | 2001-04-10 19:11:23 +0000 | [diff] [blame] | 30 | __all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs", |
Gregory P. Smith | 7d10c2b | 2008-08-18 03:41:46 +0000 | [diff] [blame] | 31 | "WeakKeyDictionary", "ReferenceType", "ProxyType", |
Raymond Hettinger | 93fa608 | 2008-02-05 00:20:01 +0000 | [diff] [blame] | 32 | "CallableProxyType", "ProxyTypes", "WeakValueDictionary", |
Richard Oudkerk | 7a3dae05 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 33 | "WeakSet", "WeakMethod", "finalize"] |
Antoine Pitrou | c3afba1 | 2012-11-17 18:57:38 +0100 | [diff] [blame] | 34 | |
| 35 | |
| 36 | class WeakMethod(ref): |
| 37 | """ |
| 38 | A custom `weakref.ref` subclass which simulates a weak reference to |
| 39 | a bound method, working around the lifetime problem of bound methods. |
| 40 | """ |
| 41 | |
| 42 | __slots__ = "_func_ref", "_meth_type", "_alive", "__weakref__" |
| 43 | |
| 44 | def __new__(cls, meth, callback=None): |
| 45 | try: |
| 46 | obj = meth.__self__ |
| 47 | func = meth.__func__ |
| 48 | except AttributeError: |
| 49 | raise TypeError("argument should be a bound method, not {}" |
| 50 | .format(type(meth))) from None |
| 51 | def _cb(arg): |
| 52 | # The self-weakref trick is needed to avoid creating a reference |
| 53 | # cycle. |
| 54 | self = self_wr() |
| 55 | if self._alive: |
| 56 | self._alive = False |
| 57 | if callback is not None: |
| 58 | callback(self) |
| 59 | self = ref.__new__(cls, obj, _cb) |
| 60 | self._func_ref = ref(func, _cb) |
| 61 | self._meth_type = type(meth) |
| 62 | self._alive = True |
| 63 | self_wr = ref(self) |
| 64 | return self |
| 65 | |
| 66 | def __call__(self): |
| 67 | obj = super().__call__() |
| 68 | func = self._func_ref() |
| 69 | if obj is None or func is None: |
| 70 | return None |
| 71 | return self._meth_type(func, obj) |
| 72 | |
| 73 | def __eq__(self, other): |
| 74 | if isinstance(other, WeakMethod): |
| 75 | if not self._alive or not other._alive: |
| 76 | return self is other |
| 77 | return ref.__eq__(self, other) and self._func_ref == other._func_ref |
| 78 | return False |
| 79 | |
| 80 | def __ne__(self, other): |
| 81 | if isinstance(other, WeakMethod): |
| 82 | if not self._alive or not other._alive: |
| 83 | return self is not other |
| 84 | return ref.__ne__(self, other) or self._func_ref != other._func_ref |
| 85 | return True |
| 86 | |
| 87 | __hash__ = ref.__hash__ |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 88 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 89 | |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 90 | class WeakValueDictionary(collections.MutableMapping): |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 91 | """Mapping class that references values weakly. |
| 92 | |
| 93 | Entries in the dictionary will be discarded when no strong |
| 94 | reference to the value exists anymore |
| 95 | """ |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 96 | # We inherit the constructor without worrying about the input |
| 97 | # dictionary; since it uses our .update() method, we get the right |
Fred Drake | 9d2c85d | 2001-03-01 03:06:03 +0000 | [diff] [blame] | 98 | # checks (if the other dictionary is a WeakValueDictionary, |
| 99 | # objects are unwrapped on the way out, and we always wrap on the |
| 100 | # way in). |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 101 | |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 102 | def __init__(self, *args, **kw): |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 103 | def remove(wr, selfref=ref(self)): |
| 104 | self = selfref() |
| 105 | if self is not None: |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 106 | if self._iterating: |
| 107 | self._pending_removals.append(wr.key) |
| 108 | else: |
| 109 | del self.data[wr.key] |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 110 | self._remove = remove |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 111 | # A list of keys to be removed |
| 112 | self._pending_removals = [] |
| 113 | self._iterating = set() |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 114 | self.data = d = {} |
Antoine Pitrou | c06de47 | 2009-05-30 21:04:26 +0000 | [diff] [blame] | 115 | self.update(*args, **kw) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 116 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 117 | def _commit_removals(self): |
| 118 | l = self._pending_removals |
| 119 | d = self.data |
| 120 | # We shouldn't encounter any KeyError, because this method should |
| 121 | # always be called *before* mutating the dict. |
| 122 | while l: |
| 123 | del d[l.pop()] |
| 124 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 125 | def __getitem__(self, key): |
Fred Drake | 4fd06e0 | 2001-08-03 04:11:27 +0000 | [diff] [blame] | 126 | o = self.data[key]() |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 127 | if o is None: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 128 | raise KeyError(key) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 129 | else: |
| 130 | return o |
| 131 | |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 132 | def __delitem__(self, key): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 133 | if self._pending_removals: |
| 134 | self._commit_removals() |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 135 | del self.data[key] |
| 136 | |
| 137 | def __len__(self): |
Antoine Pitrou | bbe2f60 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 138 | return len(self.data) - len(self._pending_removals) |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 139 | |
Raymond Hettinger | 6114679 | 2004-08-19 21:32:06 +0000 | [diff] [blame] | 140 | def __contains__(self, key): |
| 141 | try: |
| 142 | o = self.data[key]() |
| 143 | except KeyError: |
| 144 | return False |
| 145 | return o is not None |
| 146 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 147 | def __repr__(self): |
Fred Drake | 9d2c85d | 2001-03-01 03:06:03 +0000 | [diff] [blame] | 148 | return "<WeakValueDictionary at %s>" % id(self) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 149 | |
| 150 | def __setitem__(self, key, value): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 151 | if self._pending_removals: |
| 152 | self._commit_removals() |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 153 | self.data[key] = KeyedRef(value, self._remove, key) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 154 | |
| 155 | def copy(self): |
Fred Drake | 9d2c85d | 2001-03-01 03:06:03 +0000 | [diff] [blame] | 156 | new = WeakValueDictionary() |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 157 | for key, wr in self.data.items(): |
| 158 | o = wr() |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 159 | if o is not None: |
| 160 | new[key] = o |
Fred Drake | 9d2c85d | 2001-03-01 03:06:03 +0000 | [diff] [blame] | 161 | return new |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 162 | |
Antoine Pitrou | 6e61006 | 2009-05-15 17:04:50 +0000 | [diff] [blame] | 163 | __copy__ = copy |
| 164 | |
| 165 | def __deepcopy__(self, memo): |
| 166 | from copy import deepcopy |
| 167 | new = self.__class__() |
| 168 | for key, wr in self.data.items(): |
| 169 | o = wr() |
| 170 | if o is not None: |
| 171 | new[deepcopy(key, memo)] = o |
| 172 | return new |
| 173 | |
Fred Drake | 1d9e4b7 | 2001-04-16 17:34:48 +0000 | [diff] [blame] | 174 | def get(self, key, default=None): |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 175 | try: |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 176 | wr = self.data[key] |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 177 | except KeyError: |
| 178 | return default |
| 179 | else: |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 180 | o = wr() |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 181 | if o is None: |
| 182 | # This should only happen |
| 183 | return default |
| 184 | else: |
| 185 | return o |
| 186 | |
| 187 | def items(self): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 188 | with _IterationGuard(self): |
| 189 | for k, wr in self.data.items(): |
| 190 | v = wr() |
| 191 | if v is not None: |
| 192 | yield k, v |
Fred Drake | 101209d | 2001-05-02 05:43:09 +0000 | [diff] [blame] | 193 | |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 194 | def keys(self): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 195 | with _IterationGuard(self): |
| 196 | for k, wr in self.data.items(): |
| 197 | if wr() is not None: |
| 198 | yield k |
Raymond Hettinger | 6114679 | 2004-08-19 21:32:06 +0000 | [diff] [blame] | 199 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 200 | __iter__ = keys |
Fred Drake | 101209d | 2001-05-02 05:43:09 +0000 | [diff] [blame] | 201 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 202 | def itervaluerefs(self): |
| 203 | """Return an iterator that yields the weak references to the values. |
| 204 | |
| 205 | The references are not guaranteed to be 'live' at the time |
| 206 | they are used, so the result of calling the references needs |
| 207 | to be checked before being used. This can be used to avoid |
| 208 | creating references that will cause the garbage collector to |
| 209 | keep the values around longer than needed. |
| 210 | |
| 211 | """ |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 212 | with _IterationGuard(self): |
Philip Jenvey | 4993cc0 | 2012-10-01 12:53:43 -0700 | [diff] [blame] | 213 | yield from self.data.values() |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 214 | |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 215 | def values(self): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 216 | with _IterationGuard(self): |
| 217 | for wr in self.data.values(): |
| 218 | obj = wr() |
| 219 | if obj is not None: |
| 220 | yield obj |
Fred Drake | 101209d | 2001-05-02 05:43:09 +0000 | [diff] [blame] | 221 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 222 | def popitem(self): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 223 | if self._pending_removals: |
| 224 | self._commit_removals() |
Georg Brandl | bd87d08 | 2010-12-03 07:49:09 +0000 | [diff] [blame] | 225 | while True: |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 226 | key, wr = self.data.popitem() |
| 227 | o = wr() |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 228 | if o is not None: |
| 229 | return key, o |
| 230 | |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 231 | def pop(self, key, *args): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 232 | if self._pending_removals: |
| 233 | self._commit_removals() |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 234 | try: |
| 235 | o = self.data.pop(key)() |
| 236 | except KeyError: |
| 237 | if args: |
| 238 | return args[0] |
| 239 | raise |
| 240 | if o is None: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 241 | raise KeyError(key) |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 242 | else: |
| 243 | return o |
| 244 | |
Walter Dörwald | 80ce6dd | 2004-05-27 18:16:25 +0000 | [diff] [blame] | 245 | def setdefault(self, key, default=None): |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 246 | try: |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 247 | wr = self.data[key] |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 248 | except KeyError: |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 249 | if self._pending_removals: |
| 250 | self._commit_removals() |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 251 | self.data[key] = KeyedRef(default, self._remove, key) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 252 | return default |
| 253 | else: |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 254 | return wr() |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 255 | |
Raymond Hettinger | 31017ae | 2004-03-04 08:25:44 +0000 | [diff] [blame] | 256 | def update(self, dict=None, **kwargs): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 257 | if self._pending_removals: |
| 258 | self._commit_removals() |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 259 | d = self.data |
Raymond Hettinger | 31017ae | 2004-03-04 08:25:44 +0000 | [diff] [blame] | 260 | if dict is not None: |
| 261 | if not hasattr(dict, "items"): |
| 262 | dict = type({})(dict) |
| 263 | for key, o in dict.items(): |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 264 | d[key] = KeyedRef(o, self._remove, key) |
Raymond Hettinger | 31017ae | 2004-03-04 08:25:44 +0000 | [diff] [blame] | 265 | if len(kwargs): |
| 266 | self.update(kwargs) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 267 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 268 | def valuerefs(self): |
| 269 | """Return a list of weak references to the values. |
| 270 | |
| 271 | The references are not guaranteed to be 'live' at the time |
| 272 | they are used, so the result of calling the references needs |
| 273 | to be checked before being used. This can be used to avoid |
| 274 | creating references that will cause the garbage collector to |
| 275 | keep the values around longer than needed. |
| 276 | |
| 277 | """ |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 278 | return list(self.data.values()) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 279 | |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 280 | |
| 281 | class KeyedRef(ref): |
| 282 | """Specialized reference that includes a key corresponding to the value. |
| 283 | |
| 284 | This is used in the WeakValueDictionary to avoid having to create |
| 285 | a function object for each key stored in the mapping. A shared |
| 286 | callback object can use the 'key' attribute of a KeyedRef instead |
| 287 | of getting a reference to the key from an enclosing scope. |
| 288 | |
| 289 | """ |
| 290 | |
| 291 | __slots__ = "key", |
| 292 | |
| 293 | def __new__(type, ob, callback, key): |
| 294 | self = ref.__new__(type, ob, callback) |
| 295 | self.key = key |
| 296 | return self |
| 297 | |
| 298 | def __init__(self, ob, callback, key): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 299 | super().__init__(ob, callback) |
Fred Drake | 746fe0f | 2001-09-28 19:01:26 +0000 | [diff] [blame] | 300 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 301 | |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 302 | class WeakKeyDictionary(collections.MutableMapping): |
Fred Drake | bd7f818 | 2001-04-19 16:26:06 +0000 | [diff] [blame] | 303 | """ Mapping class that references keys weakly. |
| 304 | |
| 305 | Entries in the dictionary will be discarded when there is no |
| 306 | longer a strong reference to the key. This can be used to |
| 307 | associate additional data with an object owned by other parts of |
| 308 | an application without adding attributes to those objects. This |
| 309 | can be especially useful with objects that override attribute |
| 310 | accesses. |
| 311 | """ |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 312 | |
| 313 | def __init__(self, dict=None): |
| 314 | self.data = {} |
Fred Drake | 746fe0f | 2001-09-28 19:01:26 +0000 | [diff] [blame] | 315 | def remove(k, selfref=ref(self)): |
| 316 | self = selfref() |
| 317 | if self is not None: |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 318 | if self._iterating: |
| 319 | self._pending_removals.append(k) |
| 320 | else: |
| 321 | del self.data[k] |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 322 | self._remove = remove |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 323 | # A list of dead weakrefs (keys to be removed) |
| 324 | self._pending_removals = [] |
| 325 | self._iterating = set() |
| 326 | if dict is not None: |
| 327 | self.update(dict) |
| 328 | |
| 329 | def _commit_removals(self): |
| 330 | # NOTE: We don't need to call this method before mutating the dict, |
| 331 | # because a dead weakref never compares equal to a live weakref, |
| 332 | # even if they happened to refer to equal objects. |
| 333 | # However, it means keys may already have been removed. |
| 334 | l = self._pending_removals |
| 335 | d = self.data |
| 336 | while l: |
| 337 | try: |
| 338 | del d[l.pop()] |
| 339 | except KeyError: |
| 340 | pass |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 341 | |
Fred Drake | b663a2c | 2001-09-06 14:51:01 +0000 | [diff] [blame] | 342 | def __delitem__(self, key): |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 343 | del self.data[ref(key)] |
Fred Drake | b663a2c | 2001-09-06 14:51:01 +0000 | [diff] [blame] | 344 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 345 | def __getitem__(self, key): |
| 346 | return self.data[ref(key)] |
| 347 | |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 348 | def __len__(self): |
Antoine Pitrou | bbe2f60 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 349 | return len(self.data) - len(self._pending_removals) |
Raymond Hettinger | 7ac6095 | 2008-02-05 01:15:57 +0000 | [diff] [blame] | 350 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 351 | def __repr__(self): |
| 352 | return "<WeakKeyDictionary at %s>" % id(self) |
| 353 | |
| 354 | def __setitem__(self, key, value): |
| 355 | self.data[ref(key, self._remove)] = value |
| 356 | |
| 357 | def copy(self): |
| 358 | new = WeakKeyDictionary() |
| 359 | for key, value in self.data.items(): |
| 360 | o = key() |
| 361 | if o is not None: |
| 362 | new[o] = value |
Fred Drake | 9d2c85d | 2001-03-01 03:06:03 +0000 | [diff] [blame] | 363 | return new |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 364 | |
Antoine Pitrou | 6e61006 | 2009-05-15 17:04:50 +0000 | [diff] [blame] | 365 | __copy__ = copy |
| 366 | |
| 367 | def __deepcopy__(self, memo): |
| 368 | from copy import deepcopy |
| 369 | new = self.__class__() |
| 370 | for key, value in self.data.items(): |
| 371 | o = key() |
| 372 | if o is not None: |
| 373 | new[o] = deepcopy(value, memo) |
| 374 | return new |
| 375 | |
Fred Drake | 1d9e4b7 | 2001-04-16 17:34:48 +0000 | [diff] [blame] | 376 | def get(self, key, default=None): |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 377 | return self.data.get(ref(key),default) |
| 378 | |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 379 | def __contains__(self, key): |
| 380 | try: |
| 381 | wr = ref(key) |
| 382 | except TypeError: |
Georg Brandl | bd87d08 | 2010-12-03 07:49:09 +0000 | [diff] [blame] | 383 | return False |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 384 | return wr in self.data |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 385 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 386 | def items(self): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 387 | with _IterationGuard(self): |
| 388 | for wr, value in self.data.items(): |
| 389 | key = wr() |
| 390 | if key is not None: |
| 391 | yield key, value |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 392 | |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 393 | def keys(self): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 394 | with _IterationGuard(self): |
| 395 | for wr in self.data: |
| 396 | obj = wr() |
| 397 | if obj is not None: |
| 398 | yield obj |
Raymond Hettinger | 6114679 | 2004-08-19 21:32:06 +0000 | [diff] [blame] | 399 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 400 | __iter__ = keys |
Fred Drake | 101209d | 2001-05-02 05:43:09 +0000 | [diff] [blame] | 401 | |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 402 | def values(self): |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 403 | with _IterationGuard(self): |
| 404 | for wr, value in self.data.items(): |
| 405 | if wr() is not None: |
| 406 | yield value |
Fred Drake | 101209d | 2001-05-02 05:43:09 +0000 | [diff] [blame] | 407 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 408 | def keyrefs(self): |
| 409 | """Return a list of weak references to the keys. |
| 410 | |
| 411 | The references are not guaranteed to be 'live' at the time |
| 412 | they are used, so the result of calling the references needs |
| 413 | to be checked before being used. This can be used to avoid |
| 414 | creating references that will cause the garbage collector to |
| 415 | keep the keys around longer than needed. |
| 416 | |
| 417 | """ |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 418 | return list(self.data) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 419 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 420 | def popitem(self): |
Georg Brandl | bd87d08 | 2010-12-03 07:49:09 +0000 | [diff] [blame] | 421 | while True: |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 422 | key, value = self.data.popitem() |
| 423 | o = key() |
| 424 | if o is not None: |
| 425 | return o, value |
| 426 | |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 427 | def pop(self, key, *args): |
| 428 | return self.data.pop(ref(key), *args) |
| 429 | |
Walter Dörwald | 80ce6dd | 2004-05-27 18:16:25 +0000 | [diff] [blame] | 430 | def setdefault(self, key, default=None): |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 431 | return self.data.setdefault(ref(key, self._remove),default) |
| 432 | |
Raymond Hettinger | 31017ae | 2004-03-04 08:25:44 +0000 | [diff] [blame] | 433 | def update(self, dict=None, **kwargs): |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 434 | d = self.data |
Raymond Hettinger | 31017ae | 2004-03-04 08:25:44 +0000 | [diff] [blame] | 435 | if dict is not None: |
| 436 | if not hasattr(dict, "items"): |
| 437 | dict = type({})(dict) |
| 438 | for key, value in dict.items(): |
| 439 | d[ref(key, self._remove)] = value |
| 440 | if len(kwargs): |
| 441 | self.update(kwargs) |
Richard Oudkerk | 7a3dae05 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 442 | |
| 443 | |
| 444 | class finalize: |
| 445 | """Class for finalization of weakrefable objects |
| 446 | |
| 447 | finalize(obj, func, *args, **kwargs) returns a callable finalizer |
| 448 | object which will be called when obj is garbage collected. The |
| 449 | first time the finalizer is called it evaluates func(*arg, **kwargs) |
| 450 | and returns the result. After this the finalizer is dead, and |
| 451 | calling it just returns None. |
| 452 | |
| 453 | When the program exits any remaining finalizers for which the |
| 454 | atexit attribute is true will be run in reverse order of creation. |
| 455 | By default atexit is true. |
| 456 | """ |
| 457 | |
| 458 | # Finalizer objects don't have any state of their own. They are |
| 459 | # just used as keys to lookup _Info objects in the registry. This |
| 460 | # ensures that they cannot be part of a ref-cycle. |
| 461 | |
| 462 | __slots__ = () |
| 463 | _registry = {} |
| 464 | _shutdown = False |
| 465 | _index_iter = itertools.count() |
| 466 | _dirty = False |
| 467 | |
| 468 | class _Info: |
| 469 | __slots__ = ("weakref", "func", "args", "kwargs", "atexit", "index") |
| 470 | |
| 471 | def __init__(self, obj, func, *args, **kwargs): |
| 472 | info = self._Info() |
| 473 | info.weakref = ref(obj, self) |
| 474 | info.func = func |
| 475 | info.args = args |
| 476 | info.kwargs = kwargs or None |
| 477 | info.atexit = True |
| 478 | info.index = next(self._index_iter) |
| 479 | self._registry[self] = info |
| 480 | finalize._dirty = True |
| 481 | |
| 482 | def __call__(self, _=None): |
| 483 | """If alive then mark as dead and return func(*args, **kwargs); |
| 484 | otherwise return None""" |
| 485 | info = self._registry.pop(self, None) |
| 486 | if info and not self._shutdown: |
| 487 | return info.func(*info.args, **(info.kwargs or {})) |
| 488 | |
| 489 | def detach(self): |
| 490 | """If alive then mark as dead and return (obj, func, args, kwargs); |
| 491 | otherwise return None""" |
| 492 | info = self._registry.get(self) |
| 493 | obj = info and info.weakref() |
| 494 | if obj is not None and self._registry.pop(self, None): |
| 495 | return (obj, info.func, info.args, info.kwargs or {}) |
| 496 | |
| 497 | def peek(self): |
| 498 | """If alive then return (obj, func, args, kwargs); |
| 499 | otherwise return None""" |
| 500 | info = self._registry.get(self) |
| 501 | obj = info and info.weakref() |
| 502 | if obj is not None: |
| 503 | return (obj, info.func, info.args, info.kwargs or {}) |
| 504 | |
| 505 | @property |
| 506 | def alive(self): |
| 507 | """Whether finalizer is alive""" |
| 508 | return self in self._registry |
| 509 | |
| 510 | @property |
| 511 | def atexit(self): |
| 512 | """Whether finalizer should be called at exit""" |
| 513 | info = self._registry.get(self) |
| 514 | return bool(info) and info.atexit |
| 515 | |
| 516 | @atexit.setter |
| 517 | def atexit(self, value): |
| 518 | info = self._registry.get(self) |
| 519 | if info: |
| 520 | info.atexit = bool(value) |
| 521 | |
| 522 | def __repr__(self): |
| 523 | info = self._registry.get(self) |
| 524 | obj = info and info.weakref() |
| 525 | if obj is None: |
| 526 | return '<%s object at %#x; dead>' % (type(self).__name__, id(self)) |
| 527 | else: |
| 528 | return '<%s object at %#x; for %r at %#x>' % \ |
| 529 | (type(self).__name__, id(self), type(obj).__name__, id(obj)) |
| 530 | |
| 531 | @classmethod |
| 532 | def _select_for_exit(cls): |
| 533 | # Return live finalizers marked for exit, oldest first |
| 534 | L = [(f,i) for (f,i) in cls._registry.items() if i.atexit] |
| 535 | L.sort(key=lambda item:item[1].index) |
| 536 | return [f for (f,i) in L] |
| 537 | |
| 538 | @classmethod |
| 539 | def _exitfunc(cls): |
| 540 | # At shutdown invoke finalizers for which atexit is true. |
| 541 | # This is called once all other non-daemonic threads have been |
| 542 | # joined. |
| 543 | reenable_gc = False |
| 544 | try: |
| 545 | if cls._registry: |
| 546 | import gc |
| 547 | if gc.isenabled(): |
| 548 | reenable_gc = True |
| 549 | gc.disable() |
| 550 | pending = None |
| 551 | while True: |
| 552 | if pending is None or finalize._dirty: |
| 553 | pending = cls._select_for_exit() |
| 554 | finalize._dirty = False |
| 555 | if not pending: |
| 556 | break |
| 557 | f = pending.pop() |
| 558 | try: |
| 559 | # gc is disabled, so (assuming no daemonic |
| 560 | # threads) the following is the only line in |
| 561 | # this function which might trigger creation |
| 562 | # of a new finalizer |
| 563 | f() |
| 564 | except Exception: |
| 565 | sys.excepthook(*sys.exc_info()) |
| 566 | assert f not in cls._registry |
| 567 | finally: |
| 568 | # prevent any more finalizers from executing during shutdown |
| 569 | finalize._shutdown = True |
| 570 | if reenable_gc: |
| 571 | gc.enable() |
| 572 | |
| 573 | atexit.register(finalize._exitfunc) |