blob: dcc5bf3a6b3a91dffdd76b7d7072ca0178cd4c05 [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
Benjamin Petersonbec4d572009-10-10 01:16:07 +000064.. versionchanged:: 3.2
65 Added support for thread.lock and threading.Lock.
66
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
75Extension types can easily be made to support weak references; see
76:ref:`weakref-support`.
77
78
79.. class:: ref(object[, callback])
80
81 Return a weak reference to *object*. The original object can be retrieved by
82 calling the reference object if the referent is still alive; if the referent is
83 no longer alive, calling the reference object will cause :const:`None` to be
84 returned. If *callback* is provided and not :const:`None`, and the returned
85 weakref object is still alive, the callback will be called when the object is
86 about to be finalized; the weak reference object will be passed as the only
87 parameter to the callback; the referent will no longer be available.
88
89 It is allowable for many weak references to be constructed for the same object.
90 Callbacks registered for each weak reference will be called from the most
91 recently registered callback to the oldest registered callback.
92
93 Exceptions raised by the callback will be noted on the standard error output,
94 but cannot be propagated; they are handled in exactly the same way as exceptions
95 raised from an object's :meth:`__del__` method.
96
Georg Brandl7f01a132009-09-16 15:58:14 +000097 Weak references are :term:`hashable` if the *object* is hashable. They will
98 maintain their hash value even after the *object* was deleted. If
99 :func:`hash` is called the first time only after the *object* was deleted,
100 the call will raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 Weak references support tests for equality, but not ordering. If the referents
103 are still alive, two references have the same equality relationship as their
104 referents (regardless of the *callback*). If either referent has been deleted,
105 the references are equal only if the reference objects are the same object.
106
Georg Brandl55ac8f02007-09-01 13:51:09 +0000107 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109
110.. function:: proxy(object[, callback])
111
112 Return a proxy to *object* which uses a weak reference. This supports use of
113 the proxy in most contexts instead of requiring the explicit dereferencing used
114 with weak reference objects. The returned object will have a type of either
115 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000116 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000117 avoids a number of problems related to their fundamentally mutable nature, and
118 prevent their use as dictionary keys. *callback* is the same as the parameter
119 of the same name to the :func:`ref` function.
120
121
122.. function:: getweakrefcount(object)
123
124 Return the number of weak references and proxies which refer to *object*.
125
126
127.. function:: getweakrefs(object)
128
129 Return a list of all weak reference and proxy objects which refer to *object*.
130
131
132.. class:: WeakKeyDictionary([dict])
133
134 Mapping class that references keys weakly. Entries in the dictionary will be
135 discarded when there is no longer a strong reference to the key. This can be
136 used to associate additional data with an object owned by other parts of an
137 application without adding attributes to those objects. This can be especially
138 useful with objects that override attribute accesses.
139
140 .. note::
141
Christian Heimesfe337bf2008-03-23 21:54:12 +0000142 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000143 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000144 difficult to ensure for a :class:`WeakKeyDictionary` because actions
145 performed by the program during iteration may cause items in the
146 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148:class:`WeakKeyDictionary` objects have the following additional methods. These
149expose the internal references directly. The references are not guaranteed to
150be "live" at the time they are used, so the result of calling the references
151needs to be checked before being used. This can be used to avoid creating
152references that will cause the garbage collector to keep the keys around longer
153than needed.
154
155
Georg Brandl116aa622007-08-15 14:28:22 +0000156.. method:: WeakKeyDictionary.keyrefs()
157
Barry Warsawecaab832008-09-04 01:42:51 +0000158 Return an :term:`iterator` that yields the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161.. class:: WeakValueDictionary([dict])
162
163 Mapping class that references values weakly. Entries in the dictionary will be
164 discarded when no strong reference to the value exists any more.
165
166 .. note::
167
168 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
169 dictionary, it must not change size when iterating over it. This can be
170 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
171 by the program during iteration may cause items in the dictionary to vanish "by
172 magic" (as a side effect of garbage collection).
173
174:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000175These method have the same issues as the and :meth:`keyrefs` method of
176:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000177
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179.. method:: WeakValueDictionary.valuerefs()
180
Barry Warsawecaab832008-09-04 01:42:51 +0000181 Return an :term:`iterator` that yields the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Georg Brandl3b8cb172007-10-23 06:26:46 +0000184.. class:: WeakSet([elements])
185
186 Set class that keeps weak references to its elements. An element will be
187 discarded when no strong reference to it exists any more.
188
189
Georg Brandl116aa622007-08-15 14:28:22 +0000190.. data:: ReferenceType
191
192 The type object for weak references objects.
193
194
195.. data:: ProxyType
196
197 The type object for proxies of objects which are not callable.
198
199
200.. data:: CallableProxyType
201
202 The type object for proxies of callable objects.
203
204
205.. data:: ProxyTypes
206
207 Sequence containing all the type objects for proxies. This can make it simpler
208 to test if an object is a proxy without being dependent on naming both proxy
209 types.
210
211
212.. exception:: ReferenceError
213
214 Exception raised when a proxy object is used but the underlying object has been
215 collected. This is the same as the standard :exc:`ReferenceError` exception.
216
217
218.. seealso::
219
220 :pep:`0205` - Weak References
221 The proposal and rationale for this feature, including links to earlier
222 implementations and information about similar features in other languages.
223
224
225.. _weakref-objects:
226
227Weak Reference Objects
228----------------------
229
230Weak reference objects have no attributes or methods, but do allow the referent
Christian Heimesfe337bf2008-03-23 21:54:12 +0000231to be obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233 >>> import weakref
234 >>> class Object:
235 ... pass
236 ...
237 >>> o = Object()
238 >>> r = weakref.ref(o)
239 >>> o2 = r()
240 >>> o is o2
241 True
242
243If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000244:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000247 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000248 None
249
250Testing that a weak reference object is still live should be done using the
251expression ``ref() is not None``. Normally, application code that needs to use
252a reference object should follow this pattern::
253
254 # r is a weak reference object
255 o = r()
256 if o is None:
257 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000258 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000259 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000260 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000261 o.do_something_useful()
262
263Using a separate test for "liveness" creates race conditions in threaded
264applications; another thread can cause a weak reference to become invalidated
265before the weak reference is called; the idiom shown above is safe in threaded
266applications as well as single-threaded applications.
267
268Specialized versions of :class:`ref` objects can be created through subclassing.
269This is used in the implementation of the :class:`WeakValueDictionary` to reduce
270the memory overhead for each entry in the mapping. This may be most useful to
271associate additional information with a reference, but could also be used to
272insert additional processing on calls to retrieve the referent.
273
274This example shows how a subclass of :class:`ref` can be used to store
275additional information about an object and affect the value that's returned when
276the referent is accessed::
277
278 import weakref
279
280 class ExtendedRef(weakref.ref):
281 def __init__(self, ob, callback=None, **annotations):
282 super(ExtendedRef, self).__init__(ob, callback)
283 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000284 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000285 setattr(self, k, v)
286
287 def __call__(self):
288 """Return a pair containing the referent and the number of
289 times the reference has been called.
290 """
291 ob = super(ExtendedRef, self).__call__()
292 if ob is not None:
293 self.__counter += 1
294 ob = (ob, self.__counter)
295 return ob
296
297
298.. _weakref-example:
299
300Example
301-------
302
303This simple example shows how an application can use objects IDs to retrieve
304objects that it has seen before. The IDs of the objects can then be used in
305other data structures without forcing the objects to remain alive, but the
306objects can still be retrieved by ID if they do.
307
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000308.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310::
311
312 import weakref
313
314 _id2obj_dict = weakref.WeakValueDictionary()
315
316 def remember(obj):
317 oid = id(obj)
318 _id2obj_dict[oid] = obj
319 return oid
320
321 def id2obj(oid):
322 return _id2obj_dict[oid]
323