blob: 9c655871b5ed93f5a6ab65a2a9ca89e327396380 [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,
Collin Winter001a3952010-03-18 21:54:01 +000062regular expression pattern objects, and code objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
64.. versionchanged:: 2.4
65 Added support for files, sockets, arrays, and patterns.
66
Gregory P. Smith4e63d542009-08-20 09:39:38 +000067.. versionchanged:: 2.7
Collin Winter001a3952010-03-18 21:54:01 +000068 Added support for thread.lock, threading.Lock, and code objects.
Gregory P. Smith4e63d542009-08-20 09:39:38 +000069
Georg Brandld7d4fd72009-07-26 14:37:28 +000070Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl8ec7f652007-08-15 14:28:01 +000071support weak references but can add support through subclassing::
72
73 class Dict(dict):
74 pass
75
Georg Brandl1699db12008-02-22 12:57:05 +000076 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
Georg Brandl08be2e22009-10-22 08:05:04 +000078.. 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 Brandlcf842ad2009-10-21 07:15:59 +000082
Georg Brandl8ec7f652007-08-15 14:28:01 +000083Extension 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 Brandl7c3e79f2007-11-02 20:06:17 +0000105 Weak references are :term:`hashable` if the *object* is hashable. They will maintain
Georg Brandl8ec7f652007-08-15 14:28:01 +0000106 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 Brandl7c3e79f2007-11-02 20:06:17 +0000126 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127 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 Brandl86f38c82008-03-22 10:07:29 +0000152 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl8ec7f652007-08-15 14:28:01 +0000153 dictionary, it must not change size when iterating over it. This can be
Georg Brandl86f38c82008-03-22 10:07:29 +0000154 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 Brandl8ec7f652007-08-15 14:28:01 +0000157
158:class:`WeakKeyDictionary` objects have the following additional methods. These
159expose the internal references directly. The references are not guaranteed to
160be "live" at the time they are used, so the result of calling the references
161needs to be checked before being used. This can be used to avoid creating
162references that will cause the garbage collector to keep the keys around longer
163than needed.
164
165
166.. method:: WeakKeyDictionary.iterkeyrefs()
167
Georg Brandle7a09902007-10-21 12:10:28 +0000168 Return an :term:`iterator` that yields the weak references to the keys.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
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.
194These method have the same issues as the :meth:`iterkeyrefs` and :meth:`keyrefs`
195methods of :class:`WeakKeyDictionary` objects.
196
197
198.. method:: WeakValueDictionary.itervaluerefs()
199
Georg Brandle7a09902007-10-21 12:10:28 +0000200 Return an :term:`iterator` that yields the weak references to the values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000201
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
Michael Foorde6410c52010-03-29 20:04:23 +0000212.. class:: WeakSet([elements])
213
214 Set class that keeps weak references to its elements. An element will be
215 discarded when no strong reference to it exists any more.
216
217 .. versionadded:: 2.7
218
219
Georg Brandl8ec7f652007-08-15 14:28:01 +0000220.. data:: ReferenceType
221
222 The type object for weak references objects.
223
224
225.. data:: ProxyType
226
227 The type object for proxies of objects which are not callable.
228
229
230.. data:: CallableProxyType
231
232 The type object for proxies of callable objects.
233
234
235.. data:: ProxyTypes
236
237 Sequence containing all the type objects for proxies. This can make it simpler
238 to test if an object is a proxy without being dependent on naming both proxy
239 types.
240
241
242.. exception:: ReferenceError
243
244 Exception raised when a proxy object is used but the underlying object has been
245 collected. This is the same as the standard :exc:`ReferenceError` exception.
246
247
248.. seealso::
249
250 :pep:`0205` - Weak References
251 The proposal and rationale for this feature, including links to earlier
252 implementations and information about similar features in other languages.
253
254
255.. _weakref-objects:
256
257Weak Reference Objects
258----------------------
259
260Weak reference objects have no attributes or methods, but do allow the referent
Georg Brandle8f1b002008-03-22 22:04:10 +0000261to be obtained, if it still exists, by calling it:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000262
263 >>> import weakref
264 >>> class Object:
265 ... pass
266 ...
267 >>> o = Object()
268 >>> r = weakref.ref(o)
269 >>> o2 = r()
270 >>> o is o2
271 True
272
273If the referent no longer exists, calling the reference object returns
Georg Brandle8f1b002008-03-22 22:04:10 +0000274:const:`None`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275
276 >>> del o, o2
277 >>> print r()
278 None
279
280Testing that a weak reference object is still live should be done using the
281expression ``ref() is not None``. Normally, application code that needs to use
282a reference object should follow this pattern::
283
284 # r is a weak reference object
285 o = r()
286 if o is None:
287 # referent has been garbage collected
288 print "Object has been deallocated; can't frobnicate."
289 else:
290 print "Object is still live!"
291 o.do_something_useful()
292
293Using a separate test for "liveness" creates race conditions in threaded
294applications; another thread can cause a weak reference to become invalidated
295before the weak reference is called; the idiom shown above is safe in threaded
296applications as well as single-threaded applications.
297
298Specialized versions of :class:`ref` objects can be created through subclassing.
299This is used in the implementation of the :class:`WeakValueDictionary` to reduce
300the memory overhead for each entry in the mapping. This may be most useful to
301associate additional information with a reference, but could also be used to
302insert additional processing on calls to retrieve the referent.
303
304This example shows how a subclass of :class:`ref` can be used to store
305additional information about an object and affect the value that's returned when
306the referent is accessed::
307
308 import weakref
309
310 class ExtendedRef(weakref.ref):
311 def __init__(self, ob, callback=None, **annotations):
312 super(ExtendedRef, self).__init__(ob, callback)
313 self.__counter = 0
314 for k, v in annotations.iteritems():
315 setattr(self, k, v)
316
317 def __call__(self):
318 """Return a pair containing the referent and the number of
319 times the reference has been called.
320 """
321 ob = super(ExtendedRef, self).__call__()
322 if ob is not None:
323 self.__counter += 1
324 ob = (ob, self.__counter)
325 return ob
326
327
328.. _weakref-example:
329
330Example
331-------
332
333This simple example shows how an application can use objects IDs to retrieve
334objects that it has seen before. The IDs of the objects can then be used in
335other data structures without forcing the objects to remain alive, but the
336objects can still be retrieved by ID if they do.
337
Georg Brandlb19be572007-12-29 10:57:00 +0000338.. Example contributed by Tim Peters.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000339
340::
341
342 import weakref
343
344 _id2obj_dict = weakref.WeakValueDictionary()
345
346 def remember(obj):
347 oid = id(obj)
348 _id2obj_dict[oid] = obj
349 return oid
350
351 def id2obj(oid):
352 return _id2obj_dict[oid]
353