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 |
| 27 | for something else. A primary use for weak references is to implement caches or |
| 28 | 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] | 29 | kept alive solely because it appears in a cache or mapping. |
| 30 | |
| 31 | For example, if you have a number of large binary image objects, you may wish to |
| 32 | associate a name with each. If you used a Python dictionary to map names to |
| 33 | images, or images to names, the image objects would remain alive just because |
| 34 | they appeared as values or keys in the dictionaries. The |
| 35 | :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by |
| 36 | the :mod:`weakref` module are an alternative, using weak references to construct |
| 37 | mappings that don't keep objects alive solely because they appear in the mapping |
| 38 | objects. If, for example, an image object is a value in a |
| 39 | :class:`WeakValueDictionary`, then when the last remaining references to that |
| 40 | image object are the weak references held by weak mappings, garbage collection |
| 41 | can reclaim the object, and its corresponding entries in weak mappings are |
| 42 | simply deleted. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 43 | |
| 44 | :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references |
| 45 | in their implementation, setting up callback functions on the weak references |
| 46 | 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] | 47 | garbage collection. :class:`WeakSet` implements the :class:`set` interface, |
| 48 | but keeps weak references to its elements, just like a |
| 49 | :class:`WeakKeyDictionary` does. |
| 50 | |
| 51 | Most programs should find that using one of these weak container types is all |
| 52 | they need -- it's not usually necessary to create your own weak references |
| 53 | directly. The low-level machinery used by the weak dictionary implementations |
| 54 | is exposed by the :mod:`weakref` module for the benefit of advanced uses. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 55 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 56 | .. note:: |
| 57 | |
| 58 | Weak references to an object are cleared before the object's :meth:`__del__` |
| 59 | is called, to ensure that the weak reference callback (if any) finds the |
| 60 | object still alive. |
| 61 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 62 | 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] | 63 | instances, functions written in Python (but not in C), instance methods, sets, |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 64 | frozensets, some :term:`file objects <file object>`, :term:`generator`\s, type |
| 65 | objects, sockets, arrays, deques, regular expression pattern objects, and code |
| 66 | objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 67 | |
Benjamin Peterson | bec4d57 | 2009-10-10 01:16:07 +0000 | [diff] [blame] | 68 | .. versionchanged:: 3.2 |
Collin Winter | 4222e9c | 2010-03-18 22:46:40 +0000 | [diff] [blame] | 69 | Added support for thread.lock, threading.Lock, and code objects. |
Benjamin Peterson | bec4d57 | 2009-10-10 01:16:07 +0000 | [diff] [blame] | 70 | |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 71 | 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] | 72 | support weak references but can add support through subclassing:: |
| 73 | |
| 74 | class Dict(dict): |
| 75 | pass |
| 76 | |
Christian Heimes | c3f30c4 | 2008-02-22 16:37:40 +0000 | [diff] [blame] | 77 | 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] | 78 | |
Benjamin Peterson | 905982b | 2010-05-08 15:26:30 +0000 | [diff] [blame] | 79 | Other built-in types such as :class:`tuple` and :class:`int` do not support weak |
| 80 | references even when subclassed (This is an implementation detail and may be |
| 81 | different across various Python implementations.). |
Georg Brandl | ff8c1e5 | 2009-10-21 07:17:48 +0000 | [diff] [blame] | 82 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 83 | Extension types can easily be made to support weak references; see |
| 84 | :ref:`weakref-support`. |
| 85 | |
| 86 | |
| 87 | .. class:: ref(object[, callback]) |
| 88 | |
| 89 | Return a weak reference to *object*. The original object can be retrieved by |
| 90 | calling the reference object if the referent is still alive; if the referent is |
| 91 | no longer alive, calling the reference object will cause :const:`None` to be |
| 92 | returned. If *callback* is provided and not :const:`None`, and the returned |
| 93 | weakref object is still alive, the callback will be called when the object is |
| 94 | about to be finalized; the weak reference object will be passed as the only |
| 95 | parameter to the callback; the referent will no longer be available. |
| 96 | |
| 97 | It is allowable for many weak references to be constructed for the same object. |
| 98 | Callbacks registered for each weak reference will be called from the most |
| 99 | recently registered callback to the oldest registered callback. |
| 100 | |
| 101 | Exceptions raised by the callback will be noted on the standard error output, |
| 102 | but cannot be propagated; they are handled in exactly the same way as exceptions |
| 103 | raised from an object's :meth:`__del__` method. |
| 104 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 105 | Weak references are :term:`hashable` if the *object* is hashable. They will |
| 106 | maintain their hash value even after the *object* was deleted. If |
| 107 | :func:`hash` is called the first time only after the *object* was deleted, |
| 108 | the call will raise :exc:`TypeError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 109 | |
| 110 | Weak references support tests for equality, but not ordering. If the referents |
| 111 | are still alive, two references have the same equality relationship as their |
| 112 | referents (regardless of the *callback*). If either referent has been deleted, |
| 113 | the references are equal only if the reference objects are the same object. |
| 114 | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 115 | This is a subclassable type rather than a factory function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 116 | |
| 117 | |
| 118 | .. function:: proxy(object[, callback]) |
| 119 | |
| 120 | Return a proxy to *object* which uses a weak reference. This supports use of |
| 121 | the proxy in most contexts instead of requiring the explicit dereferencing used |
| 122 | with weak reference objects. The returned object will have a type of either |
| 123 | ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 124 | callable. Proxy objects are not :term:`hashable` regardless of the referent; this |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 125 | avoids a number of problems related to their fundamentally mutable nature, and |
| 126 | prevent their use as dictionary keys. *callback* is the same as the parameter |
| 127 | of the same name to the :func:`ref` function. |
| 128 | |
| 129 | |
| 130 | .. function:: getweakrefcount(object) |
| 131 | |
| 132 | Return the number of weak references and proxies which refer to *object*. |
| 133 | |
| 134 | |
| 135 | .. function:: getweakrefs(object) |
| 136 | |
| 137 | Return a list of all weak reference and proxy objects which refer to *object*. |
| 138 | |
| 139 | |
| 140 | .. class:: WeakKeyDictionary([dict]) |
| 141 | |
| 142 | Mapping class that references keys weakly. Entries in the dictionary will be |
| 143 | discarded when there is no longer a strong reference to the key. This can be |
| 144 | used to associate additional data with an object owned by other parts of an |
| 145 | application without adding attributes to those objects. This can be especially |
| 146 | useful with objects that override attribute accesses. |
| 147 | |
| 148 | .. note:: |
| 149 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 150 | Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 151 | 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] | 152 | difficult to ensure for a :class:`WeakKeyDictionary` because actions |
| 153 | performed by the program during iteration may cause items in the |
| 154 | dictionary to vanish "by magic" (as a side effect of garbage collection). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 155 | |
| 156 | :class:`WeakKeyDictionary` objects have the following additional methods. These |
| 157 | expose the internal references directly. The references are not guaranteed to |
| 158 | be "live" at the time they are used, so the result of calling the references |
| 159 | needs to be checked before being used. This can be used to avoid creating |
| 160 | references that will cause the garbage collector to keep the keys around longer |
| 161 | than needed. |
| 162 | |
| 163 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 164 | .. method:: WeakKeyDictionary.keyrefs() |
| 165 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 166 | Return an iterable of the weak references to the keys. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 167 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 168 | |
| 169 | .. class:: WeakValueDictionary([dict]) |
| 170 | |
| 171 | Mapping class that references values weakly. Entries in the dictionary will be |
| 172 | discarded when no strong reference to the value exists any more. |
| 173 | |
| 174 | .. note:: |
| 175 | |
| 176 | Caution: Because a :class:`WeakValueDictionary` is built on top of a Python |
| 177 | dictionary, it must not change size when iterating over it. This can be |
| 178 | difficult to ensure for a :class:`WeakValueDictionary` because actions performed |
| 179 | by the program during iteration may cause items in the dictionary to vanish "by |
| 180 | magic" (as a side effect of garbage collection). |
| 181 | |
| 182 | :class:`WeakValueDictionary` objects have the following additional methods. |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 183 | These method have the same issues as the and :meth:`keyrefs` method of |
| 184 | :class:`WeakKeyDictionary` objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 185 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 186 | |
| 187 | .. method:: WeakValueDictionary.valuerefs() |
| 188 | |
Antoine Pitrou | c1baa60 | 2010-01-08 17:54:23 +0000 | [diff] [blame] | 189 | Return an iterable of the weak references to the values. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 190 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 191 | |
Georg Brandl | 3b8cb17 | 2007-10-23 06:26:46 +0000 | [diff] [blame] | 192 | .. class:: WeakSet([elements]) |
| 193 | |
| 194 | Set class that keeps weak references to its elements. An element will be |
| 195 | discarded when no strong reference to it exists any more. |
| 196 | |
| 197 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 198 | .. data:: ReferenceType |
| 199 | |
| 200 | The type object for weak references objects. |
| 201 | |
| 202 | |
| 203 | .. data:: ProxyType |
| 204 | |
| 205 | The type object for proxies of objects which are not callable. |
| 206 | |
| 207 | |
| 208 | .. data:: CallableProxyType |
| 209 | |
| 210 | The type object for proxies of callable objects. |
| 211 | |
| 212 | |
| 213 | .. data:: ProxyTypes |
| 214 | |
| 215 | Sequence containing all the type objects for proxies. This can make it simpler |
| 216 | to test if an object is a proxy without being dependent on naming both proxy |
| 217 | types. |
| 218 | |
| 219 | |
| 220 | .. exception:: ReferenceError |
| 221 | |
| 222 | Exception raised when a proxy object is used but the underlying object has been |
| 223 | collected. This is the same as the standard :exc:`ReferenceError` exception. |
| 224 | |
| 225 | |
| 226 | .. seealso:: |
| 227 | |
| 228 | :pep:`0205` - Weak References |
| 229 | The proposal and rationale for this feature, including links to earlier |
| 230 | implementations and information about similar features in other languages. |
| 231 | |
| 232 | |
| 233 | .. _weakref-objects: |
| 234 | |
| 235 | Weak Reference Objects |
| 236 | ---------------------- |
| 237 | |
| 238 | Weak reference objects have no attributes or methods, but do allow the referent |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 239 | to be obtained, if it still exists, by calling it: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 240 | |
| 241 | >>> import weakref |
| 242 | >>> class Object: |
| 243 | ... pass |
| 244 | ... |
| 245 | >>> o = Object() |
| 246 | >>> r = weakref.ref(o) |
| 247 | >>> o2 = r() |
| 248 | >>> o is o2 |
| 249 | True |
| 250 | |
| 251 | If the referent no longer exists, calling the reference object returns |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 252 | :const:`None`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 253 | |
| 254 | >>> del o, o2 |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 255 | >>> print(r()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 256 | None |
| 257 | |
| 258 | Testing that a weak reference object is still live should be done using the |
| 259 | expression ``ref() is not None``. Normally, application code that needs to use |
| 260 | a reference object should follow this pattern:: |
| 261 | |
| 262 | # r is a weak reference object |
| 263 | o = r() |
| 264 | if o is None: |
| 265 | # referent has been garbage collected |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 266 | print("Object has been deallocated; can't frobnicate.") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 267 | else: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 268 | print("Object is still live!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 269 | o.do_something_useful() |
| 270 | |
| 271 | Using a separate test for "liveness" creates race conditions in threaded |
| 272 | applications; another thread can cause a weak reference to become invalidated |
| 273 | before the weak reference is called; the idiom shown above is safe in threaded |
| 274 | applications as well as single-threaded applications. |
| 275 | |
| 276 | Specialized versions of :class:`ref` objects can be created through subclassing. |
| 277 | This is used in the implementation of the :class:`WeakValueDictionary` to reduce |
| 278 | the memory overhead for each entry in the mapping. This may be most useful to |
| 279 | associate additional information with a reference, but could also be used to |
| 280 | insert additional processing on calls to retrieve the referent. |
| 281 | |
| 282 | This example shows how a subclass of :class:`ref` can be used to store |
| 283 | additional information about an object and affect the value that's returned when |
| 284 | the referent is accessed:: |
| 285 | |
| 286 | import weakref |
| 287 | |
| 288 | class ExtendedRef(weakref.ref): |
| 289 | def __init__(self, ob, callback=None, **annotations): |
| 290 | super(ExtendedRef, self).__init__(ob, callback) |
| 291 | self.__counter = 0 |
Barry Warsaw | ecaab83 | 2008-09-04 01:42:51 +0000 | [diff] [blame] | 292 | for k, v in annotations.items(): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 293 | setattr(self, k, v) |
| 294 | |
| 295 | def __call__(self): |
| 296 | """Return a pair containing the referent and the number of |
| 297 | times the reference has been called. |
| 298 | """ |
| 299 | ob = super(ExtendedRef, self).__call__() |
| 300 | if ob is not None: |
| 301 | self.__counter += 1 |
| 302 | ob = (ob, self.__counter) |
| 303 | return ob |
| 304 | |
| 305 | |
| 306 | .. _weakref-example: |
| 307 | |
| 308 | Example |
| 309 | ------- |
| 310 | |
| 311 | This simple example shows how an application can use objects IDs to retrieve |
| 312 | objects that it has seen before. The IDs of the objects can then be used in |
| 313 | other data structures without forcing the objects to remain alive, but the |
| 314 | objects can still be retrieved by ID if they do. |
| 315 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 316 | .. Example contributed by Tim Peters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 317 | |
| 318 | :: |
| 319 | |
| 320 | import weakref |
| 321 | |
| 322 | _id2obj_dict = weakref.WeakValueDictionary() |
| 323 | |
| 324 | def remember(obj): |
| 325 | oid = id(obj) |
| 326 | _id2obj_dict[oid] = obj |
| 327 | return oid |
| 328 | |
| 329 | def id2obj(oid): |
| 330 | return _id2obj_dict[oid] |
| 331 | |