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