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