blob: ec50107c75228fb22e20c21e1a158d3180174f7a [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
Mark Dickinson556e94b2013-04-13 15:45:44 +0100114 .. attribute:: __callback__
115
116 This read-only attribute returns the callback currently associated to the
117 weakref. If there is no callback or if the referent of the weakref is
118 no longer alive then this attribute will have value ``None``.
119
Mark Dickinson9b6fdf82013-04-13 16:09:18 +0100120 .. versionadded:: 3.4
121 Added the :attr:`__callback__` attribute.
Mark Dickinson556e94b2013-04-13 15:45:44 +0100122
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124.. function:: proxy(object[, callback])
125
126 Return a proxy to *object* which uses a weak reference. This supports use of
127 the proxy in most contexts instead of requiring the explicit dereferencing used
128 with weak reference objects. The returned object will have a type of either
129 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000130 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000131 avoids a number of problems related to their fundamentally mutable nature, and
132 prevent their use as dictionary keys. *callback* is the same as the parameter
133 of the same name to the :func:`ref` function.
134
135
136.. function:: getweakrefcount(object)
137
138 Return the number of weak references and proxies which refer to *object*.
139
140
141.. function:: getweakrefs(object)
142
143 Return a list of all weak reference and proxy objects which refer to *object*.
144
145
146.. class:: WeakKeyDictionary([dict])
147
148 Mapping class that references keys weakly. Entries in the dictionary will be
149 discarded when there is no longer a strong reference to the key. This can be
150 used to associate additional data with an object owned by other parts of an
151 application without adding attributes to those objects. This can be especially
152 useful with objects that override attribute accesses.
153
154 .. note::
155
Christian Heimesfe337bf2008-03-23 21:54:12 +0000156 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000157 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000158 difficult to ensure for a :class:`WeakKeyDictionary` because actions
159 performed by the program during iteration may cause items in the
160 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162:class:`WeakKeyDictionary` objects have the following additional methods. These
163expose the internal references directly. The references are not guaranteed to
164be "live" at the time they are used, so the result of calling the references
165needs to be checked before being used. This can be used to avoid creating
166references that will cause the garbage collector to keep the keys around longer
167than needed.
168
169
Georg Brandl116aa622007-08-15 14:28:22 +0000170.. method:: WeakKeyDictionary.keyrefs()
171
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000172 Return an iterable of the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175.. class:: WeakValueDictionary([dict])
176
177 Mapping class that references values weakly. Entries in the dictionary will be
178 discarded when no strong reference to the value exists any more.
179
180 .. note::
181
182 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
183 dictionary, it must not change size when iterating over it. This can be
184 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
185 by the program during iteration may cause items in the dictionary to vanish "by
186 magic" (as a side effect of garbage collection).
187
188:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000189These method have the same issues as the and :meth:`keyrefs` method of
190:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193.. method:: WeakValueDictionary.valuerefs()
194
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000195 Return an iterable of the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Georg Brandl3b8cb172007-10-23 06:26:46 +0000198.. class:: WeakSet([elements])
199
200 Set class that keeps weak references to its elements. An element will be
201 discarded when no strong reference to it exists any more.
202
203
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100204.. class:: WeakMethod(method)
205
206 A custom :class:`ref` subclass which simulates a weak reference to a bound
207 method (i.e., a method defined on a class and looked up on an instance).
208 Since a bound method is ephemeral, a standard weak reference cannot keep
209 hold of it. :class:`WeakMethod` has special code to recreate the bound
210 method until either the object or the original function dies::
211
212 >>> class C:
213 ... def method(self):
214 ... print("method called!")
215 ...
216 >>> c = C()
217 >>> r = weakref.ref(c.method)
218 >>> r()
219 >>> r = weakref.WeakMethod(c.method)
220 >>> r()
221 <bound method C.method of <__main__.C object at 0x7fc859830220>>
222 >>> r()()
223 method called!
224 >>> del c
225 >>> gc.collect()
226 0
227 >>> r()
228 >>>
229
230 .. versionadded:: 3.4
231
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233.. data:: ReferenceType
234
235 The type object for weak references objects.
236
237
238.. data:: ProxyType
239
240 The type object for proxies of objects which are not callable.
241
242
243.. data:: CallableProxyType
244
245 The type object for proxies of callable objects.
246
247
248.. data:: ProxyTypes
249
250 Sequence containing all the type objects for proxies. This can make it simpler
251 to test if an object is a proxy without being dependent on naming both proxy
252 types.
253
254
255.. exception:: ReferenceError
256
257 Exception raised when a proxy object is used but the underlying object has been
258 collected. This is the same as the standard :exc:`ReferenceError` exception.
259
260
261.. seealso::
262
263 :pep:`0205` - Weak References
264 The proposal and rationale for this feature, including links to earlier
265 implementations and information about similar features in other languages.
266
267
268.. _weakref-objects:
269
270Weak Reference Objects
271----------------------
272
Mark Dickinson556e94b2013-04-13 15:45:44 +0100273Weak reference objects have no methods and no attributes besides
274:attr:`ref.__callback__`. A weak reference object allows the referent to be
275obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277 >>> import weakref
278 >>> class Object:
279 ... pass
280 ...
281 >>> o = Object()
282 >>> r = weakref.ref(o)
283 >>> o2 = r()
284 >>> o is o2
285 True
286
287If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000288:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000291 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000292 None
293
294Testing that a weak reference object is still live should be done using the
295expression ``ref() is not None``. Normally, application code that needs to use
296a reference object should follow this pattern::
297
298 # r is a weak reference object
299 o = r()
300 if o is None:
301 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000302 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000303 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000304 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000305 o.do_something_useful()
306
307Using a separate test for "liveness" creates race conditions in threaded
308applications; another thread can cause a weak reference to become invalidated
309before the weak reference is called; the idiom shown above is safe in threaded
310applications as well as single-threaded applications.
311
312Specialized versions of :class:`ref` objects can be created through subclassing.
313This is used in the implementation of the :class:`WeakValueDictionary` to reduce
314the memory overhead for each entry in the mapping. This may be most useful to
315associate additional information with a reference, but could also be used to
316insert additional processing on calls to retrieve the referent.
317
318This example shows how a subclass of :class:`ref` can be used to store
319additional information about an object and affect the value that's returned when
320the referent is accessed::
321
322 import weakref
323
324 class ExtendedRef(weakref.ref):
325 def __init__(self, ob, callback=None, **annotations):
326 super(ExtendedRef, self).__init__(ob, callback)
327 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000328 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000329 setattr(self, k, v)
330
331 def __call__(self):
332 """Return a pair containing the referent and the number of
333 times the reference has been called.
334 """
335 ob = super(ExtendedRef, self).__call__()
336 if ob is not None:
337 self.__counter += 1
338 ob = (ob, self.__counter)
339 return ob
340
341
342.. _weakref-example:
343
344Example
345-------
346
347This simple example shows how an application can use objects IDs to retrieve
348objects that it has seen before. The IDs of the objects can then be used in
349other data structures without forcing the objects to remain alive, but the
350objects can still be retrieved by ID if they do.
351
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000352.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354::
355
356 import weakref
357
358 _id2obj_dict = weakref.WeakValueDictionary()
359
360 def remember(obj):
361 oid = id(obj)
362 _id2obj_dict[oid] = obj
363 return oid
364
365 def id2obj(oid):
366 return _id2obj_dict[oid]
367