blob: 96036e99c1a96db2a05ab08f1e00769c7071e5b4 [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
Gregory P. Smith4e63d542009-08-20 09:39:38 +000067.. versionchanged:: 2.7
68 Added support for thread.lock and threading.Lock.
69
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
212.. data:: ReferenceType
213
214 The type object for weak references objects.
215
216
217.. data:: ProxyType
218
219 The type object for proxies of objects which are not callable.
220
221
222.. data:: CallableProxyType
223
224 The type object for proxies of callable objects.
225
226
227.. data:: ProxyTypes
228
229 Sequence containing all the type objects for proxies. This can make it simpler
230 to test if an object is a proxy without being dependent on naming both proxy
231 types.
232
233
234.. exception:: ReferenceError
235
236 Exception raised when a proxy object is used but the underlying object has been
237 collected. This is the same as the standard :exc:`ReferenceError` exception.
238
239
240.. seealso::
241
242 :pep:`0205` - Weak References
243 The proposal and rationale for this feature, including links to earlier
244 implementations and information about similar features in other languages.
245
246
247.. _weakref-objects:
248
249Weak Reference Objects
250----------------------
251
252Weak reference objects have no attributes or methods, but do allow the referent
Georg Brandle8f1b002008-03-22 22:04:10 +0000253to be obtained, if it still exists, by calling it:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000254
255 >>> import weakref
256 >>> class Object:
257 ... pass
258 ...
259 >>> o = Object()
260 >>> r = weakref.ref(o)
261 >>> o2 = r()
262 >>> o is o2
263 True
264
265If the referent no longer exists, calling the reference object returns
Georg Brandle8f1b002008-03-22 22:04:10 +0000266:const:`None`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000267
268 >>> del o, o2
269 >>> print r()
270 None
271
272Testing that a weak reference object is still live should be done using the
273expression ``ref() is not None``. Normally, application code that needs to use
274a reference object should follow this pattern::
275
276 # r is a weak reference object
277 o = r()
278 if o is None:
279 # referent has been garbage collected
280 print "Object has been deallocated; can't frobnicate."
281 else:
282 print "Object is still live!"
283 o.do_something_useful()
284
285Using a separate test for "liveness" creates race conditions in threaded
286applications; another thread can cause a weak reference to become invalidated
287before the weak reference is called; the idiom shown above is safe in threaded
288applications as well as single-threaded applications.
289
290Specialized versions of :class:`ref` objects can be created through subclassing.
291This is used in the implementation of the :class:`WeakValueDictionary` to reduce
292the memory overhead for each entry in the mapping. This may be most useful to
293associate additional information with a reference, but could also be used to
294insert additional processing on calls to retrieve the referent.
295
296This example shows how a subclass of :class:`ref` can be used to store
297additional information about an object and affect the value that's returned when
298the referent is accessed::
299
300 import weakref
301
302 class ExtendedRef(weakref.ref):
303 def __init__(self, ob, callback=None, **annotations):
304 super(ExtendedRef, self).__init__(ob, callback)
305 self.__counter = 0
306 for k, v in annotations.iteritems():
307 setattr(self, k, v)
308
309 def __call__(self):
310 """Return a pair containing the referent and the number of
311 times the reference has been called.
312 """
313 ob = super(ExtendedRef, self).__call__()
314 if ob is not None:
315 self.__counter += 1
316 ob = (ob, self.__counter)
317 return ob
318
319
320.. _weakref-example:
321
322Example
323-------
324
325This simple example shows how an application can use objects IDs to retrieve
326objects that it has seen before. The IDs of the objects can then be used in
327other data structures without forcing the objects to remain alive, but the
328objects can still be retrieved by ID if they do.
329
Georg Brandlb19be572007-12-29 10:57:00 +0000330.. Example contributed by Tim Peters.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000331
332::
333
334 import weakref
335
336 _id2obj_dict = weakref.WeakValueDictionary()
337
338 def remember(obj):
339 oid = id(obj)
340 _id2obj_dict[oid] = obj
341 return oid
342
343 def id2obj(oid):
344 return _id2obj_dict[oid]
345