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