blob: 195ac95c86a860a0899fbfe97e61d51e4f2c1cac [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000013The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
14references` to objects.
15
Christian Heimes5b5e81c2007-12-31 16:14:33 +000016.. When making changes to the examples in this file, be sure to update
17 Lib/test/test_weakref.py::libreftest too!
Georg Brandl116aa622007-08-15 14:28:22 +000018
19In the following, the term :dfn:`referent` means the object which is referred to
20by a weak reference.
21
22A weak reference to an object is not enough to keep the object alive: when the
Christian Heimesd8654cf2007-12-02 15:22:16 +000023only remaining references to a referent are weak references,
24:term:`garbage collection` is free to destroy the referent and reuse its memory
25for something else. A primary use for weak references is to implement caches or
26mappings holding large objects, where it's desired that a large object not be
27kept alive solely because it appears in a cache or mapping. For example, if you
28have a number of large binary image objects, you may wish to associate a name
29with each. If you used a Python dictionary to map names to images, or images to
30names, the image objects would remain alive just because they appeared as values
31or keys in the dictionaries. The :class:`WeakKeyDictionary` and
32:class:`WeakValueDictionary` classes supplied by the :mod:`weakref` module are
33an alternative, using weak references to construct mappings that don't keep
34objects alive solely because they appear in the mapping objects. If, for
35example, an image object is a value in a :class:`WeakValueDictionary`, then when
36the last remaining references to that image object are the weak references held
37by weak mappings, garbage collection can reclaim the object, and its
38corresponding entries in weak mappings are simply deleted.
Georg Brandl116aa622007-08-15 14:28:22 +000039
40:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
41in their implementation, setting up callback functions on the weak references
42that notify the weak dictionaries when a key or value has been reclaimed by
Georg Brandl3b8cb172007-10-23 06:26:46 +000043garbage collection. :class:`WeakSet` implements the :class:`set` interface,
44but keeps weak references to its elements, just like a
45:class:`WeakKeyDictionary` does.
46
47Most programs should find that using one of these weak container types is all
48they need -- it's not usually necessary to create your own weak references
49directly. The low-level machinery used by the weak dictionary implementations
50is exposed by the :mod:`weakref` module for the benefit of advanced uses.
Georg Brandl116aa622007-08-15 14:28:22 +000051
52Not all objects can be weakly referenced; those objects which can include class
Georg Brandl2e0b7552007-11-27 12:43:08 +000053instances, functions written in Python (but not in C), instance methods, sets,
54frozensets, file objects, :term:`generator`\s, type objects, :class:`DBcursor`
55objects from the :mod:`bsddb` module, sockets, arrays, deques, and regular
56expression pattern objects.
Georg Brandl116aa622007-08-15 14:28:22 +000057
Georg Brandl116aa622007-08-15 14:28:22 +000058Several builtin types such as :class:`list` and :class:`dict` do not directly
59support weak references but can add support through subclassing::
60
61 class Dict(dict):
62 pass
63
64 obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
65
66Extension types can easily be made to support weak references; see
67:ref:`weakref-support`.
68
69
70.. class:: ref(object[, callback])
71
72 Return a weak reference to *object*. The original object can be retrieved by
73 calling the reference object if the referent is still alive; if the referent is
74 no longer alive, calling the reference object will cause :const:`None` to be
75 returned. If *callback* is provided and not :const:`None`, and the returned
76 weakref object is still alive, the callback will be called when the object is
77 about to be finalized; the weak reference object will be passed as the only
78 parameter to the callback; the referent will no longer be available.
79
80 It is allowable for many weak references to be constructed for the same object.
81 Callbacks registered for each weak reference will be called from the most
82 recently registered callback to the oldest registered callback.
83
84 Exceptions raised by the callback will be noted on the standard error output,
85 but cannot be propagated; they are handled in exactly the same way as exceptions
86 raised from an object's :meth:`__del__` method.
87
Guido van Rossum2cc30da2007-11-02 23:46:40 +000088 Weak references are :term:`hashable` if the *object* is hashable. They will maintain
Georg Brandl116aa622007-08-15 14:28:22 +000089 their hash value even after the *object* was deleted. If :func:`hash` is called
90 the first time only after the *object* was deleted, the call will raise
91 :exc:`TypeError`.
92
93 Weak references support tests for equality, but not ordering. If the referents
94 are still alive, two references have the same equality relationship as their
95 referents (regardless of the *callback*). If either referent has been deleted,
96 the references are equal only if the reference objects are the same object.
97
Georg Brandl55ac8f02007-09-01 13:51:09 +000098 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +000099
100
101.. function:: proxy(object[, callback])
102
103 Return a proxy to *object* which uses a weak reference. This supports use of
104 the proxy in most contexts instead of requiring the explicit dereferencing used
105 with weak reference objects. The returned object will have a type of either
106 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000107 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000108 avoids a number of problems related to their fundamentally mutable nature, and
109 prevent their use as dictionary keys. *callback* is the same as the parameter
110 of the same name to the :func:`ref` function.
111
112
113.. function:: getweakrefcount(object)
114
115 Return the number of weak references and proxies which refer to *object*.
116
117
118.. function:: getweakrefs(object)
119
120 Return a list of all weak reference and proxy objects which refer to *object*.
121
122
123.. class:: WeakKeyDictionary([dict])
124
125 Mapping class that references keys weakly. Entries in the dictionary will be
126 discarded when there is no longer a strong reference to the key. This can be
127 used to associate additional data with an object owned by other parts of an
128 application without adding attributes to those objects. This can be especially
129 useful with objects that override attribute accesses.
130
131 .. note::
132
133 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
134 dictionary, it must not change size when iterating over it. This can be
135 difficult to ensure for a :class:`WeakKeyDictionary` because actions performed
136 by the program during iteration may cause items in the dictionary to vanish "by
137 magic" (as a side effect of garbage collection).
138
139:class:`WeakKeyDictionary` objects have the following additional methods. These
140expose the internal references directly. The references are not guaranteed to
141be "live" at the time they are used, so the result of calling the references
142needs to be checked before being used. This can be used to avoid creating
143references that will cause the garbage collector to keep the keys around longer
144than needed.
145
146
147.. method:: WeakKeyDictionary.iterkeyrefs()
148
Georg Brandl9afde1c2007-11-01 20:32:30 +0000149 Return an :term:`iterator` that yields the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152.. method:: WeakKeyDictionary.keyrefs()
153
154 Return a list of weak references to the keys.
155
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157.. class:: WeakValueDictionary([dict])
158
159 Mapping class that references values weakly. Entries in the dictionary will be
160 discarded when no strong reference to the value exists any more.
161
162 .. note::
163
164 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
165 dictionary, it must not change size when iterating over it. This can be
166 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
167 by the program during iteration may cause items in the dictionary to vanish "by
168 magic" (as a side effect of garbage collection).
169
170:class:`WeakValueDictionary` objects have the following additional methods.
171These method have the same issues as the :meth:`iterkeyrefs` and :meth:`keyrefs`
172methods of :class:`WeakKeyDictionary` objects.
173
174
175.. method:: WeakValueDictionary.itervaluerefs()
176
Georg Brandl9afde1c2007-11-01 20:32:30 +0000177 Return an :term:`iterator` that yields the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180.. method:: WeakValueDictionary.valuerefs()
181
182 Return a list of weak references to the values.
183
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Georg Brandl3b8cb172007-10-23 06:26:46 +0000185.. class:: WeakSet([elements])
186
187 Set class that keeps weak references to its elements. An element will be
188 discarded when no strong reference to it exists any more.
189
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191.. data:: ReferenceType
192
193 The type object for weak references objects.
194
195
196.. data:: ProxyType
197
198 The type object for proxies of objects which are not callable.
199
200
201.. data:: CallableProxyType
202
203 The type object for proxies of callable objects.
204
205
206.. data:: ProxyTypes
207
208 Sequence containing all the type objects for proxies. This can make it simpler
209 to test if an object is a proxy without being dependent on naming both proxy
210 types.
211
212
213.. exception:: ReferenceError
214
215 Exception raised when a proxy object is used but the underlying object has been
216 collected. This is the same as the standard :exc:`ReferenceError` exception.
217
218
219.. seealso::
220
221 :pep:`0205` - Weak References
222 The proposal and rationale for this feature, including links to earlier
223 implementations and information about similar features in other languages.
224
225
226.. _weakref-objects:
227
228Weak Reference Objects
229----------------------
230
231Weak reference objects have no attributes or methods, but do allow the referent
232to be obtained, if it still exists, by calling it::
233
234 >>> import weakref
235 >>> class Object:
236 ... pass
237 ...
238 >>> o = Object()
239 >>> r = weakref.ref(o)
240 >>> o2 = r()
241 >>> o is o2
242 True
243
244If the referent no longer exists, calling the reference object returns
245:const:`None`::
246
247 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000248 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000249 None
250
251Testing that a weak reference object is still live should be done using the
252expression ``ref() is not None``. Normally, application code that needs to use
253a reference object should follow this pattern::
254
255 # r is a weak reference object
256 o = r()
257 if o is None:
258 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000259 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000260 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000261 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000262 o.do_something_useful()
263
264Using a separate test for "liveness" creates race conditions in threaded
265applications; another thread can cause a weak reference to become invalidated
266before the weak reference is called; the idiom shown above is safe in threaded
267applications as well as single-threaded applications.
268
269Specialized versions of :class:`ref` objects can be created through subclassing.
270This is used in the implementation of the :class:`WeakValueDictionary` to reduce
271the memory overhead for each entry in the mapping. This may be most useful to
272associate additional information with a reference, but could also be used to
273insert additional processing on calls to retrieve the referent.
274
275This example shows how a subclass of :class:`ref` can be used to store
276additional information about an object and affect the value that's returned when
277the referent is accessed::
278
279 import weakref
280
281 class ExtendedRef(weakref.ref):
282 def __init__(self, ob, callback=None, **annotations):
283 super(ExtendedRef, self).__init__(ob, callback)
284 self.__counter = 0
285 for k, v in annotations.iteritems():
286 setattr(self, k, v)
287
288 def __call__(self):
289 """Return a pair containing the referent and the number of
290 times the reference has been called.
291 """
292 ob = super(ExtendedRef, self).__call__()
293 if ob is not None:
294 self.__counter += 1
295 ob = (ob, self.__counter)
296 return ob
297
298
299.. _weakref-example:
300
301Example
302-------
303
304This simple example shows how an application can use objects IDs to retrieve
305objects that it has seen before. The IDs of the objects can then be used in
306other data structures without forcing the objects to remain alive, but the
307objects can still be retrieved by ID if they do.
308
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000309.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311::
312
313 import weakref
314
315 _id2obj_dict = weakref.WeakValueDictionary()
316
317 def remember(obj):
318 oid = id(obj)
319 _id2obj_dict[oid] = obj
320 return oid
321
322 def id2obj(oid):
323 return _id2obj_dict[oid]
324