blob: 612e56f9bab42d4a88c9686c757218c70475db35 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
13references` to objects.
14
Christian Heimes5b5e81c2007-12-31 16:14:33 +000015.. When making changes to the examples in this file, be sure to update
16 Lib/test/test_weakref.py::libreftest too!
Georg Brandl116aa622007-08-15 14:28:22 +000017
18In the following, the term :dfn:`referent` means the object which is referred to
19by a weak reference.
20
21A weak reference to an object is not enough to keep the object alive: when the
Christian Heimesd8654cf2007-12-02 15:22:16 +000022only remaining references to a referent are weak references,
23:term:`garbage collection` is free to destroy the referent and reuse its memory
24for something else. A primary use for weak references is to implement caches or
25mappings holding large objects, where it's desired that a large object not be
Christian Heimesfe337bf2008-03-23 21:54:12 +000026kept alive solely because it appears in a cache or mapping.
27
28For example, if you have a number of large binary image objects, you may wish to
29associate a name with each. If you used a Python dictionary to map names to
30images, or images to names, the image objects would remain alive just because
31they appeared as values or keys in the dictionaries. The
32:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
33the :mod:`weakref` module are an alternative, using weak references to construct
34mappings that don't keep objects alive solely because they appear in the mapping
35objects. If, for example, an image object is a value in a
36:class:`WeakValueDictionary`, then when the last remaining references to that
37image object are the weak references held by weak mappings, garbage collection
38can reclaim the object, and its corresponding entries in weak mappings are
39simply deleted.
Georg Brandl116aa622007-08-15 14:28:22 +000040
41:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
42in their implementation, setting up callback functions on the weak references
43that notify the weak dictionaries when a key or value has been reclaimed by
Georg Brandl3b8cb172007-10-23 06:26:46 +000044garbage collection. :class:`WeakSet` implements the :class:`set` interface,
45but keeps weak references to its elements, just like a
46:class:`WeakKeyDictionary` does.
47
48Most programs should find that using one of these weak container types is all
49they need -- it's not usually necessary to create your own weak references
50directly. The low-level machinery used by the weak dictionary implementations
51is exposed by the :mod:`weakref` module for the benefit of advanced uses.
Georg Brandl116aa622007-08-15 14:28:22 +000052
Christian Heimesfe337bf2008-03-23 21:54:12 +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 Brandl116aa622007-08-15 14:28:22 +000059Not all objects can be weakly referenced; those objects which can include class
Georg Brandl2e0b7552007-11-27 12:43:08 +000060instances, functions written in Python (but not in C), instance methods, sets,
Georg Brandl1158a332009-06-04 09:30:30 +000061frozensets, file objects, :term:`generator`\s, type objects, sockets, arrays,
62deques, and regular expression pattern objects.
Georg Brandl116aa622007-08-15 14:28:22 +000063
Georg Brandlc5605df2009-08-13 08:26:44 +000064Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl116aa622007-08-15 14:28:22 +000065support weak references but can add support through subclassing::
66
67 class Dict(dict):
68 pass
69
Christian Heimesc3f30c42008-02-22 16:37:40 +000070 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl116aa622007-08-15 14:28:22 +000071
Benjamin Peterson3a3bba32010-05-08 15:29:41 +000072Other built-in types such as :class:`tuple` and :class:`int` do not support weak
73references even when subclassed (This is an implementation detail and may be
74different across various Python implementations.).
Georg Brandl1e8cbe32009-10-27 20:23:20 +000075
Georg Brandl116aa622007-08-15 14:28:22 +000076Extension types can easily be made to support weak references; see
77:ref:`weakref-support`.
78
79
80.. class:: ref(object[, callback])
81
82 Return a weak reference to *object*. The original object can be retrieved by
83 calling the reference object if the referent is still alive; if the referent is
84 no longer alive, calling the reference object will cause :const:`None` to be
85 returned. If *callback* is provided and not :const:`None`, and the returned
86 weakref object is still alive, the callback will be called when the object is
87 about to be finalized; the weak reference object will be passed as the only
88 parameter to the callback; the referent will no longer be available.
89
90 It is allowable for many weak references to be constructed for the same object.
91 Callbacks registered for each weak reference will be called from the most
92 recently registered callback to the oldest registered callback.
93
94 Exceptions raised by the callback will be noted on the standard error output,
95 but cannot be propagated; they are handled in exactly the same way as exceptions
96 raised from an object's :meth:`__del__` method.
97
Georg Brandlb044b2a2009-09-16 16:05:59 +000098 Weak references are :term:`hashable` if the *object* is hashable. They will
99 maintain their hash value even after the *object* was deleted. If
100 :func:`hash` is called the first time only after the *object* was deleted,
101 the call will raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103 Weak references support tests for equality, but not ordering. If the referents
104 are still alive, two references have the same equality relationship as their
105 referents (regardless of the *callback*). If either referent has been deleted,
106 the references are equal only if the reference objects are the same object.
107
Georg Brandl55ac8f02007-09-01 13:51:09 +0000108 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110
111.. function:: proxy(object[, callback])
112
113 Return a proxy to *object* which uses a weak reference. This supports use of
114 the proxy in most contexts instead of requiring the explicit dereferencing used
115 with weak reference objects. The returned object will have a type of either
116 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000117 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000118 avoids a number of problems related to their fundamentally mutable nature, and
119 prevent their use as dictionary keys. *callback* is the same as the parameter
120 of the same name to the :func:`ref` function.
121
122
123.. function:: getweakrefcount(object)
124
125 Return the number of weak references and proxies which refer to *object*.
126
127
128.. function:: getweakrefs(object)
129
130 Return a list of all weak reference and proxy objects which refer to *object*.
131
132
133.. class:: WeakKeyDictionary([dict])
134
135 Mapping class that references keys weakly. Entries in the dictionary will be
136 discarded when there is no longer a strong reference to the key. This can be
137 used to associate additional data with an object owned by other parts of an
138 application without adding attributes to those objects. This can be especially
139 useful with objects that override attribute accesses.
140
141 .. note::
142
Christian Heimesfe337bf2008-03-23 21:54:12 +0000143 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000144 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000145 difficult to ensure for a :class:`WeakKeyDictionary` because actions
146 performed by the program during iteration may cause items in the
147 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149:class:`WeakKeyDictionary` objects have the following additional methods. These
150expose the internal references directly. The references are not guaranteed to
151be "live" at the time they are used, so the result of calling the references
152needs to be checked before being used. This can be used to avoid creating
153references that will cause the garbage collector to keep the keys around longer
154than needed.
155
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157.. method:: WeakKeyDictionary.keyrefs()
158
Antoine Pitrou1a2d3562010-01-08 17:56:16 +0000159 Return an iterable of the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162.. class:: WeakValueDictionary([dict])
163
164 Mapping class that references values weakly. Entries in the dictionary will be
165 discarded when no strong reference to the value exists any more.
166
167 .. note::
168
169 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
170 dictionary, it must not change size when iterating over it. This can be
171 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
172 by the program during iteration may cause items in the dictionary to vanish "by
173 magic" (as a side effect of garbage collection).
174
175:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000176These method have the same issues as the and :meth:`keyrefs` method of
177:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180.. method:: WeakValueDictionary.valuerefs()
181
Antoine Pitrou1a2d3562010-01-08 17:56:16 +0000182 Return an iterable of the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000183
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
Christian Heimesfe337bf2008-03-23 21:54:12 +0000232to be obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000233
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
Christian Heimesfe337bf2008-03-23 21:54:12 +0000245:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000246
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
Barry Warsawecaab832008-09-04 01:42:51 +0000285 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000286 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