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