Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +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 | |
| 11 | |
| 12 | .. versionadded:: 2.1 |
| 13 | |
| 14 | The :mod:`weakref` module allows the Python programmer to create :dfn:`weak |
| 15 | references` to objects. |
| 16 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 17 | .. When making changes to the examples in this file, be sure to update |
| 18 | Lib/test/test_weakref.py::libreftest too! |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 19 | |
| 20 | In the following, the term :dfn:`referent` means the object which is referred to |
| 21 | by a weak reference. |
| 22 | |
| 23 | A weak reference to an object is not enough to keep the object alive: when the |
Georg Brandl | 584265b | 2007-12-02 14:58:50 +0000 | [diff] [blame] | 24 | only remaining references to a referent are weak references, |
| 25 | :term:`garbage collection` is free to destroy the referent and reuse its memory |
| 26 | for something else. A primary use for weak references is to implement caches or |
| 27 | mappings holding large objects, where it's desired that a large object not be |
Georg Brandl | 86f38c8 | 2008-03-22 10:07:29 +0000 | [diff] [blame] | 28 | kept alive solely because it appears in a cache or mapping. |
| 29 | |
| 30 | For example, if you have a number of large binary image objects, you may wish to |
| 31 | associate a name with each. If you used a Python dictionary to map names to |
| 32 | images, or images to names, the image objects would remain alive just because |
| 33 | they appeared as values or keys in the dictionaries. The |
| 34 | :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by |
| 35 | the :mod:`weakref` module are an alternative, using weak references to construct |
| 36 | mappings that don't keep objects alive solely because they appear in the mapping |
| 37 | objects. If, for example, an image object is a value in a |
| 38 | :class:`WeakValueDictionary`, then when the last remaining references to that |
| 39 | image object are the weak references held by weak mappings, garbage collection |
| 40 | can reclaim the object, and its corresponding entries in weak mappings are |
| 41 | simply deleted. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 42 | |
| 43 | :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references |
| 44 | in their implementation, setting up callback functions on the weak references |
| 45 | that notify the weak dictionaries when a key or value has been reclaimed by |
| 46 | garbage collection. Most programs should find that using one of these weak |
| 47 | dictionary types is all they need -- it's not usually necessary to create your |
| 48 | own weak references directly. The low-level machinery used by the weak |
| 49 | dictionary implementations is exposed by the :mod:`weakref` module for the |
| 50 | benefit of advanced uses. |
| 51 | |
Georg Brandl | 86f38c8 | 2008-03-22 10:07:29 +0000 | [diff] [blame] | 52 | .. note:: |
| 53 | |
| 54 | Weak references to an object are cleared before the object's :meth:`__del__` |
| 55 | is called, to ensure that the weak reference callback (if any) finds the |
| 56 | object still alive. |
| 57 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 58 | Not all objects can be weakly referenced; those objects which can include class |
| 59 | instances, functions written in Python (but not in C), methods (both bound and |
Georg Brandl | cf3fb25 | 2007-10-21 10:52:38 +0000 | [diff] [blame] | 60 | unbound), sets, frozensets, file objects, :term:`generator`\s, type objects, |
| 61 | :class:`DBcursor` objects from the :mod:`bsddb` module, sockets, arrays, deques, |
| 62 | and regular expression pattern objects. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 63 | |
| 64 | .. versionchanged:: 2.4 |
| 65 | Added support for files, sockets, arrays, and patterns. |
| 66 | |
Gregory P. Smith | 4e63d54 | 2009-08-20 09:39:38 +0000 | [diff] [blame] | 67 | .. versionchanged:: 2.7 |
| 68 | Added support for thread.lock and threading.Lock. |
| 69 | |
Georg Brandl | d7d4fd7 | 2009-07-26 14:37:28 +0000 | [diff] [blame] | 70 | Several built-in types such as :class:`list` and :class:`dict` do not directly |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 71 | support weak references but can add support through subclassing:: |
| 72 | |
| 73 | class Dict(dict): |
| 74 | pass |
| 75 | |
Georg Brandl | 1699db1 | 2008-02-22 12:57:05 +0000 | [diff] [blame] | 76 | obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 77 | |
Georg Brandl | 08be2e2 | 2009-10-22 08:05:04 +0000 | [diff] [blame] | 78 | .. impl-detail:: |
| 79 | |
| 80 | Other built-in types such as :class:`tuple` and :class:`long` do not support |
| 81 | weak references even when subclassed. |
Georg Brandl | cf842ad | 2009-10-21 07:15:59 +0000 | [diff] [blame] | 82 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +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 | 7c3e79f | 2007-11-02 20:06:17 +0000 | [diff] [blame] | 105 | Weak references are :term:`hashable` if the *object* is hashable. They will maintain |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 106 | their hash value even after the *object* was deleted. If :func:`hash` is called |
| 107 | the first time only after the *object* was deleted, the call will raise |
| 108 | :exc:`TypeError`. |
| 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 | |
| 115 | .. versionchanged:: 2.4 |
| 116 | This is now a subclassable type rather than a factory function; it derives from |
| 117 | :class:`object`. |
| 118 | |
| 119 | |
| 120 | .. function:: proxy(object[, callback]) |
| 121 | |
| 122 | Return a proxy to *object* which uses a weak reference. This supports use of |
| 123 | the proxy in most contexts instead of requiring the explicit dereferencing used |
| 124 | with weak reference objects. The returned object will have a type of either |
| 125 | ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is |
Georg Brandl | 7c3e79f | 2007-11-02 20:06:17 +0000 | [diff] [blame] | 126 | callable. Proxy objects are not :term:`hashable` regardless of the referent; this |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 127 | avoids a number of problems related to their fundamentally mutable nature, and |
| 128 | prevent their use as dictionary keys. *callback* is the same as the parameter |
| 129 | of the same name to the :func:`ref` function. |
| 130 | |
| 131 | |
| 132 | .. function:: getweakrefcount(object) |
| 133 | |
| 134 | Return the number of weak references and proxies which refer to *object*. |
| 135 | |
| 136 | |
| 137 | .. function:: getweakrefs(object) |
| 138 | |
| 139 | Return a list of all weak reference and proxy objects which refer to *object*. |
| 140 | |
| 141 | |
| 142 | .. class:: WeakKeyDictionary([dict]) |
| 143 | |
| 144 | Mapping class that references keys weakly. Entries in the dictionary will be |
| 145 | discarded when there is no longer a strong reference to the key. This can be |
| 146 | used to associate additional data with an object owned by other parts of an |
| 147 | application without adding attributes to those objects. This can be especially |
| 148 | useful with objects that override attribute accesses. |
| 149 | |
| 150 | .. note:: |
| 151 | |
Georg Brandl | 86f38c8 | 2008-03-22 10:07:29 +0000 | [diff] [blame] | 152 | Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 153 | dictionary, it must not change size when iterating over it. This can be |
Georg Brandl | 86f38c8 | 2008-03-22 10:07:29 +0000 | [diff] [blame] | 154 | difficult to ensure for a :class:`WeakKeyDictionary` because actions |
| 155 | performed by the program during iteration may cause items in the |
| 156 | dictionary to vanish "by magic" (as a side effect of garbage collection). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 157 | |
| 158 | :class:`WeakKeyDictionary` objects have the following additional methods. These |
| 159 | expose the internal references directly. The references are not guaranteed to |
| 160 | be "live" at the time they are used, so the result of calling the references |
| 161 | needs to be checked before being used. This can be used to avoid creating |
| 162 | references that will cause the garbage collector to keep the keys around longer |
| 163 | than needed. |
| 164 | |
| 165 | |
| 166 | .. method:: WeakKeyDictionary.iterkeyrefs() |
| 167 | |
Georg Brandl | e7a0990 | 2007-10-21 12:10:28 +0000 | [diff] [blame] | 168 | Return an :term:`iterator` that yields the weak references to the keys. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 169 | |
| 170 | .. versionadded:: 2.5 |
| 171 | |
| 172 | |
| 173 | .. method:: WeakKeyDictionary.keyrefs() |
| 174 | |
| 175 | Return a list of weak references to the keys. |
| 176 | |
| 177 | .. versionadded:: 2.5 |
| 178 | |
| 179 | |
| 180 | .. class:: WeakValueDictionary([dict]) |
| 181 | |
| 182 | Mapping class that references values weakly. Entries in the dictionary will be |
| 183 | discarded when no strong reference to the value exists any more. |
| 184 | |
| 185 | .. note:: |
| 186 | |
| 187 | Caution: Because a :class:`WeakValueDictionary` is built on top of a Python |
| 188 | dictionary, it must not change size when iterating over it. This can be |
| 189 | difficult to ensure for a :class:`WeakValueDictionary` because actions performed |
| 190 | by the program during iteration may cause items in the dictionary to vanish "by |
| 191 | magic" (as a side effect of garbage collection). |
| 192 | |
| 193 | :class:`WeakValueDictionary` objects have the following additional methods. |
| 194 | These method have the same issues as the :meth:`iterkeyrefs` and :meth:`keyrefs` |
| 195 | methods of :class:`WeakKeyDictionary` objects. |
| 196 | |
| 197 | |
| 198 | .. method:: WeakValueDictionary.itervaluerefs() |
| 199 | |
Georg Brandl | e7a0990 | 2007-10-21 12:10:28 +0000 | [diff] [blame] | 200 | Return an :term:`iterator` that yields the weak references to the values. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 201 | |
| 202 | .. versionadded:: 2.5 |
| 203 | |
| 204 | |
| 205 | .. method:: WeakValueDictionary.valuerefs() |
| 206 | |
| 207 | Return a list of weak references to the values. |
| 208 | |
| 209 | .. versionadded:: 2.5 |
| 210 | |
| 211 | |
| 212 | .. data:: ReferenceType |
| 213 | |
| 214 | The type object for weak references objects. |
| 215 | |
| 216 | |
| 217 | .. data:: ProxyType |
| 218 | |
| 219 | The type object for proxies of objects which are not callable. |
| 220 | |
| 221 | |
| 222 | .. data:: CallableProxyType |
| 223 | |
| 224 | The type object for proxies of callable objects. |
| 225 | |
| 226 | |
| 227 | .. data:: ProxyTypes |
| 228 | |
| 229 | Sequence containing all the type objects for proxies. This can make it simpler |
| 230 | to test if an object is a proxy without being dependent on naming both proxy |
| 231 | types. |
| 232 | |
| 233 | |
| 234 | .. exception:: ReferenceError |
| 235 | |
| 236 | Exception raised when a proxy object is used but the underlying object has been |
| 237 | collected. This is the same as the standard :exc:`ReferenceError` exception. |
| 238 | |
| 239 | |
| 240 | .. seealso:: |
| 241 | |
| 242 | :pep:`0205` - Weak References |
| 243 | The proposal and rationale for this feature, including links to earlier |
| 244 | implementations and information about similar features in other languages. |
| 245 | |
| 246 | |
| 247 | .. _weakref-objects: |
| 248 | |
| 249 | Weak Reference Objects |
| 250 | ---------------------- |
| 251 | |
| 252 | Weak reference objects have no attributes or methods, but do allow the referent |
Georg Brandl | e8f1b00 | 2008-03-22 22:04:10 +0000 | [diff] [blame] | 253 | to be obtained, if it still exists, by calling it: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 254 | |
| 255 | >>> import weakref |
| 256 | >>> class Object: |
| 257 | ... pass |
| 258 | ... |
| 259 | >>> o = Object() |
| 260 | >>> r = weakref.ref(o) |
| 261 | >>> o2 = r() |
| 262 | >>> o is o2 |
| 263 | True |
| 264 | |
| 265 | If the referent no longer exists, calling the reference object returns |
Georg Brandl | e8f1b00 | 2008-03-22 22:04:10 +0000 | [diff] [blame] | 266 | :const:`None`: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 267 | |
| 268 | >>> del o, o2 |
| 269 | >>> print r() |
| 270 | None |
| 271 | |
| 272 | Testing that a weak reference object is still live should be done using the |
| 273 | expression ``ref() is not None``. Normally, application code that needs to use |
| 274 | a reference object should follow this pattern:: |
| 275 | |
| 276 | # r is a weak reference object |
| 277 | o = r() |
| 278 | if o is None: |
| 279 | # referent has been garbage collected |
| 280 | print "Object has been deallocated; can't frobnicate." |
| 281 | else: |
| 282 | print "Object is still live!" |
| 283 | o.do_something_useful() |
| 284 | |
| 285 | Using a separate test for "liveness" creates race conditions in threaded |
| 286 | applications; another thread can cause a weak reference to become invalidated |
| 287 | before the weak reference is called; the idiom shown above is safe in threaded |
| 288 | applications as well as single-threaded applications. |
| 289 | |
| 290 | Specialized versions of :class:`ref` objects can be created through subclassing. |
| 291 | This is used in the implementation of the :class:`WeakValueDictionary` to reduce |
| 292 | the memory overhead for each entry in the mapping. This may be most useful to |
| 293 | associate additional information with a reference, but could also be used to |
| 294 | insert additional processing on calls to retrieve the referent. |
| 295 | |
| 296 | This example shows how a subclass of :class:`ref` can be used to store |
| 297 | additional information about an object and affect the value that's returned when |
| 298 | the referent is accessed:: |
| 299 | |
| 300 | import weakref |
| 301 | |
| 302 | class ExtendedRef(weakref.ref): |
| 303 | def __init__(self, ob, callback=None, **annotations): |
| 304 | super(ExtendedRef, self).__init__(ob, callback) |
| 305 | self.__counter = 0 |
| 306 | for k, v in annotations.iteritems(): |
| 307 | setattr(self, k, v) |
| 308 | |
| 309 | def __call__(self): |
| 310 | """Return a pair containing the referent and the number of |
| 311 | times the reference has been called. |
| 312 | """ |
| 313 | ob = super(ExtendedRef, self).__call__() |
| 314 | if ob is not None: |
| 315 | self.__counter += 1 |
| 316 | ob = (ob, self.__counter) |
| 317 | return ob |
| 318 | |
| 319 | |
| 320 | .. _weakref-example: |
| 321 | |
| 322 | Example |
| 323 | ------- |
| 324 | |
| 325 | This simple example shows how an application can use objects IDs to retrieve |
| 326 | objects that it has seen before. The IDs of the objects can then be used in |
| 327 | other data structures without forcing the objects to remain alive, but the |
| 328 | objects can still be retrieved by ID if they do. |
| 329 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 330 | .. Example contributed by Tim Peters. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 331 | |
| 332 | :: |
| 333 | |
| 334 | import weakref |
| 335 | |
| 336 | _id2obj_dict = weakref.WeakValueDictionary() |
| 337 | |
| 338 | def remember(obj): |
| 339 | oid = id(obj) |
| 340 | _id2obj_dict[oid] = obj |
| 341 | return oid |
| 342 | |
| 343 | def id2obj(oid): |
| 344 | return _id2obj_dict[oid] |
| 345 | |