blob: 10b69c98c012a6740c8607e70c1c73ca60206dfe [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,
Antoine Pitrou25d535e2010-09-15 11:25:11 +000061frozensets, some :term:`file objects <file object>`, :term:`generator`\s, type
62objects, sockets, arrays, deques and regular expression pattern objects.
63
Georg Brandl116aa622007-08-15 14:28:22 +000064
Georg Brandlc5605df2009-08-13 08:26:44 +000065Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl116aa622007-08-15 14:28:22 +000066support weak references but can add support through subclassing::
67
68 class Dict(dict):
69 pass
70
Christian Heimesc3f30c42008-02-22 16:37:40 +000071 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl116aa622007-08-15 14:28:22 +000072
Benjamin Peterson3a3bba32010-05-08 15:29:41 +000073Other built-in types such as :class:`tuple` and :class:`int` do not support weak
74references even when subclassed (This is an implementation detail and may be
75different across various Python implementations.).
Georg Brandl1e8cbe32009-10-27 20:23:20 +000076
Georg Brandl116aa622007-08-15 14:28:22 +000077Extension types can easily be made to support weak references; see
78:ref:`weakref-support`.
79
80
81.. class:: ref(object[, callback])
82
83 Return a weak reference to *object*. The original object can be retrieved by
84 calling the reference object if the referent is still alive; if the referent is
85 no longer alive, calling the reference object will cause :const:`None` to be
86 returned. If *callback* is provided and not :const:`None`, and the returned
87 weakref object is still alive, the callback will be called when the object is
88 about to be finalized; the weak reference object will be passed as the only
89 parameter to the callback; the referent will no longer be available.
90
91 It is allowable for many weak references to be constructed for the same object.
92 Callbacks registered for each weak reference will be called from the most
93 recently registered callback to the oldest registered callback.
94
95 Exceptions raised by the callback will be noted on the standard error output,
96 but cannot be propagated; they are handled in exactly the same way as exceptions
97 raised from an object's :meth:`__del__` method.
98
Georg Brandlb044b2a2009-09-16 16:05:59 +000099 Weak references are :term:`hashable` if the *object* is hashable. They will
100 maintain their hash value even after the *object* was deleted. If
101 :func:`hash` is called the first time only after the *object* was deleted,
102 the call will raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104 Weak references support tests for equality, but not ordering. If the referents
105 are still alive, two references have the same equality relationship as their
106 referents (regardless of the *callback*). If either referent has been deleted,
107 the references are equal only if the reference objects are the same object.
108
Georg Brandl55ac8f02007-09-01 13:51:09 +0000109 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111
112.. function:: proxy(object[, callback])
113
114 Return a proxy to *object* which uses a weak reference. This supports use of
115 the proxy in most contexts instead of requiring the explicit dereferencing used
116 with weak reference objects. The returned object will have a type of either
117 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000118 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000119 avoids a number of problems related to their fundamentally mutable nature, and
120 prevent their use as dictionary keys. *callback* is the same as the parameter
121 of the same name to the :func:`ref` function.
122
123
124.. function:: getweakrefcount(object)
125
126 Return the number of weak references and proxies which refer to *object*.
127
128
129.. function:: getweakrefs(object)
130
131 Return a list of all weak reference and proxy objects which refer to *object*.
132
133
134.. class:: WeakKeyDictionary([dict])
135
136 Mapping class that references keys weakly. Entries in the dictionary will be
137 discarded when there is no longer a strong reference to the key. This can be
138 used to associate additional data with an object owned by other parts of an
139 application without adding attributes to those objects. This can be especially
140 useful with objects that override attribute accesses.
141
142 .. note::
143
Christian Heimesfe337bf2008-03-23 21:54:12 +0000144 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000145 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000146 difficult to ensure for a :class:`WeakKeyDictionary` because actions
147 performed by the program during iteration may cause items in the
148 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150:class:`WeakKeyDictionary` objects have the following additional methods. These
151expose the internal references directly. The references are not guaranteed to
152be "live" at the time they are used, so the result of calling the references
153needs to be checked before being used. This can be used to avoid creating
154references that will cause the garbage collector to keep the keys around longer
155than needed.
156
157
Georg Brandl116aa622007-08-15 14:28:22 +0000158.. method:: WeakKeyDictionary.keyrefs()
159
Antoine Pitrou1a2d3562010-01-08 17:56:16 +0000160 Return an iterable of the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Georg Brandl116aa622007-08-15 14:28:22 +0000162
163.. class:: WeakValueDictionary([dict])
164
165 Mapping class that references values weakly. Entries in the dictionary will be
166 discarded when no strong reference to the value exists any more.
167
168 .. note::
169
170 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
171 dictionary, it must not change size when iterating over it. This can be
172 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
173 by the program during iteration may cause items in the dictionary to vanish "by
174 magic" (as a side effect of garbage collection).
175
176:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000177These method have the same issues as the and :meth:`keyrefs` method of
178:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181.. method:: WeakValueDictionary.valuerefs()
182
Antoine Pitrou1a2d3562010-01-08 17:56:16 +0000183 Return an iterable of the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Georg Brandl3b8cb172007-10-23 06:26:46 +0000186.. class:: WeakSet([elements])
187
188 Set class that keeps weak references to its elements. An element will be
189 discarded when no strong reference to it exists any more.
190
191
Georg Brandl116aa622007-08-15 14:28:22 +0000192.. data:: ReferenceType
193
194 The type object for weak references objects.
195
196
197.. data:: ProxyType
198
199 The type object for proxies of objects which are not callable.
200
201
202.. data:: CallableProxyType
203
204 The type object for proxies of callable objects.
205
206
207.. data:: ProxyTypes
208
209 Sequence containing all the type objects for proxies. This can make it simpler
210 to test if an object is a proxy without being dependent on naming both proxy
211 types.
212
213
214.. exception:: ReferenceError
215
216 Exception raised when a proxy object is used but the underlying object has been
217 collected. This is the same as the standard :exc:`ReferenceError` exception.
218
219
220.. seealso::
221
222 :pep:`0205` - Weak References
223 The proposal and rationale for this feature, including links to earlier
224 implementations and information about similar features in other languages.
225
226
227.. _weakref-objects:
228
229Weak Reference Objects
230----------------------
231
232Weak reference objects have no attributes or methods, but do allow the referent
Christian Heimesfe337bf2008-03-23 21:54:12 +0000233to be obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000234
235 >>> import weakref
236 >>> class Object:
237 ... pass
238 ...
239 >>> o = Object()
240 >>> r = weakref.ref(o)
241 >>> o2 = r()
242 >>> o is o2
243 True
244
245If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000246:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000249 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000250 None
251
252Testing that a weak reference object is still live should be done using the
253expression ``ref() is not None``. Normally, application code that needs to use
254a reference object should follow this pattern::
255
256 # r is a weak reference object
257 o = r()
258 if o is None:
259 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000260 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000261 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000262 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000263 o.do_something_useful()
264
265Using a separate test for "liveness" creates race conditions in threaded
266applications; another thread can cause a weak reference to become invalidated
267before the weak reference is called; the idiom shown above is safe in threaded
268applications as well as single-threaded applications.
269
270Specialized versions of :class:`ref` objects can be created through subclassing.
271This is used in the implementation of the :class:`WeakValueDictionary` to reduce
272the memory overhead for each entry in the mapping. This may be most useful to
273associate additional information with a reference, but could also be used to
274insert additional processing on calls to retrieve the referent.
275
276This example shows how a subclass of :class:`ref` can be used to store
277additional information about an object and affect the value that's returned when
278the referent is accessed::
279
280 import weakref
281
282 class ExtendedRef(weakref.ref):
283 def __init__(self, ob, callback=None, **annotations):
284 super(ExtendedRef, self).__init__(ob, callback)
285 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000286 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000287 setattr(self, k, v)
288
289 def __call__(self):
290 """Return a pair containing the referent and the number of
291 times the reference has been called.
292 """
293 ob = super(ExtendedRef, self).__call__()
294 if ob is not None:
295 self.__counter += 1
296 ob = (ob, self.__counter)
297 return ob
298
299
300.. _weakref-example:
301
302Example
303-------
304
305This simple example shows how an application can use objects IDs to retrieve
306objects that it has seen before. The IDs of the objects can then be used in
307other data structures without forcing the objects to remain alive, but the
308objects can still be retrieved by ID if they do.
309
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000310.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312::
313
314 import weakref
315
316 _id2obj_dict = weakref.WeakValueDictionary()
317
318 def remember(obj):
319 oid = id(obj)
320 _id2obj_dict[oid] = obj
321 return oid
322
323 def id2obj(oid):
324 return _id2obj_dict[oid]
325