blob: c8eb8998b82d6370bb61de938ff1df98a17ceda0 [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,
Collin Winter4222e9c2010-03-18 22:46:40 +000062deques, regular expression pattern objects, and code objects.
Georg Brandl116aa622007-08-15 14:28:22 +000063
Benjamin Petersonbec4d572009-10-10 01:16:07 +000064.. versionchanged:: 3.2
Collin Winter4222e9c2010-03-18 22:46:40 +000065 Added support for thread.lock, threading.Lock, and code objects.
Benjamin Petersonbec4d572009-10-10 01:16:07 +000066
Georg Brandl22b34312009-07-26 14:54:51 +000067Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl116aa622007-08-15 14:28:22 +000068support weak references but can add support through subclassing::
69
70 class Dict(dict):
71 pass
72
Christian Heimesc3f30c42008-02-22 16:37:40 +000073 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl116aa622007-08-15 14:28:22 +000074
Benjamin Peterson905982b2010-05-08 15:26:30 +000075Other built-in types such as :class:`tuple` and :class:`int` do not support weak
76references even when subclassed (This is an implementation detail and may be
77different across various Python implementations.).
Georg Brandlff8c1e52009-10-21 07:17:48 +000078
Georg Brandl116aa622007-08-15 14:28:22 +000079Extension 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 Brandl7f01a132009-09-16 15:58:14 +0000101 Weak references are :term:`hashable` if the *object* is hashable. They will
102 maintain their hash value even after the *object* was deleted. If
103 :func:`hash` is called the first time only after the *object* was deleted,
104 the call will raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
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
Georg Brandl55ac8f02007-09-01 13:51:09 +0000111 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. function:: proxy(object[, callback])
115
116 Return a proxy to *object* which uses a weak reference. This supports use of
117 the proxy in most contexts instead of requiring the explicit dereferencing used
118 with weak reference objects. The returned object will have a type of either
119 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000120 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000121 avoids a number of problems related to their fundamentally mutable nature, and
122 prevent their use as dictionary keys. *callback* is the same as the parameter
123 of the same name to the :func:`ref` function.
124
125
126.. function:: getweakrefcount(object)
127
128 Return the number of weak references and proxies which refer to *object*.
129
130
131.. function:: getweakrefs(object)
132
133 Return a list of all weak reference and proxy objects which refer to *object*.
134
135
136.. class:: WeakKeyDictionary([dict])
137
138 Mapping class that references keys weakly. Entries in the dictionary will be
139 discarded when there is no longer a strong reference to the key. This can be
140 used to associate additional data with an object owned by other parts of an
141 application without adding attributes to those objects. This can be especially
142 useful with objects that override attribute accesses.
143
144 .. note::
145
Christian Heimesfe337bf2008-03-23 21:54:12 +0000146 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000147 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000148 difficult to ensure for a :class:`WeakKeyDictionary` because actions
149 performed by the program during iteration may cause items in the
150 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152:class:`WeakKeyDictionary` objects have the following additional methods. These
153expose the internal references directly. The references are not guaranteed to
154be "live" at the time they are used, so the result of calling the references
155needs to be checked before being used. This can be used to avoid creating
156references that will cause the garbage collector to keep the keys around longer
157than needed.
158
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160.. method:: WeakKeyDictionary.keyrefs()
161
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000162 Return an iterable of the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. class:: WeakValueDictionary([dict])
166
167 Mapping class that references values weakly. Entries in the dictionary will be
168 discarded when no strong reference to the value exists any more.
169
170 .. note::
171
172 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
173 dictionary, it must not change size when iterating over it. This can be
174 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
175 by the program during iteration may cause items in the dictionary to vanish "by
176 magic" (as a side effect of garbage collection).
177
178:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000179These method have the same issues as the and :meth:`keyrefs` method of
180:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183.. method:: WeakValueDictionary.valuerefs()
184
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000185 Return an iterable of the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000186
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl3b8cb172007-10-23 06:26:46 +0000188.. class:: WeakSet([elements])
189
190 Set class that keeps weak references to its elements. An element will be
191 discarded when no strong reference to it exists any more.
192
193
Georg Brandl116aa622007-08-15 14:28:22 +0000194.. data:: ReferenceType
195
196 The type object for weak references objects.
197
198
199.. data:: ProxyType
200
201 The type object for proxies of objects which are not callable.
202
203
204.. data:: CallableProxyType
205
206 The type object for proxies of callable objects.
207
208
209.. data:: ProxyTypes
210
211 Sequence containing all the type objects for proxies. This can make it simpler
212 to test if an object is a proxy without being dependent on naming both proxy
213 types.
214
215
216.. exception:: ReferenceError
217
218 Exception raised when a proxy object is used but the underlying object has been
219 collected. This is the same as the standard :exc:`ReferenceError` exception.
220
221
222.. seealso::
223
224 :pep:`0205` - Weak References
225 The proposal and rationale for this feature, including links to earlier
226 implementations and information about similar features in other languages.
227
228
229.. _weakref-objects:
230
231Weak Reference Objects
232----------------------
233
234Weak reference objects have no attributes or methods, but do allow the referent
Christian Heimesfe337bf2008-03-23 21:54:12 +0000235to be obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237 >>> import weakref
238 >>> class Object:
239 ... pass
240 ...
241 >>> o = Object()
242 >>> r = weakref.ref(o)
243 >>> o2 = r()
244 >>> o is o2
245 True
246
247If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000248:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000251 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000252 None
253
254Testing that a weak reference object is still live should be done using the
255expression ``ref() is not None``. Normally, application code that needs to use
256a reference object should follow this pattern::
257
258 # r is a weak reference object
259 o = r()
260 if o is None:
261 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000262 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000263 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000264 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000265 o.do_something_useful()
266
267Using a separate test for "liveness" creates race conditions in threaded
268applications; another thread can cause a weak reference to become invalidated
269before the weak reference is called; the idiom shown above is safe in threaded
270applications as well as single-threaded applications.
271
272Specialized versions of :class:`ref` objects can be created through subclassing.
273This is used in the implementation of the :class:`WeakValueDictionary` to reduce
274the memory overhead for each entry in the mapping. This may be most useful to
275associate additional information with a reference, but could also be used to
276insert additional processing on calls to retrieve the referent.
277
278This example shows how a subclass of :class:`ref` can be used to store
279additional information about an object and affect the value that's returned when
280the referent is accessed::
281
282 import weakref
283
284 class ExtendedRef(weakref.ref):
285 def __init__(self, ob, callback=None, **annotations):
286 super(ExtendedRef, self).__init__(ob, callback)
287 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000288 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000289 setattr(self, k, v)
290
291 def __call__(self):
292 """Return a pair containing the referent and the number of
293 times the reference has been called.
294 """
295 ob = super(ExtendedRef, self).__call__()
296 if ob is not None:
297 self.__counter += 1
298 ob = (ob, self.__counter)
299 return ob
300
301
302.. _weakref-example:
303
304Example
305-------
306
307This simple example shows how an application can use objects IDs to retrieve
308objects that it has seen before. The IDs of the objects can then be used in
309other data structures without forcing the objects to remain alive, but the
310objects can still be retrieved by ID if they do.
311
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000312.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314::
315
316 import weakref
317
318 _id2obj_dict = weakref.WeakValueDictionary()
319
320 def remember(obj):
321 oid = id(obj)
322 _id2obj_dict[oid] = obj
323 return oid
324
325 def id2obj(oid):
326 return _id2obj_dict[oid]
327