Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`weakref` --- Weak references |
| 2 | ================================== |
| 3 | |
| 4 | .. module:: weakref |
| 5 | :synopsis: Support for weak references and weak dictionaries. |
| 6 | .. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 7 | .. moduleauthor:: Neil Schemenauer <nas@arctrix.com> |
| 8 | .. moduleauthor:: Martin von Lรถwis <martin@loewis.home.cs.tu-berlin.de> |
| 9 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 10 | |
Raymond Hettinger | 469271d | 2011-01-27 20:38:46 +0000 | [diff] [blame] | 11 | **Source code:** :source:`Lib/weakref.py` |
| 12 | |
| 13 | -------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 15 | The :mod:`weakref` module allows the Python programmer to create :dfn:`weak |
| 16 | references` to objects. |
| 17 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 18 | .. When making changes to the examples in this file, be sure to update |
| 19 | Lib/test/test_weakref.py::libreftest too! |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 20 | |
| 21 | In the following, the term :dfn:`referent` means the object which is referred to |
| 22 | by a weak reference. |
| 23 | |
| 24 | A weak reference to an object is not enough to keep the object alive: when the |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 25 | only remaining references to a referent are weak references, |
| 26 | :term:`garbage collection` is free to destroy the referent and reuse its memory |
Antoine Pitrou | 9439f04 | 2012-08-21 00:07:07 +0200 | [diff] [blame] | 27 | for something else. However, until the object is actually destroyed the weak |
| 28 | reference may return the object even if there are no strong references to it. |
| 29 | |
| 30 | A primary use for weak references is to implement caches or |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 31 | mappings holding large objects, where it's desired that a large object not be |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 32 | kept alive solely because it appears in a cache or mapping. |
| 33 | |
| 34 | For example, if you have a number of large binary image objects, you may wish to |
| 35 | associate a name with each. If you used a Python dictionary to map names to |
| 36 | images, or images to names, the image objects would remain alive just because |
| 37 | they appeared as values or keys in the dictionaries. The |
| 38 | :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by |
| 39 | the :mod:`weakref` module are an alternative, using weak references to construct |
| 40 | mappings that don't keep objects alive solely because they appear in the mapping |
| 41 | objects. If, for example, an image object is a value in a |
| 42 | :class:`WeakValueDictionary`, then when the last remaining references to that |
| 43 | image object are the weak references held by weak mappings, garbage collection |
| 44 | can reclaim the object, and its corresponding entries in weak mappings are |
| 45 | simply deleted. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 46 | |
| 47 | :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references |
| 48 | in their implementation, setting up callback functions on the weak references |
| 49 | that notify the weak dictionaries when a key or value has been reclaimed by |
Georg Brandl | 3b8cb17 | 2007-10-23 06:26:46 +0000 | [diff] [blame] | 50 | garbage collection. :class:`WeakSet` implements the :class:`set` interface, |
| 51 | but keeps weak references to its elements, just like a |
| 52 | :class:`WeakKeyDictionary` does. |
| 53 | |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 54 | :class:`finalize` provides a straight forward way to register a |
| 55 | cleanup function to be called when an object is garbage collected. |
| 56 | This is simpler to use than setting up a callback function on a raw |
Nick Coghlan | be57ab8 | 2013-09-22 21:26:30 +1000 | [diff] [blame^] | 57 | weak reference, since the module automatically ensures that the finalizer |
| 58 | remains alive until the object is collected. |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 59 | |
| 60 | Most programs should find that using one of these weak container types |
| 61 | or :class:`finalize` is all they need -- it's not usually necessary to |
| 62 | create your own weak references directly. The low-level machinery is |
| 63 | exposed by the :mod:`weakref` module for the benefit of advanced uses. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 64 | |
| 65 | Not all objects can be weakly referenced; those objects which can include class |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 66 | instances, functions written in Python (but not in C), instance methods, sets, |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 67 | frozensets, some :term:`file objects <file object>`, :term:`generator`\s, type |
| 68 | objects, sockets, arrays, deques, regular expression pattern objects, and code |
| 69 | objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 70 | |
Benjamin Peterson | bec4d57 | 2009-10-10 01:16:07 +0000 | [diff] [blame] | 71 | .. versionchanged:: 3.2 |
Collin Winter | 4222e9c | 2010-03-18 22:46:40 +0000 | [diff] [blame] | 72 | Added support for thread.lock, threading.Lock, and code objects. |
Benjamin Peterson | bec4d57 | 2009-10-10 01:16:07 +0000 | [diff] [blame] | 73 | |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 74 | Several built-in types such as :class:`list` and :class:`dict` do not directly |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 75 | support weak references but can add support through subclassing:: |
| 76 | |
| 77 | class Dict(dict): |
| 78 | pass |
| 79 | |
Christian Heimes | c3f30c4 | 2008-02-22 16:37:40 +0000 | [diff] [blame] | 80 | obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 81 | |
Benjamin Peterson | 905982b | 2010-05-08 15:26:30 +0000 | [diff] [blame] | 82 | Other built-in types such as :class:`tuple` and :class:`int` do not support weak |
| 83 | references even when subclassed (This is an implementation detail and may be |
| 84 | different across various Python implementations.). |
Georg Brandl | ff8c1e5 | 2009-10-21 07:17:48 +0000 | [diff] [blame] | 85 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 86 | Extension types can easily be made to support weak references; see |
| 87 | :ref:`weakref-support`. |
| 88 | |
| 89 | |
| 90 | .. class:: ref(object[, callback]) |
| 91 | |
| 92 | Return a weak reference to *object*. The original object can be retrieved by |
| 93 | calling the reference object if the referent is still alive; if the referent is |
| 94 | no longer alive, calling the reference object will cause :const:`None` to be |
| 95 | returned. If *callback* is provided and not :const:`None`, and the returned |
| 96 | weakref object is still alive, the callback will be called when the object is |
| 97 | about to be finalized; the weak reference object will be passed as the only |
| 98 | parameter to the callback; the referent will no longer be available. |
| 99 | |
| 100 | It is allowable for many weak references to be constructed for the same object. |
| 101 | Callbacks registered for each weak reference will be called from the most |
| 102 | recently registered callback to the oldest registered callback. |
| 103 | |
| 104 | Exceptions raised by the callback will be noted on the standard error output, |
| 105 | but cannot be propagated; they are handled in exactly the same way as exceptions |
| 106 | raised from an object's :meth:`__del__` method. |
| 107 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 108 | Weak references are :term:`hashable` if the *object* is hashable. They will |
| 109 | maintain their hash value even after the *object* was deleted. If |
| 110 | :func:`hash` is called the first time only after the *object* was deleted, |
| 111 | the call will raise :exc:`TypeError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 | |
| 113 | Weak references support tests for equality, but not ordering. If the referents |
| 114 | are still alive, two references have the same equality relationship as their |
| 115 | referents (regardless of the *callback*). If either referent has been deleted, |
| 116 | the references are equal only if the reference objects are the same object. |
| 117 | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 118 | This is a subclassable type rather than a factory function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 119 | |
Mark Dickinson | 556e94b | 2013-04-13 15:45:44 +0100 | [diff] [blame] | 120 | .. attribute:: __callback__ |
| 121 | |
| 122 | This read-only attribute returns the callback currently associated to the |
| 123 | weakref. If there is no callback or if the referent of the weakref is |
| 124 | no longer alive then this attribute will have value ``None``. |
| 125 | |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 126 | .. note:: |
| 127 | |
| 128 | Like :meth:`__del__` methods, weak reference callbacks can be |
| 129 | called during interpreter shutdown when module globals have been |
| 130 | overwritten with :const:`None`. This can make writing robust |
| 131 | weak reference callbacks a challenge. Callbacks registered |
| 132 | using :class:`finalize` do not have to worry about this issue |
| 133 | because they will not be run after module teardown has begun. |
| 134 | |
| 135 | .. versionchanged:: 3.4 |
Mark Dickinson | 9b6fdf8 | 2013-04-13 16:09:18 +0100 | [diff] [blame] | 136 | Added the :attr:`__callback__` attribute. |
Mark Dickinson | 556e94b | 2013-04-13 15:45:44 +0100 | [diff] [blame] | 137 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 138 | |
| 139 | .. function:: proxy(object[, callback]) |
| 140 | |
| 141 | Return a proxy to *object* which uses a weak reference. This supports use of |
| 142 | the proxy in most contexts instead of requiring the explicit dereferencing used |
| 143 | with weak reference objects. The returned object will have a type of either |
| 144 | ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 145 | callable. Proxy objects are not :term:`hashable` regardless of the referent; this |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 146 | avoids a number of problems related to their fundamentally mutable nature, and |
| 147 | prevent their use as dictionary keys. *callback* is the same as the parameter |
| 148 | of the same name to the :func:`ref` function. |
| 149 | |
| 150 | |
| 151 | .. function:: getweakrefcount(object) |
| 152 | |
| 153 | Return the number of weak references and proxies which refer to *object*. |
| 154 | |
| 155 | |
| 156 | .. function:: getweakrefs(object) |
| 157 | |
| 158 | Return a list of all weak reference and proxy objects which refer to *object*. |
| 159 | |
| 160 | |
| 161 | .. class:: WeakKeyDictionary([dict]) |
| 162 | |
| 163 | Mapping class that references keys weakly. Entries in the dictionary will be |
| 164 | discarded when there is no longer a strong reference to the key. This can be |
| 165 | used to associate additional data with an object owned by other parts of an |
| 166 | application without adding attributes to those objects. This can be especially |
| 167 | useful with objects that override attribute accesses. |
| 168 | |
| 169 | .. note:: |
| 170 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 171 | Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 172 | dictionary, it must not change size when iterating over it. This can be |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 173 | difficult to ensure for a :class:`WeakKeyDictionary` because actions |
| 174 | performed by the program during iteration may cause items in the |
| 175 | dictionary to vanish "by magic" (as a side effect of garbage collection). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 176 | |
| 177 | :class:`WeakKeyDictionary` objects have the following additional methods. These |
| 178 | expose the internal references directly. The references are not guaranteed to |
| 179 | be "live" at the time they are used, so the result of calling the references |
| 180 | needs to be checked before being used. This can be used to avoid creating |
| 181 | references that will cause the garbage collector to keep the keys around longer |
| 182 | than needed. |
| 183 | |
| 184 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 185 | .. method:: WeakKeyDictionary.keyrefs() |
| 186 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 187 | Return an iterable of the weak references to the keys. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 188 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 189 | |
| 190 | .. class:: WeakValueDictionary([dict]) |
| 191 | |
| 192 | Mapping class that references values weakly. Entries in the dictionary will be |
| 193 | discarded when no strong reference to the value exists any more. |
| 194 | |
| 195 | .. note:: |
| 196 | |
| 197 | Caution: Because a :class:`WeakValueDictionary` is built on top of a Python |
| 198 | dictionary, it must not change size when iterating over it. This can be |
| 199 | difficult to ensure for a :class:`WeakValueDictionary` because actions performed |
| 200 | by the program during iteration may cause items in the dictionary to vanish "by |
| 201 | magic" (as a side effect of garbage collection). |
| 202 | |
| 203 | :class:`WeakValueDictionary` objects have the following additional methods. |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 204 | These method have the same issues as the and :meth:`keyrefs` method of |
| 205 | :class:`WeakKeyDictionary` objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 206 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | |
| 208 | .. method:: WeakValueDictionary.valuerefs() |
| 209 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 210 | Return an iterable of the weak references to the values. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 211 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 212 | |
Georg Brandl | 3b8cb17 | 2007-10-23 06:26:46 +0000 | [diff] [blame] | 213 | .. class:: WeakSet([elements]) |
| 214 | |
| 215 | Set class that keeps weak references to its elements. An element will be |
| 216 | discarded when no strong reference to it exists any more. |
| 217 | |
| 218 | |
Antoine Pitrou | c3afba1 | 2012-11-17 18:57:38 +0100 | [diff] [blame] | 219 | .. class:: WeakMethod(method) |
| 220 | |
| 221 | A custom :class:`ref` subclass which simulates a weak reference to a bound |
| 222 | method (i.e., a method defined on a class and looked up on an instance). |
| 223 | Since a bound method is ephemeral, a standard weak reference cannot keep |
| 224 | hold of it. :class:`WeakMethod` has special code to recreate the bound |
| 225 | method until either the object or the original function dies:: |
| 226 | |
| 227 | >>> class C: |
| 228 | ... def method(self): |
| 229 | ... print("method called!") |
| 230 | ... |
| 231 | >>> c = C() |
| 232 | >>> r = weakref.ref(c.method) |
| 233 | >>> r() |
| 234 | >>> r = weakref.WeakMethod(c.method) |
| 235 | >>> r() |
| 236 | <bound method C.method of <__main__.C object at 0x7fc859830220>> |
| 237 | >>> r()() |
| 238 | method called! |
| 239 | >>> del c |
| 240 | >>> gc.collect() |
| 241 | 0 |
| 242 | >>> r() |
| 243 | >>> |
| 244 | |
| 245 | .. versionadded:: 3.4 |
| 246 | |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 247 | .. class:: finalize(obj, func, *args, **kwargs) |
| 248 | |
| 249 | Return a callable finalizer object which will be called when *obj* |
Nick Coghlan | be57ab8 | 2013-09-22 21:26:30 +1000 | [diff] [blame^] | 250 | is garbage collected. Unlike an ordinary weak reference, a finalizer is |
| 251 | will always survive until the reference object is collected, greatly |
| 252 | simplifying lifecycle management. |
| 253 | |
| 254 | A finalizer is considered *alive* until it is called (either explicitly |
| 255 | or at garbage collection), and after that it is *dead*. Calling a live |
| 256 | finalizer returns the result of evaluating ``func(*arg, **kwargs)``, |
| 257 | whereas calling a dead finalizer returns :const:`None`. |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 258 | |
| 259 | Exceptions raised by finalizer callbacks during garbage collection |
| 260 | will be shown on the standard error output, but cannot be |
| 261 | propagated. They are handled in the same way as exceptions raised |
| 262 | from an object's :meth:`__del__` method or a weak reference's |
| 263 | callback. |
| 264 | |
| 265 | When the program exits, each remaining live finalizer is called |
| 266 | unless its :attr:`atexit` attribute has been set to false. They |
| 267 | are called in reverse order of creation. |
| 268 | |
| 269 | A finalizer will never invoke its callback during the later part of |
| 270 | the interpreter shutdown when module globals are liable to have |
| 271 | been replaced by :const:`None`. |
| 272 | |
| 273 | .. method:: __call__() |
| 274 | |
| 275 | If *self* is alive then mark it as dead and return the result of |
| 276 | calling ``func(*args, **kwargs)``. If *self* is dead then return |
| 277 | :const:`None`. |
| 278 | |
| 279 | .. method:: detach() |
| 280 | |
| 281 | If *self* is alive then mark it as dead and return the tuple |
| 282 | ``(obj, func, args, kwargs)``. If *self* is dead then return |
| 283 | :const:`None`. |
| 284 | |
| 285 | .. method:: peek() |
| 286 | |
| 287 | If *self* is alive then return the tuple ``(obj, func, args, |
| 288 | kwargs)``. If *self* is dead then return :const:`None`. |
| 289 | |
| 290 | .. attribute:: alive |
| 291 | |
| 292 | Property which is true if the finalizer is alive, false otherwise. |
| 293 | |
| 294 | .. attribute:: atexit |
| 295 | |
| 296 | A writable boolean property which by default is true. When the |
| 297 | program exits, it calls all remaining live finalizers for which |
| 298 | :attr:`.atexit` is true. They are called in reverse order of |
| 299 | creation. |
| 300 | |
| 301 | .. note:: |
| 302 | |
| 303 | It is important to ensure that *func*, *args* and *kwargs* do |
| 304 | not own any references to *obj*, either directly or indirectly, |
| 305 | since otherwise *obj* will never be garbage collected. In |
| 306 | particular, *func* should not be a bound method of *obj*. |
| 307 | |
| 308 | .. versionadded:: 3.4 |
| 309 | |
Antoine Pitrou | c3afba1 | 2012-11-17 18:57:38 +0100 | [diff] [blame] | 310 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 311 | .. data:: ReferenceType |
| 312 | |
| 313 | The type object for weak references objects. |
| 314 | |
| 315 | |
| 316 | .. data:: ProxyType |
| 317 | |
| 318 | The type object for proxies of objects which are not callable. |
| 319 | |
| 320 | |
| 321 | .. data:: CallableProxyType |
| 322 | |
| 323 | The type object for proxies of callable objects. |
| 324 | |
| 325 | |
| 326 | .. data:: ProxyTypes |
| 327 | |
| 328 | Sequence containing all the type objects for proxies. This can make it simpler |
| 329 | to test if an object is a proxy without being dependent on naming both proxy |
| 330 | types. |
| 331 | |
| 332 | |
| 333 | .. exception:: ReferenceError |
| 334 | |
| 335 | Exception raised when a proxy object is used but the underlying object has been |
| 336 | collected. This is the same as the standard :exc:`ReferenceError` exception. |
| 337 | |
| 338 | |
| 339 | .. seealso:: |
| 340 | |
| 341 | :pep:`0205` - Weak References |
| 342 | The proposal and rationale for this feature, including links to earlier |
| 343 | implementations and information about similar features in other languages. |
| 344 | |
| 345 | |
| 346 | .. _weakref-objects: |
| 347 | |
| 348 | Weak Reference Objects |
| 349 | ---------------------- |
| 350 | |
Mark Dickinson | 556e94b | 2013-04-13 15:45:44 +0100 | [diff] [blame] | 351 | Weak reference objects have no methods and no attributes besides |
| 352 | :attr:`ref.__callback__`. A weak reference object allows the referent to be |
| 353 | obtained, if it still exists, by calling it: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 354 | |
| 355 | >>> import weakref |
| 356 | >>> class Object: |
| 357 | ... pass |
| 358 | ... |
| 359 | >>> o = Object() |
| 360 | >>> r = weakref.ref(o) |
| 361 | >>> o2 = r() |
| 362 | >>> o is o2 |
| 363 | True |
| 364 | |
| 365 | If the referent no longer exists, calling the reference object returns |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 366 | :const:`None`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 367 | |
| 368 | >>> del o, o2 |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 369 | >>> print(r()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 370 | None |
| 371 | |
| 372 | Testing that a weak reference object is still live should be done using the |
| 373 | expression ``ref() is not None``. Normally, application code that needs to use |
| 374 | a reference object should follow this pattern:: |
| 375 | |
| 376 | # r is a weak reference object |
| 377 | o = r() |
| 378 | if o is None: |
| 379 | # referent has been garbage collected |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 380 | print("Object has been deallocated; can't frobnicate.") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 381 | else: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 382 | print("Object is still live!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 383 | o.do_something_useful() |
| 384 | |
| 385 | Using a separate test for "liveness" creates race conditions in threaded |
| 386 | applications; another thread can cause a weak reference to become invalidated |
| 387 | before the weak reference is called; the idiom shown above is safe in threaded |
| 388 | applications as well as single-threaded applications. |
| 389 | |
| 390 | Specialized versions of :class:`ref` objects can be created through subclassing. |
| 391 | This is used in the implementation of the :class:`WeakValueDictionary` to reduce |
| 392 | the memory overhead for each entry in the mapping. This may be most useful to |
| 393 | associate additional information with a reference, but could also be used to |
| 394 | insert additional processing on calls to retrieve the referent. |
| 395 | |
| 396 | This example shows how a subclass of :class:`ref` can be used to store |
| 397 | additional information about an object and affect the value that's returned when |
| 398 | the referent is accessed:: |
| 399 | |
| 400 | import weakref |
| 401 | |
| 402 | class ExtendedRef(weakref.ref): |
| 403 | def __init__(self, ob, callback=None, **annotations): |
| 404 | super(ExtendedRef, self).__init__(ob, callback) |
| 405 | self.__counter = 0 |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 406 | for k, v in annotations.items(): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 407 | setattr(self, k, v) |
| 408 | |
| 409 | def __call__(self): |
| 410 | """Return a pair containing the referent and the number of |
| 411 | times the reference has been called. |
| 412 | """ |
| 413 | ob = super(ExtendedRef, self).__call__() |
| 414 | if ob is not None: |
| 415 | self.__counter += 1 |
| 416 | ob = (ob, self.__counter) |
| 417 | return ob |
| 418 | |
| 419 | |
| 420 | .. _weakref-example: |
| 421 | |
| 422 | Example |
| 423 | ------- |
| 424 | |
| 425 | This simple example shows how an application can use objects IDs to retrieve |
| 426 | objects that it has seen before. The IDs of the objects can then be used in |
| 427 | other data structures without forcing the objects to remain alive, but the |
| 428 | objects can still be retrieved by ID if they do. |
| 429 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 430 | .. Example contributed by Tim Peters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 431 | |
| 432 | :: |
| 433 | |
| 434 | import weakref |
| 435 | |
| 436 | _id2obj_dict = weakref.WeakValueDictionary() |
| 437 | |
| 438 | def remember(obj): |
| 439 | oid = id(obj) |
| 440 | _id2obj_dict[oid] = obj |
| 441 | return oid |
| 442 | |
| 443 | def id2obj(oid): |
| 444 | return _id2obj_dict[oid] |
| 445 | |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 446 | |
| 447 | .. _finalize-examples: |
| 448 | |
| 449 | Finalizer Objects |
| 450 | ----------------- |
| 451 | |
Nick Coghlan | be57ab8 | 2013-09-22 21:26:30 +1000 | [diff] [blame^] | 452 | The main benefit of using :class:`finalize` is that it makes it simple |
| 453 | to register a callback without needing to preserve the returned finalizer |
| 454 | object. For instance |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 455 | |
| 456 | >>> import weakref |
| 457 | >>> class Object: |
| 458 | ... pass |
| 459 | ... |
| 460 | >>> kenny = Object() |
| 461 | >>> weakref.finalize(kenny, print, "You killed Kenny!") #doctest:+ELLIPSIS |
| 462 | <finalize object at ...; for 'Object' at ...> |
| 463 | >>> del kenny |
| 464 | You killed Kenny! |
| 465 | |
| 466 | The finalizer can be called directly as well. However the finalizer |
| 467 | will invoke the callback at most once. |
| 468 | |
| 469 | >>> def callback(x, y, z): |
| 470 | ... print("CALLBACK") |
| 471 | ... return x + y + z |
| 472 | ... |
| 473 | >>> obj = Object() |
| 474 | >>> f = weakref.finalize(obj, callback, 1, 2, z=3) |
| 475 | >>> assert f.alive |
| 476 | >>> assert f() == 6 |
| 477 | CALLBACK |
| 478 | >>> assert not f.alive |
| 479 | >>> f() # callback not called because finalizer dead |
| 480 | >>> del obj # callback not called because finalizer dead |
| 481 | |
| 482 | You can unregister a finalizer using its :meth:`~finalize.detach` |
| 483 | method. This kills the finalizer and returns the arguments passed to |
| 484 | the constructor when it was created. |
| 485 | |
| 486 | >>> obj = Object() |
| 487 | >>> f = weakref.finalize(obj, callback, 1, 2, z=3) |
| 488 | >>> f.detach() #doctest:+ELLIPSIS |
| 489 | (<__main__.Object object ...>, <function callback ...>, (1, 2), {'z': 3}) |
| 490 | >>> newobj, func, args, kwargs = _ |
| 491 | >>> assert not f.alive |
| 492 | >>> assert newobj is obj |
| 493 | >>> assert func(*args, **kwargs) == 6 |
| 494 | CALLBACK |
| 495 | |
| 496 | Unless you set the :attr:`~finalize.atexit` attribute to |
Nick Coghlan | be57ab8 | 2013-09-22 21:26:30 +1000 | [diff] [blame^] | 497 | :const:`False`, a finalizer will be called when the program exits if it |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 498 | is still alive. For instance |
| 499 | |
| 500 | >>> obj = Object() |
| 501 | >>> weakref.finalize(obj, print, "obj dead or exiting") #doctest:+ELLIPSIS |
| 502 | <finalize object at ...; for 'Object' at ...> |
| 503 | >>> exit() #doctest:+SKIP |
| 504 | obj dead or exiting |
| 505 | |
| 506 | |
| 507 | Comparing finalizers with :meth:`__del__` methods |
| 508 | ------------------------------------------------- |
| 509 | |
| 510 | Suppose we want to create a class whose instances represent temporary |
| 511 | directories. The directories should be deleted with their contents |
| 512 | when the first of the following events occurs: |
| 513 | |
| 514 | * the object is garbage collected, |
| 515 | * the object's :meth:`remove` method is called, or |
| 516 | * the program exits. |
| 517 | |
| 518 | We might try to implement the class using a :meth:`__del__` method as |
| 519 | follows:: |
| 520 | |
| 521 | class TempDir: |
| 522 | def __init__(self): |
| 523 | self.name = tempfile.mkdtemp() |
| 524 | |
| 525 | def remove(self): |
| 526 | if self.name is not None: |
| 527 | shutil.rmtree(self.name) |
| 528 | self.name = None |
| 529 | |
| 530 | @property |
| 531 | def removed(self): |
| 532 | return self.name is None |
| 533 | |
| 534 | def __del__(self): |
| 535 | self.remove() |
| 536 | |
Nick Coghlan | be57ab8 | 2013-09-22 21:26:30 +1000 | [diff] [blame^] | 537 | Starting with Python 3.4, :meth:`__del__` methods no longer prevent |
| 538 | reference cycles from being garbage collected, and module globals are |
| 539 | no longer forced to :const:`None` during interpreter shutdown. So this |
| 540 | code should work without any issues on CPython. |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 541 | |
Nick Coghlan | be57ab8 | 2013-09-22 21:26:30 +1000 | [diff] [blame^] | 542 | However, handling of :meth:`__del__` methods is notoriously implementation |
| 543 | specific, since it depends on how the interpreter's garbage collector |
| 544 | handles reference cycles and finalizers. |
| 545 | |
| 546 | A more robust alternative can be to define a finalizer which only references |
| 547 | the specific functions and objects that it needs, rather than having access |
| 548 | to the full state of the object:: |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 549 | |
| 550 | class TempDir: |
| 551 | def __init__(self): |
| 552 | self.name = tempfile.mkdtemp() |
| 553 | self._finalizer = weakref.finalize(self, shutil.rmtree, self.name) |
| 554 | |
| 555 | def remove(self): |
| 556 | self._finalizer() |
| 557 | |
| 558 | @property |
| 559 | def removed(self): |
| 560 | return not self._finalizer.alive |
| 561 | |
Nick Coghlan | be57ab8 | 2013-09-22 21:26:30 +1000 | [diff] [blame^] | 562 | Defined like this, our finalizer only receives a reference to the details |
| 563 | it needs to clean up the directory appropriately. If the object never gets |
| 564 | garbage collected the finalizer will still be called at exit. |
| 565 | |
| 566 | The other advantage of weakref based finalizers is that they can be used to |
| 567 | register finalizers for classes where the definition is controlled by a |
| 568 | third party, such as running code when a module is unloaded:: |
| 569 | |
| 570 | import weakref, sys |
| 571 | def unloading_module(): |
| 572 | # implicit reference to the module globals from the function body |
| 573 | weakref.finalize(sys.modules[__name__], unloading_module) |
| 574 | |
Richard Oudkerk | 7a3dae0 | 2013-05-05 23:05:00 +0100 | [diff] [blame] | 575 | |
| 576 | .. note:: |
| 577 | |
| 578 | If you create a finalizer object in a daemonic thread just as the |
| 579 | the program exits then there is the possibility that the finalizer |
| 580 | does not get called at exit. However, in a daemonic thread |
| 581 | :func:`atexit.register`, ``try: ... finally: ...`` and ``with: ...`` |
| 582 | do not guarantee that cleanup occurs either. |