blob: 7929c5179e596659fadffc001dbe2228d14e17f1 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001: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
Éric Araujo29a0b572011-08-19 02:14:03 +020014**Source code:** :source:`Lib/weakref.py`
15
16--------------
17
Georg Brandl8ec7f652007-08-15 14:28:01 +000018The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
19references` to objects.
20
Georg Brandlb19be572007-12-29 10:57:00 +000021.. When making changes to the examples in this file, be sure to update
22 Lib/test/test_weakref.py::libreftest too!
Georg Brandl8ec7f652007-08-15 14:28:01 +000023
24In the following, the term :dfn:`referent` means the object which is referred to
25by a weak reference.
26
27A weak reference to an object is not enough to keep the object alive: when the
Georg Brandl584265b2007-12-02 14:58:50 +000028only remaining references to a referent are weak references,
29:term:`garbage collection` is free to destroy the referent and reuse its memory
30for something else. A primary use for weak references is to implement caches or
31mappings holding large objects, where it's desired that a large object not be
Georg Brandl86f38c82008-03-22 10:07:29 +000032kept alive solely because it appears in a cache or mapping.
33
34For example, if you have a number of large binary image objects, you may wish to
35associate a name with each. If you used a Python dictionary to map names to
36images, or images to names, the image objects would remain alive just because
37they appeared as values or keys in the dictionaries. The
38:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
39the :mod:`weakref` module are an alternative, using weak references to construct
40mappings that don't keep objects alive solely because they appear in the mapping
41objects. If, for example, an image object is a value in a
42:class:`WeakValueDictionary`, then when the last remaining references to that
43image object are the weak references held by weak mappings, garbage collection
44can reclaim the object, and its corresponding entries in weak mappings are
45simply deleted.
Georg Brandl8ec7f652007-08-15 14:28:01 +000046
47:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
48in their implementation, setting up callback functions on the weak references
49that notify the weak dictionaries when a key or value has been reclaimed by
50garbage collection. Most programs should find that using one of these weak
51dictionary types is all they need -- it's not usually necessary to create your
52own weak references directly. The low-level machinery used by the weak
53dictionary implementations is exposed by the :mod:`weakref` module for the
54benefit of advanced uses.
55
Georg Brandl86f38c82008-03-22 10:07:29 +000056.. 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 Brandl8ec7f652007-08-15 14:28:01 +000062Not all objects can be weakly referenced; those objects which can include class
63instances, functions written in Python (but not in C), methods (both bound and
Georg Brandlcf3fb252007-10-21 10:52:38 +000064unbound), sets, frozensets, file objects, :term:`generator`\s, type objects,
65:class:`DBcursor` objects from the :mod:`bsddb` module, sockets, arrays, deques,
Collin Winter001a3952010-03-18 21:54:01 +000066regular expression pattern objects, and code objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
68.. versionchanged:: 2.4
69 Added support for files, sockets, arrays, and patterns.
70
Gregory P. Smith4e63d542009-08-20 09:39:38 +000071.. versionchanged:: 2.7
Collin Winter001a3952010-03-18 21:54:01 +000072 Added support for thread.lock, threading.Lock, and code objects.
Gregory P. Smith4e63d542009-08-20 09:39:38 +000073
Georg Brandld7d4fd72009-07-26 14:37:28 +000074Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl8ec7f652007-08-15 14:28:01 +000075support weak references but can add support through subclassing::
76
77 class Dict(dict):
78 pass
79
Georg Brandl1699db12008-02-22 12:57:05 +000080 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl8ec7f652007-08-15 14:28:01 +000081
Georg Brandl08be2e22009-10-22 08:05:04 +000082.. impl-detail::
83
84 Other built-in types such as :class:`tuple` and :class:`long` do not support
85 weak references even when subclassed.
Georg Brandlcf842ad2009-10-21 07:15:59 +000086
Georg Brandl8ec7f652007-08-15 14:28:01 +000087Extension types can easily be made to support weak references; see
88:ref:`weakref-support`.
89
90
91.. class:: ref(object[, callback])
92
93 Return a weak reference to *object*. The original object can be retrieved by
94 calling the reference object if the referent is still alive; if the referent is
95 no longer alive, calling the reference object will cause :const:`None` to be
96 returned. If *callback* is provided and not :const:`None`, and the returned
97 weakref object is still alive, the callback will be called when the object is
98 about to be finalized; the weak reference object will be passed as the only
99 parameter to the callback; the referent will no longer be available.
100
101 It is allowable for many weak references to be constructed for the same object.
102 Callbacks registered for each weak reference will be called from the most
103 recently registered callback to the oldest registered callback.
104
105 Exceptions raised by the callback will be noted on the standard error output,
106 but cannot be propagated; they are handled in exactly the same way as exceptions
107 raised from an object's :meth:`__del__` method.
108
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000109 Weak references are :term:`hashable` if the *object* is hashable. They will maintain
Georg Brandl8ec7f652007-08-15 14:28:01 +0000110 their hash value even after the *object* was deleted. If :func:`hash` is called
111 the first time only after the *object* was deleted, the call will raise
112 :exc:`TypeError`.
113
114 Weak references support tests for equality, but not ordering. If the referents
115 are still alive, two references have the same equality relationship as their
116 referents (regardless of the *callback*). If either referent has been deleted,
117 the references are equal only if the reference objects are the same object.
118
119 .. versionchanged:: 2.4
120 This is now a subclassable type rather than a factory function; it derives from
121 :class:`object`.
122
123
124.. function:: proxy(object[, callback])
125
126 Return a proxy to *object* which uses a weak reference. This supports use of
127 the proxy in most contexts instead of requiring the explicit dereferencing used
128 with weak reference objects. The returned object will have a type of either
129 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000130 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl8ec7f652007-08-15 14:28:01 +0000131 avoids a number of problems related to their fundamentally mutable nature, and
132 prevent their use as dictionary keys. *callback* is the same as the parameter
133 of the same name to the :func:`ref` function.
134
135
136.. function:: getweakrefcount(object)
137
138 Return the number of weak references and proxies which refer to *object*.
139
140
141.. function:: getweakrefs(object)
142
143 Return a list of all weak reference and proxy objects which refer to *object*.
144
145
146.. class:: WeakKeyDictionary([dict])
147
148 Mapping class that references keys weakly. Entries in the dictionary will be
149 discarded when there is no longer a strong reference to the key. This can be
150 used to associate additional data with an object owned by other parts of an
151 application without adding attributes to those objects. This can be especially
152 useful with objects that override attribute accesses.
153
154 .. note::
155
Georg Brandl86f38c82008-03-22 10:07:29 +0000156 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157 dictionary, it must not change size when iterating over it. This can be
Georg Brandl86f38c82008-03-22 10:07:29 +0000158 difficult to ensure for a :class:`WeakKeyDictionary` because actions
159 performed by the program during iteration may cause items in the
160 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
162:class:`WeakKeyDictionary` objects have the following additional methods. These
163expose the internal references directly. The references are not guaranteed to
164be "live" at the time they are used, so the result of calling the references
165needs to be checked before being used. This can be used to avoid creating
166references that will cause the garbage collector to keep the keys around longer
167than needed.
168
169
170.. method:: WeakKeyDictionary.iterkeyrefs()
171
Georg Brandle7a09902007-10-21 12:10:28 +0000172 Return an :term:`iterator` that yields the weak references to the keys.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173
174 .. versionadded:: 2.5
175
176
177.. method:: WeakKeyDictionary.keyrefs()
178
179 Return a list of weak references to the keys.
180
181 .. versionadded:: 2.5
182
183
184.. class:: WeakValueDictionary([dict])
185
186 Mapping class that references values weakly. Entries in the dictionary will be
187 discarded when no strong reference to the value exists any more.
188
189 .. note::
190
191 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
192 dictionary, it must not change size when iterating over it. This can be
193 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
194 by the program during iteration may cause items in the dictionary to vanish "by
195 magic" (as a side effect of garbage collection).
196
197:class:`WeakValueDictionary` objects have the following additional methods.
198These method have the same issues as the :meth:`iterkeyrefs` and :meth:`keyrefs`
199methods of :class:`WeakKeyDictionary` objects.
200
201
202.. method:: WeakValueDictionary.itervaluerefs()
203
Georg Brandle7a09902007-10-21 12:10:28 +0000204 Return an :term:`iterator` that yields the weak references to the values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000205
206 .. versionadded:: 2.5
207
208
209.. method:: WeakValueDictionary.valuerefs()
210
211 Return a list of weak references to the values.
212
213 .. versionadded:: 2.5
214
215
Michael Foorde6410c52010-03-29 20:04:23 +0000216.. class:: WeakSet([elements])
217
218 Set class that keeps weak references to its elements. An element will be
219 discarded when no strong reference to it exists any more.
220
221 .. versionadded:: 2.7
222
223
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224.. data:: ReferenceType
225
226 The type object for weak references objects.
227
228
229.. data:: ProxyType
230
231 The type object for proxies of objects which are not callable.
232
233
234.. data:: CallableProxyType
235
236 The type object for proxies of callable objects.
237
238
239.. data:: ProxyTypes
240
241 Sequence containing all the type objects for proxies. This can make it simpler
242 to test if an object is a proxy without being dependent on naming both proxy
243 types.
244
245
246.. exception:: ReferenceError
247
248 Exception raised when a proxy object is used but the underlying object has been
249 collected. This is the same as the standard :exc:`ReferenceError` exception.
250
251
252.. seealso::
253
254 :pep:`0205` - Weak References
255 The proposal and rationale for this feature, including links to earlier
256 implementations and information about similar features in other languages.
257
258
259.. _weakref-objects:
260
261Weak Reference Objects
262----------------------
263
264Weak reference objects have no attributes or methods, but do allow the referent
Georg Brandle8f1b002008-03-22 22:04:10 +0000265to be obtained, if it still exists, by calling it:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266
267 >>> import weakref
268 >>> class Object:
269 ... pass
270 ...
271 >>> o = Object()
272 >>> r = weakref.ref(o)
273 >>> o2 = r()
274 >>> o is o2
275 True
276
277If the referent no longer exists, calling the reference object returns
Georg Brandle8f1b002008-03-22 22:04:10 +0000278:const:`None`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
280 >>> del o, o2
281 >>> print r()
282 None
283
284Testing that a weak reference object is still live should be done using the
285expression ``ref() is not None``. Normally, application code that needs to use
286a reference object should follow this pattern::
287
288 # r is a weak reference object
289 o = r()
290 if o is None:
291 # referent has been garbage collected
292 print "Object has been deallocated; can't frobnicate."
293 else:
294 print "Object is still live!"
295 o.do_something_useful()
296
297Using a separate test for "liveness" creates race conditions in threaded
298applications; another thread can cause a weak reference to become invalidated
299before the weak reference is called; the idiom shown above is safe in threaded
300applications as well as single-threaded applications.
301
302Specialized versions of :class:`ref` objects can be created through subclassing.
303This is used in the implementation of the :class:`WeakValueDictionary` to reduce
304the memory overhead for each entry in the mapping. This may be most useful to
305associate additional information with a reference, but could also be used to
306insert additional processing on calls to retrieve the referent.
307
308This example shows how a subclass of :class:`ref` can be used to store
309additional information about an object and affect the value that's returned when
310the referent is accessed::
311
312 import weakref
313
314 class ExtendedRef(weakref.ref):
315 def __init__(self, ob, callback=None, **annotations):
316 super(ExtendedRef, self).__init__(ob, callback)
317 self.__counter = 0
318 for k, v in annotations.iteritems():
319 setattr(self, k, v)
320
321 def __call__(self):
322 """Return a pair containing the referent and the number of
323 times the reference has been called.
324 """
325 ob = super(ExtendedRef, self).__call__()
326 if ob is not None:
327 self.__counter += 1
328 ob = (ob, self.__counter)
329 return ob
330
331
332.. _weakref-example:
333
334Example
335-------
336
337This simple example shows how an application can use objects IDs to retrieve
338objects that it has seen before. The IDs of the objects can then be used in
339other data structures without forcing the objects to remain alive, but the
340objects can still be retrieved by ID if they do.
341
Georg Brandlb19be572007-12-29 10:57:00 +0000342.. Example contributed by Tim Peters.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
344::
345
346 import weakref
347
348 _id2obj_dict = weakref.WeakValueDictionary()
349
350 def remember(obj):
351 oid = id(obj)
352 _id2obj_dict[oid] = obj
353 return oid
354
355 def id2obj(oid):
356 return _id2obj_dict[oid]
357