blob: 7c7be951b01842c267636596d391bee3f2eb012f [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
Christian Heimesfe337bf2008-03-23 21:54:12 +000027kept alive solely because it appears in a cache or mapping.
28
29For example, if you have a number of large binary image objects, you may wish to
30associate a name with each. If you used a Python dictionary to map names to
31images, or images to names, the image objects would remain alive just because
32they appeared as values or keys in the dictionaries. The
33:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
34the :mod:`weakref` module are an alternative, using weak references to construct
35mappings that don't keep objects alive solely because they appear in the mapping
36objects. If, for example, an image object is a value in a
37:class:`WeakValueDictionary`, then when the last remaining references to that
38image object are the weak references held by weak mappings, garbage collection
39can reclaim the object, and its corresponding entries in weak mappings are
40simply deleted.
Georg Brandl116aa622007-08-15 14:28:22 +000041
42:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
43in their implementation, setting up callback functions on the weak references
44that notify the weak dictionaries when a key or value has been reclaimed by
Georg Brandl3b8cb172007-10-23 06:26:46 +000045garbage collection. :class:`WeakSet` implements the :class:`set` interface,
46but keeps weak references to its elements, just like a
47:class:`WeakKeyDictionary` does.
48
49Most programs should find that using one of these weak container types is all
50they need -- it's not usually necessary to create your own weak references
51directly. The low-level machinery used by the weak dictionary implementations
52is exposed by the :mod:`weakref` module for the benefit of advanced uses.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Christian Heimesfe337bf2008-03-23 21:54:12 +000054.. note::
55
56 Weak references to an object are cleared before the object's :meth:`__del__`
57 is called, to ensure that the weak reference callback (if any) finds the
58 object still alive.
59
Georg Brandl116aa622007-08-15 14:28:22 +000060Not all objects can be weakly referenced; those objects which can include class
Georg Brandl2e0b7552007-11-27 12:43:08 +000061instances, functions written in Python (but not in C), instance methods, sets,
Georg Brandl1158a332009-06-04 09:30:30 +000062frozensets, file objects, :term:`generator`\s, type objects, sockets, arrays,
63deques, and regular expression pattern objects.
Georg Brandl116aa622007-08-15 14:28:22 +000064
Georg Brandl22b34312009-07-26 14:54:51 +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
73Extension types can easily be made to support weak references; see
74:ref:`weakref-support`.
75
76
77.. class:: ref(object[, callback])
78
79 Return a weak reference to *object*. The original object can be retrieved by
80 calling the reference object if the referent is still alive; if the referent is
81 no longer alive, calling the reference object will cause :const:`None` to be
82 returned. If *callback* is provided and not :const:`None`, and the returned
83 weakref object is still alive, the callback will be called when the object is
84 about to be finalized; the weak reference object will be passed as the only
85 parameter to the callback; the referent will no longer be available.
86
87 It is allowable for many weak references to be constructed for the same object.
88 Callbacks registered for each weak reference will be called from the most
89 recently registered callback to the oldest registered callback.
90
91 Exceptions raised by the callback will be noted on the standard error output,
92 but cannot be propagated; they are handled in exactly the same way as exceptions
93 raised from an object's :meth:`__del__` method.
94
Guido van Rossum2cc30da2007-11-02 23:46:40 +000095 Weak references are :term:`hashable` if the *object* is hashable. They will maintain
Georg Brandl116aa622007-08-15 14:28:22 +000096 their hash value even after the *object* was deleted. If :func:`hash` is called
97 the first time only after the *object* was deleted, the call will raise
98 :exc:`TypeError`.
99
100 Weak references support tests for equality, but not ordering. If the referents
101 are still alive, two references have the same equality relationship as their
102 referents (regardless of the *callback*). If either referent has been deleted,
103 the references are equal only if the reference objects are the same object.
104
Georg Brandl55ac8f02007-09-01 13:51:09 +0000105 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107
108.. function:: proxy(object[, callback])
109
110 Return a proxy to *object* which uses a weak reference. This supports use of
111 the proxy in most contexts instead of requiring the explicit dereferencing used
112 with weak reference objects. The returned object will have a type of either
113 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000114 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000115 avoids a number of problems related to their fundamentally mutable nature, and
116 prevent their use as dictionary keys. *callback* is the same as the parameter
117 of the same name to the :func:`ref` function.
118
119
120.. function:: getweakrefcount(object)
121
122 Return the number of weak references and proxies which refer to *object*.
123
124
125.. function:: getweakrefs(object)
126
127 Return a list of all weak reference and proxy objects which refer to *object*.
128
129
130.. class:: WeakKeyDictionary([dict])
131
132 Mapping class that references keys weakly. Entries in the dictionary will be
133 discarded when there is no longer a strong reference to the key. This can be
134 used to associate additional data with an object owned by other parts of an
135 application without adding attributes to those objects. This can be especially
136 useful with objects that override attribute accesses.
137
138 .. note::
139
Christian Heimesfe337bf2008-03-23 21:54:12 +0000140 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000141 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000142 difficult to ensure for a :class:`WeakKeyDictionary` because actions
143 performed by the program during iteration may cause items in the
144 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146:class:`WeakKeyDictionary` objects have the following additional methods. These
147expose the internal references directly. The references are not guaranteed to
148be "live" at the time they are used, so the result of calling the references
149needs to be checked before being used. This can be used to avoid creating
150references that will cause the garbage collector to keep the keys around longer
151than needed.
152
153
Georg Brandl116aa622007-08-15 14:28:22 +0000154.. method:: WeakKeyDictionary.keyrefs()
155
Barry Warsawecaab832008-09-04 01:42:51 +0000156 Return an :term:`iterator` that yields the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159.. class:: WeakValueDictionary([dict])
160
161 Mapping class that references values weakly. Entries in the dictionary will be
162 discarded when no strong reference to the value exists any more.
163
164 .. note::
165
166 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
167 dictionary, it must not change size when iterating over it. This can be
168 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
169 by the program during iteration may cause items in the dictionary to vanish "by
170 magic" (as a side effect of garbage collection).
171
172:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000173These method have the same issues as the and :meth:`keyrefs` method of
174:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Georg Brandl116aa622007-08-15 14:28:22 +0000176
177.. method:: WeakValueDictionary.valuerefs()
178
Barry Warsawecaab832008-09-04 01:42:51 +0000179 Return an :term:`iterator` that yields the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Georg Brandl3b8cb172007-10-23 06:26:46 +0000182.. class:: WeakSet([elements])
183
184 Set class that keeps weak references to its elements. An element will be
185 discarded when no strong reference to it exists any more.
186
187
Georg Brandl116aa622007-08-15 14:28:22 +0000188.. data:: ReferenceType
189
190 The type object for weak references objects.
191
192
193.. data:: ProxyType
194
195 The type object for proxies of objects which are not callable.
196
197
198.. data:: CallableProxyType
199
200 The type object for proxies of callable objects.
201
202
203.. data:: ProxyTypes
204
205 Sequence containing all the type objects for proxies. This can make it simpler
206 to test if an object is a proxy without being dependent on naming both proxy
207 types.
208
209
210.. exception:: ReferenceError
211
212 Exception raised when a proxy object is used but the underlying object has been
213 collected. This is the same as the standard :exc:`ReferenceError` exception.
214
215
216.. seealso::
217
218 :pep:`0205` - Weak References
219 The proposal and rationale for this feature, including links to earlier
220 implementations and information about similar features in other languages.
221
222
223.. _weakref-objects:
224
225Weak Reference Objects
226----------------------
227
228Weak reference objects have no attributes or methods, but do allow the referent
Christian Heimesfe337bf2008-03-23 21:54:12 +0000229to be obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231 >>> import weakref
232 >>> class Object:
233 ... pass
234 ...
235 >>> o = Object()
236 >>> r = weakref.ref(o)
237 >>> o2 = r()
238 >>> o is o2
239 True
240
241If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000242:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000245 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000246 None
247
248Testing that a weak reference object is still live should be done using the
249expression ``ref() is not None``. Normally, application code that needs to use
250a reference object should follow this pattern::
251
252 # r is a weak reference object
253 o = r()
254 if o is None:
255 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000256 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000257 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000258 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000259 o.do_something_useful()
260
261Using a separate test for "liveness" creates race conditions in threaded
262applications; another thread can cause a weak reference to become invalidated
263before the weak reference is called; the idiom shown above is safe in threaded
264applications as well as single-threaded applications.
265
266Specialized versions of :class:`ref` objects can be created through subclassing.
267This is used in the implementation of the :class:`WeakValueDictionary` to reduce
268the memory overhead for each entry in the mapping. This may be most useful to
269associate additional information with a reference, but could also be used to
270insert additional processing on calls to retrieve the referent.
271
272This example shows how a subclass of :class:`ref` can be used to store
273additional information about an object and affect the value that's returned when
274the referent is accessed::
275
276 import weakref
277
278 class ExtendedRef(weakref.ref):
279 def __init__(self, ob, callback=None, **annotations):
280 super(ExtendedRef, self).__init__(ob, callback)
281 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000282 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000283 setattr(self, k, v)
284
285 def __call__(self):
286 """Return a pair containing the referent and the number of
287 times the reference has been called.
288 """
289 ob = super(ExtendedRef, self).__call__()
290 if ob is not None:
291 self.__counter += 1
292 ob = (ob, self.__counter)
293 return ob
294
295
296.. _weakref-example:
297
298Example
299-------
300
301This simple example shows how an application can use objects IDs to retrieve
302objects that it has seen before. The IDs of the objects can then be used in
303other data structures without forcing the objects to remain alive, but the
304objects can still be retrieved by ID if they do.
305
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000306.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308::
309
310 import weakref
311
312 _id2obj_dict = weakref.WeakValueDictionary()
313
314 def remember(obj):
315 oid = id(obj)
316 _id2obj_dict[oid] = obj
317 return oid
318
319 def id2obj(oid):
320 return _id2obj_dict[oid]
321