blob: 1bf6b58770878168475c09c2bfe5bdc4633beb9f [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
Raymond Hettinger469271d2011-01-27 20:38:46 +000011**Source code:** :source:`Lib/weakref.py`
12
13--------------
Georg Brandl116aa622007-08-15 14:28:22 +000014
Georg Brandl116aa622007-08-15 14:28:22 +000015The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
16references` to objects.
17
Christian Heimes5b5e81c2007-12-31 16:14:33 +000018.. When making changes to the examples in this file, be sure to update
19 Lib/test/test_weakref.py::libreftest too!
Georg Brandl116aa622007-08-15 14:28:22 +000020
21In the following, the term :dfn:`referent` means the object which is referred to
22by a weak reference.
23
24A weak reference to an object is not enough to keep the object alive: when the
Christian Heimesd8654cf2007-12-02 15:22:16 +000025only remaining references to a referent are weak references,
26:term:`garbage collection` is free to destroy the referent and reuse its memory
Antoine Pitrou9439f042012-08-21 00:07:07 +020027for something else. However, until the object is actually destroyed the weak
28reference may return the object even if there are no strong references to it.
29
30A primary use for weak references is to implement caches or
Christian Heimesd8654cf2007-12-02 15:22:16 +000031mappings holding large objects, where it's desired that a large object not be
Christian Heimesfe337bf2008-03-23 21:54:12 +000032kept alive solely because it appears in a cache or mapping.
33
34For example, if you have a number of large binary image objects, you may wish to
35associate a name with each. If you used a Python dictionary to map names to
36images, or images to names, the image objects would remain alive just because
37they appeared as values or keys in the dictionaries. The
38:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
39the :mod:`weakref` module are an alternative, using weak references to construct
40mappings that don't keep objects alive solely because they appear in the mapping
41objects. If, for example, an image object is a value in a
42:class:`WeakValueDictionary`, then when the last remaining references to that
43image object are the weak references held by weak mappings, garbage collection
44can reclaim the object, and its corresponding entries in weak mappings are
45simply deleted.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
48in their implementation, setting up callback functions on the weak references
49that notify the weak dictionaries when a key or value has been reclaimed by
Georg Brandl3b8cb172007-10-23 06:26:46 +000050garbage collection. :class:`WeakSet` implements the :class:`set` interface,
51but keeps weak references to its elements, just like a
52:class:`WeakKeyDictionary` does.
53
54Most programs should find that using one of these weak container types is all
55they need -- it's not usually necessary to create your own weak references
56directly. The low-level machinery used by the weak dictionary implementations
57is exposed by the :mod:`weakref` module for the benefit of advanced uses.
Georg Brandl116aa622007-08-15 14:28:22 +000058
59Not 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 Pitrou11cb9612010-09-15 11:11:28 +000061frozensets, some :term:`file objects <file object>`, :term:`generator`\s, type
62objects, sockets, arrays, deques, regular expression pattern objects, and code
63objects.
Georg Brandl116aa622007-08-15 14:28:22 +000064
Benjamin Petersonbec4d572009-10-10 01:16:07 +000065.. versionchanged:: 3.2
Collin Winter4222e9c2010-03-18 22:46:40 +000066 Added support for thread.lock, threading.Lock, and code objects.
Benjamin Petersonbec4d572009-10-10 01:16:07 +000067
Georg Brandl22b34312009-07-26 14:54:51 +000068Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl116aa622007-08-15 14:28:22 +000069support weak references but can add support through subclassing::
70
71 class Dict(dict):
72 pass
73
Christian Heimesc3f30c42008-02-22 16:37:40 +000074 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl116aa622007-08-15 14:28:22 +000075
Benjamin Peterson905982b2010-05-08 15:26:30 +000076Other built-in types such as :class:`tuple` and :class:`int` do not support weak
77references even when subclassed (This is an implementation detail and may be
78different across various Python implementations.).
Georg Brandlff8c1e52009-10-21 07:17:48 +000079
Georg Brandl116aa622007-08-15 14:28:22 +000080Extension types can easily be made to support weak references; see
81:ref:`weakref-support`.
82
83
84.. class:: ref(object[, callback])
85
86 Return a weak reference to *object*. The original object can be retrieved by
87 calling the reference object if the referent is still alive; if the referent is
88 no longer alive, calling the reference object will cause :const:`None` to be
89 returned. If *callback* is provided and not :const:`None`, and the returned
90 weakref object is still alive, the callback will be called when the object is
91 about to be finalized; the weak reference object will be passed as the only
92 parameter to the callback; the referent will no longer be available.
93
94 It is allowable for many weak references to be constructed for the same object.
95 Callbacks registered for each weak reference will be called from the most
96 recently registered callback to the oldest registered callback.
97
98 Exceptions raised by the callback will be noted on the standard error output,
99 but cannot be propagated; they are handled in exactly the same way as exceptions
100 raised from an object's :meth:`__del__` method.
101
Georg Brandl7f01a132009-09-16 15:58:14 +0000102 Weak references are :term:`hashable` if the *object* is hashable. They will
103 maintain their hash value even after the *object* was deleted. If
104 :func:`hash` is called the first time only after the *object* was deleted,
105 the call will raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107 Weak references support tests for equality, but not ordering. If the referents
108 are still alive, two references have the same equality relationship as their
109 referents (regardless of the *callback*). If either referent has been deleted,
110 the references are equal only if the reference objects are the same object.
111
Georg Brandl55ac8f02007-09-01 13:51:09 +0000112 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114
115.. function:: proxy(object[, callback])
116
117 Return a proxy to *object* which uses a weak reference. This supports use of
118 the proxy in most contexts instead of requiring the explicit dereferencing used
119 with weak reference objects. The returned object will have a type of either
120 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000121 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000122 avoids a number of problems related to their fundamentally mutable nature, and
123 prevent their use as dictionary keys. *callback* is the same as the parameter
124 of the same name to the :func:`ref` function.
125
126
127.. function:: getweakrefcount(object)
128
129 Return the number of weak references and proxies which refer to *object*.
130
131
132.. function:: getweakrefs(object)
133
134 Return a list of all weak reference and proxy objects which refer to *object*.
135
136
137.. class:: WeakKeyDictionary([dict])
138
139 Mapping class that references keys weakly. Entries in the dictionary will be
140 discarded when there is no longer a strong reference to the key. This can be
141 used to associate additional data with an object owned by other parts of an
142 application without adding attributes to those objects. This can be especially
143 useful with objects that override attribute accesses.
144
145 .. note::
146
Christian Heimesfe337bf2008-03-23 21:54:12 +0000147 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000148 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000149 difficult to ensure for a :class:`WeakKeyDictionary` because actions
150 performed by the program during iteration may cause items in the
151 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153:class:`WeakKeyDictionary` objects have the following additional methods. These
154expose the internal references directly. The references are not guaranteed to
155be "live" at the time they are used, so the result of calling the references
156needs to be checked before being used. This can be used to avoid creating
157references that will cause the garbage collector to keep the keys around longer
158than needed.
159
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161.. method:: WeakKeyDictionary.keyrefs()
162
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000163 Return an iterable of the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166.. class:: WeakValueDictionary([dict])
167
168 Mapping class that references values weakly. Entries in the dictionary will be
169 discarded when no strong reference to the value exists any more.
170
171 .. note::
172
173 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
174 dictionary, it must not change size when iterating over it. This can be
175 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
176 by the program during iteration may cause items in the dictionary to vanish "by
177 magic" (as a side effect of garbage collection).
178
179:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000180These method have the same issues as the and :meth:`keyrefs` method of
181:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184.. method:: WeakValueDictionary.valuerefs()
185
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000186 Return an iterable of the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl116aa622007-08-15 14:28:22 +0000188
Georg Brandl3b8cb172007-10-23 06:26:46 +0000189.. class:: WeakSet([elements])
190
191 Set class that keeps weak references to its elements. An element will be
192 discarded when no strong reference to it exists any more.
193
194
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100195.. class:: WeakMethod(method)
196
197 A custom :class:`ref` subclass which simulates a weak reference to a bound
198 method (i.e., a method defined on a class and looked up on an instance).
199 Since a bound method is ephemeral, a standard weak reference cannot keep
200 hold of it. :class:`WeakMethod` has special code to recreate the bound
201 method until either the object or the original function dies::
202
203 >>> class C:
204 ... def method(self):
205 ... print("method called!")
206 ...
207 >>> c = C()
208 >>> r = weakref.ref(c.method)
209 >>> r()
210 >>> r = weakref.WeakMethod(c.method)
211 >>> r()
212 <bound method C.method of <__main__.C object at 0x7fc859830220>>
213 >>> r()()
214 method called!
215 >>> del c
216 >>> gc.collect()
217 0
218 >>> r()
219 >>>
220
221 .. versionadded:: 3.4
222
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224.. data:: ReferenceType
225
226 The type object for weak references objects.
227
228
229.. data:: ProxyType
230
231 The type object for proxies of objects which are not callable.
232
233
234.. data:: CallableProxyType
235
236 The type object for proxies of callable objects.
237
238
239.. data:: ProxyTypes
240
241 Sequence containing all the type objects for proxies. This can make it simpler
242 to test if an object is a proxy without being dependent on naming both proxy
243 types.
244
245
246.. exception:: ReferenceError
247
248 Exception raised when a proxy object is used but the underlying object has been
249 collected. This is the same as the standard :exc:`ReferenceError` exception.
250
251
252.. seealso::
253
254 :pep:`0205` - Weak References
255 The proposal and rationale for this feature, including links to earlier
256 implementations and information about similar features in other languages.
257
258
259.. _weakref-objects:
260
261Weak Reference Objects
262----------------------
263
264Weak reference objects have no attributes or methods, but do allow the referent
Christian Heimesfe337bf2008-03-23 21:54:12 +0000265to be obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267 >>> import weakref
268 >>> class Object:
269 ... pass
270 ...
271 >>> o = Object()
272 >>> r = weakref.ref(o)
273 >>> o2 = r()
274 >>> o is o2
275 True
276
277If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000278:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000281 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000282 None
283
284Testing that a weak reference object is still live should be done using the
285expression ``ref() is not None``. Normally, application code that needs to use
286a reference object should follow this pattern::
287
288 # r is a weak reference object
289 o = r()
290 if o is None:
291 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000292 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000293 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000294 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000295 o.do_something_useful()
296
297Using a separate test for "liveness" creates race conditions in threaded
298applications; another thread can cause a weak reference to become invalidated
299before the weak reference is called; the idiom shown above is safe in threaded
300applications as well as single-threaded applications.
301
302Specialized versions of :class:`ref` objects can be created through subclassing.
303This is used in the implementation of the :class:`WeakValueDictionary` to reduce
304the memory overhead for each entry in the mapping. This may be most useful to
305associate additional information with a reference, but could also be used to
306insert additional processing on calls to retrieve the referent.
307
308This example shows how a subclass of :class:`ref` can be used to store
309additional information about an object and affect the value that's returned when
310the referent is accessed::
311
312 import weakref
313
314 class ExtendedRef(weakref.ref):
315 def __init__(self, ob, callback=None, **annotations):
316 super(ExtendedRef, self).__init__(ob, callback)
317 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000318 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000319 setattr(self, k, v)
320
321 def __call__(self):
322 """Return a pair containing the referent and the number of
323 times the reference has been called.
324 """
325 ob = super(ExtendedRef, self).__call__()
326 if ob is not None:
327 self.__counter += 1
328 ob = (ob, self.__counter)
329 return ob
330
331
332.. _weakref-example:
333
334Example
335-------
336
337This simple example shows how an application can use objects IDs to retrieve
338objects that it has seen before. The IDs of the objects can then be used in
339other data structures without forcing the objects to remain alive, but the
340objects can still be retrieved by ID if they do.
341
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000342.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344::
345
346 import weakref
347
348 _id2obj_dict = weakref.WeakValueDictionary()
349
350 def remember(obj):
351 oid = id(obj)
352 _id2obj_dict[oid] = obj
353 return oid
354
355 def id2obj(oid):
356 return _id2obj_dict[oid]
357