blob: c76684bf027bb13640ea157c055a2119bef5c449 [file] [log] [blame]
Fred Drakeebcf6a82001-02-01 05:20:20 +00001\section{\module{weakref} ---
2 Weak references}
3
4\declaremodule{extension}{weakref}
Fred Drakeeedf9852001-04-11 19:17:11 +00005\modulesynopsis{Support for weak references and weak dictionaries.}
Fred Drakeebcf6a82001-02-01 05:20:20 +00006\moduleauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
Martin v. Löwis5e163332001-02-27 18:36:56 +00007\moduleauthor{Neil Schemenauer}{nas@arctrix.com}
Fred Drake0c209042001-06-29 16:25:07 +00008\moduleauthor{Martin von L\"owis}{martin@loewis.home.cs.tu-berlin.de}
Fred Drakeebcf6a82001-02-01 05:20:20 +00009\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
10
11\versionadded{2.1}
12
13
14The \module{weakref} module allows the Python programmer to create
15\dfn{weak references} to objects.
16
Tim Peters5a5b2432003-11-21 22:20:57 +000017In the following, the term \dfn{referent} means the
Fred Drake7408da52001-10-26 17:40:22 +000018object which is referred to by a weak reference.
19
Tim Peters5a5b2432003-11-21 22:20:57 +000020A weak reference to an object is not enough to keep the object alive:
21when the only remaining references to a referent are weak references,
22garbage collection is free to destroy the referent and reuse its memory
23for something else. A primary use for weak references is to implement
24caches or mappings holding large objects, where it's desired that a
25large object not be kept alive solely because it appears in a cache or
26mapping. For example, if you have a number of large binary image objects,
27you may wish to associate a name with each. If you used a Python
28dictionary to map names to images, or images to names, the image objects
29would remain alive just because they appeared as values or keys in the
30dictionaries. The \class{WeakKeyDictionary} and
31\class{WeakValueDictionary} classes supplied by the \module{weakref}
32module are an alternative, using weak references to construct mappings
33that don't keep objects alive solely because they appear in the mapping
34objects. If, for example, an image object is a value in a
35\class{WeakValueDictionary}, then when the last remaining
36references to that image object are the weak references held by weak
37mappings, garbage collection can reclaim the object, and its corresponding
38entries in weak mappings are simply deleted.
39
40\class{WeakKeyDictionary} and \class{WeakValueDictionary} use weak
41references in their implementation, setting up callback functions on
42the weak references that notify the weak dictionaries when a key or value
43has been reclaimed by garbage collection. Most programs should find that
44using one of these weak dictionary types is all they need -- it's
45not usually necessary to create your own weak references directly. The
46low-level machinery used by the weak dictionary implementations is exposed
47by the \module{weakref} module for the benefit of advanced uses.
Fred Drakeebcf6a82001-02-01 05:20:20 +000048
Raymond Hettingerf8020e02003-07-02 15:10:38 +000049Not all objects can be weakly referenced; those objects which can
Fred Drake5e0dfac2001-03-23 04:36:02 +000050include class instances, functions written in Python (but not in C),
Raymond Hettinger027bb632004-05-31 03:09:25 +000051methods (both bound and unbound), sets, frozensets, file objects,
Raymond Hettinger34809172004-06-12 06:56:44 +000052generators, type objects, DBcursor objects from the \module{bsddb} module,
Raymond Hettinger027bb632004-05-31 03:09:25 +000053sockets, arrays, deques, and regular expression pattern objects.
54\versionchanged[Added support for files, sockets, arrays, and patterns]{2.4}
55
56Several builtin types such as \class{list} and \class{dict} do not
57directly support weak references but can add support through subclassing:
58
59\begin{verbatim}
60class Dict(dict):
61 pass
62
63obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
64\end{verbatim}
65
66Extension types can easily be made to support weak references; see section
67\ref{weakref-extension}, ``Weak References in Extension Types,'' for more
68information.
Fred Drakeebcf6a82001-02-01 05:20:20 +000069
Fred Drakeebcf6a82001-02-01 05:20:20 +000070
Fred Drake0a4dd392004-07-02 18:57:45 +000071\begin{classdesc}{ref}{object\optional{, callback}}
Fred Drake7408da52001-10-26 17:40:22 +000072 Return a weak reference to \var{object}. The original object can be
73 retrieved by calling the reference object if the referent is still
74 alive; if the referent is no longer alive, calling the reference
Fred Drake21ae4f92004-02-03 20:55:15 +000075 object will cause \constant{None} to be returned. If \var{callback} is
Fred Drake4458ece2004-02-03 19:44:26 +000076 provided and not \constant{None},
77 it will be called when the object is about to be
Fred Drakeebcf6a82001-02-01 05:20:20 +000078 finalized; the weak reference object will be passed as the only
79 parameter to the callback; the referent will no longer be available.
Fred Drakeebcf6a82001-02-01 05:20:20 +000080
81 It is allowable for many weak references to be constructed for the
82 same object. Callbacks registered for each weak reference will be
83 called from the most recently registered callback to the oldest
84 registered callback.
85
86 Exceptions raised by the callback will be noted on the standard
Andrew M. Kuchlinge7d7e6c2001-02-14 02:39:11 +000087 error output, but cannot be propagated; they are handled in exactly
Fred Drakeebcf6a82001-02-01 05:20:20 +000088 the same way as exceptions raised from an object's
89 \method{__del__()} method.
Tim Peters5a5b2432003-11-21 22:20:57 +000090
Martin v. Löwis5e163332001-02-27 18:36:56 +000091 Weak references are hashable if the \var{object} is hashable. They
92 will maintain their hash value even after the \var{object} was
93 deleted. If \function{hash()} is called the first time only after
94 the \var{object} was deleted, the call will raise
95 \exception{TypeError}.
Tim Peters5a5b2432003-11-21 22:20:57 +000096
Fred Drake3a2c4622001-10-26 03:00:39 +000097 Weak references support tests for equality, but not ordering. If
Fred Drake7408da52001-10-26 17:40:22 +000098 the referents are still alive, two references have the same
Fred Drakeb03d0cc2001-11-26 21:39:40 +000099 equality relationship as their referents (regardless of the
Fred Drake7408da52001-10-26 17:40:22 +0000100 \var{callback}). If either referent has been deleted, the
101 references are equal only if the reference objects are the same
102 object.
Fred Drake0a4dd392004-07-02 18:57:45 +0000103
104 \versionchanged[This is now a subclassable type rather than a
105 factory function; it derives from \class{object}]
106 {2.4}
107\end{classdesc}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000108
Fred Drakeebcf6a82001-02-01 05:20:20 +0000109\begin{funcdesc}{proxy}{object\optional{, callback}}
110 Return a proxy to \var{object} which uses a weak reference. This
111 supports use of the proxy in most contexts instead of requiring the
112 explicit dereferencing used with weak reference objects. The
113 returned object will have a type of either \code{ProxyType} or
114 \code{CallableProxyType}, depending on whether \var{object} is
115 callable. Proxy objects are not hashable regardless of the
116 referent; this avoids a number of problems related to their
117 fundamentally mutable nature, and prevent their use as dictionary
Fred Drakee7ec1ef2001-05-10 17:22:17 +0000118 keys. \var{callback} is the same as the parameter of the same name
Fred Drakeebcf6a82001-02-01 05:20:20 +0000119 to the \function{ref()} function.
120\end{funcdesc}
121
122\begin{funcdesc}{getweakrefcount}{object}
123 Return the number of weak references and proxies which refer to
124 \var{object}.
125\end{funcdesc}
126
127\begin{funcdesc}{getweakrefs}{object}
128 Return a list of all weak reference and proxy objects which refer to
129 \var{object}.
130\end{funcdesc}
131
Martin v. Löwis5e163332001-02-27 18:36:56 +0000132\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000133 Mapping class that references keys weakly. Entries in the
134 dictionary will be discarded when there is no longer a strong
135 reference to the key. This can be used to associate additional data
136 with an object owned by other parts of an application without adding
137 attributes to those objects. This can be especially useful with
138 objects that override attribute accesses.
Tim Peters5a5b2432003-11-21 22:20:57 +0000139
140 \note{Caution: Because a \class{WeakKeyDictionary} is built on top
141 of a Python dictionary, it must not change size when iterating
142 over it. This can be difficult to ensure for a
143 \class{WeakKeyDictionary} because actions performed by the
144 program during iteration may cause items in the dictionary
145 to vanish "by magic" (as a side effect of garbage collection).}
Martin v. Löwis5e163332001-02-27 18:36:56 +0000146\end{classdesc}
147
148\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000149 Mapping class that references values weakly. Entries in the
150 dictionary will be discarded when no strong reference to the value
Fred Drake7408da52001-10-26 17:40:22 +0000151 exists any more.
Tim Peters5a5b2432003-11-21 22:20:57 +0000152
153 \note{Caution: Because a \class{WeakValueDictionary} is built on top
154 of a Python dictionary, it must not change size when iterating
155 over it. This can be difficult to ensure for a
156 \class{WeakValueDictionary} because actions performed by the
157 program during iteration may cause items in the dictionary
158 to vanish "by magic" (as a side effect of garbage collection).}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000159\end{classdesc}
160
161\begin{datadesc}{ReferenceType}
162 The type object for weak references objects.
163\end{datadesc}
164
165\begin{datadesc}{ProxyType}
166 The type object for proxies of objects which are not callable.
167\end{datadesc}
168
169\begin{datadesc}{CallableProxyType}
170 The type object for proxies of callable objects.
171\end{datadesc}
172
173\begin{datadesc}{ProxyTypes}
174 Sequence containing all the type objects for proxies. This can make
175 it simpler to test if an object is a proxy without being dependent
176 on naming both proxy types.
177\end{datadesc}
178
Fred Drakeac154a12001-04-10 19:57:58 +0000179\begin{excdesc}{ReferenceError}
180 Exception raised when a proxy object is used but the underlying
Fred Drake8c2c3d32001-10-06 06:10:54 +0000181 object has been collected. This is the same as the standard
182 \exception{ReferenceError} exception.
Fred Drakeac154a12001-04-10 19:57:58 +0000183\end{excdesc}
184
Fred Drakeebcf6a82001-02-01 05:20:20 +0000185
186\begin{seealso}
187 \seepep{0205}{Weak References}{The proposal and rationale for this
188 feature, including links to earlier implementations
189 and information about similar features in other
190 languages.}
191\end{seealso}
192
193
194\subsection{Weak Reference Objects
195 \label{weakref-objects}}
196
197Weak reference objects have no attributes or methods, but do allow the
198referent to be obtained, if it still exists, by calling it:
199
200\begin{verbatim}
201>>> import weakref
202>>> class Object:
203... pass
204...
205>>> o = Object()
206>>> r = weakref.ref(o)
207>>> o2 = r()
208>>> o is o2
Martin v. Löwisccabed32003-11-27 19:48:03 +0000209True
Fred Drakeebcf6a82001-02-01 05:20:20 +0000210\end{verbatim}
211
212If the referent no longer exists, calling the reference object returns
Fred Drake21ae4f92004-02-03 20:55:15 +0000213\constant{None}:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000214
215\begin{verbatim}
216>>> del o, o2
217>>> print r()
218None
219\end{verbatim}
220
221Testing that a weak reference object is still live should be done
Fred Drake5d548792001-08-03 03:50:28 +0000222using the expression \code{\var{ref}() is not None}. Normally,
Fred Drakeebcf6a82001-02-01 05:20:20 +0000223application code that needs to use a reference object should follow
224this pattern:
225
226\begin{verbatim}
Fred Drake7408da52001-10-26 17:40:22 +0000227# r is a weak reference object
228o = r()
Fred Drakeebcf6a82001-02-01 05:20:20 +0000229if o is None:
230 # referent has been garbage collected
231 print "Object has been allocated; can't frobnicate."
232else:
233 print "Object is still live!"
234 o.do_something_useful()
235\end{verbatim}
236
237Using a separate test for ``liveness'' creates race conditions in
238threaded applications; another thread can cause a weak reference to
Fred Drake7408da52001-10-26 17:40:22 +0000239become invalidated before the weak reference is called; the
Fred Drakeebcf6a82001-02-01 05:20:20 +0000240idiom shown above is safe in threaded applications as well as
241single-threaded applications.
242
Fred Drake0a4dd392004-07-02 18:57:45 +0000243Specialized versions of \class{ref} objects can be created through
244subclassing. This is used in the implementation of the
245\class{WeakValueDictionary} to reduce the memory overhead for each
246entry in the mapping. This may be most useful to associate additional
247information with a reference, but could also be used to insert
248additional processing on calls to retrieve the referent.
249
250This example shows how a subclass of \class{ref} can be used to store
251additional information about an object and affect the value that's
252returned when the referent is accessed:
253
254\begin{verbatim}
255import weakref
256
257class ExtendedRef(weakref.ref):
258 def __new__(cls, ob, callback=None, **annotations):
259 weakref.ref.__new__(cls, ob, callback)
260 self.__counter = 0
261
262 def __init__(self, ob, callback=None, **annotations):
263 super(ExtendedRef, self).__init__(ob, callback)
264 for k, v in annotations:
265 setattr(self, k, v)
266
267 def __call__(self):
268 """Return a pair containing the referent and the number of
269 times the reference has been called.
270 """
271 ob = super(ExtendedRef, self)()
272 if ob is not None:
273 self.__counter += 1
274 ob = (ob, self.__counter)
275 return ob
276\end{verbatim}
277
Fred Drakeebcf6a82001-02-01 05:20:20 +0000278
Fred Drakecb839882001-03-28 21:15:41 +0000279\subsection{Example \label{weakref-example}}
280
281This simple example shows how an application can use objects IDs to
282retrieve objects that it has seen before. The IDs of the objects can
283then be used in other data structures without forcing the objects to
284remain alive, but the objects can still be retrieved by ID if they
285do.
286
Fred Drake42713102003-12-30 16:15:35 +0000287% Example contributed by Tim Peters.
Fred Drakecb839882001-03-28 21:15:41 +0000288\begin{verbatim}
289import weakref
290
Fred Drakeac154a12001-04-10 19:57:58 +0000291_id2obj_dict = weakref.WeakValueDictionary()
Fred Drakecb839882001-03-28 21:15:41 +0000292
293def remember(obj):
Fred Drake7408da52001-10-26 17:40:22 +0000294 oid = id(obj)
295 _id2obj_dict[oid] = obj
296 return oid
Fred Drakecb839882001-03-28 21:15:41 +0000297
Fred Drake7408da52001-10-26 17:40:22 +0000298def id2obj(oid):
299 return _id2obj_dict[oid]
Fred Drakecb839882001-03-28 21:15:41 +0000300\end{verbatim}
301
302
Fred Drakeebcf6a82001-02-01 05:20:20 +0000303\subsection{Weak References in Extension Types
304 \label{weakref-extension}}
305
306One of the goals of the implementation is to allow any type to
307participate in the weak reference mechanism without incurring the
308overhead on those objects which do not benefit by weak referencing
309(such as numbers).
310
311For an object to be weakly referencable, the extension must include a
Fred Drake7408da52001-10-26 17:40:22 +0000312\ctype{PyObject*} field in the instance structure for the use of the
Fred Drake5e0dfac2001-03-23 04:36:02 +0000313weak reference mechanism; it must be initialized to \NULL{} by the
314object's constructor. It must also set the \member{tp_weaklistoffset}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000315field of the corresponding type object to the offset of the field.
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000316Also, it needs to add \constant{Py_TPFLAGS_HAVE_WEAKREFS} to the
317tp_flags slot. For example, the instance type is defined with the
318following structure:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000319
320\begin{verbatim}
321typedef struct {
322 PyObject_HEAD
323 PyClassObject *in_class; /* The class object */
Martin v. Löwis5e163332001-02-27 18:36:56 +0000324 PyObject *in_dict; /* A dictionary */
325 PyObject *in_weakreflist; /* List of weak references */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000326} PyInstanceObject;
327\end{verbatim}
328
329The statically-declared type object for instances is defined this way:
330
331\begin{verbatim}
332PyTypeObject PyInstance_Type = {
333 PyObject_HEAD_INIT(&PyType_Type)
334 0,
Guido van Rossum14648392001-12-08 18:02:58 +0000335 "module.instance",
Fred Drakeebcf6a82001-02-01 05:20:20 +0000336
Fred Drakef66cb5d2001-06-22 17:20:29 +0000337 /* Lots of stuff omitted for brevity... */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000338
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000339 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS /* tp_flags */
340 0, /* tp_doc */
341 0, /* tp_traverse */
342 0, /* tp_clear */
343 0, /* tp_richcompare */
344 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000345};
346\end{verbatim}
347
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000348The type constructor is responsible for initializing the weak reference
349list to \NULL:
350
351\begin{verbatim}
Tim Peters5a5b2432003-11-21 22:20:57 +0000352static PyObject *
353instance_new() {
354 /* Other initialization stuff omitted for brevity */
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000355
Tim Peters5a5b2432003-11-21 22:20:57 +0000356 self->in_weakreflist = NULL;
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000357
Tim Peters5a5b2432003-11-21 22:20:57 +0000358 return (PyObject *) self;
359}
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000360\end{verbatim}
361
Fred Drakeebcf6a82001-02-01 05:20:20 +0000362The only further addition is that the destructor needs to call the
Fred Drakef66cb5d2001-06-22 17:20:29 +0000363weak reference manager to clear any weak references. This should be
Fred Drake7408da52001-10-26 17:40:22 +0000364done before any other parts of the destruction have occurred, but is
365only required if the weak reference list is non-\NULL:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000366
367\begin{verbatim}
368static void
369instance_dealloc(PyInstanceObject *inst)
370{
Fred Drake7408da52001-10-26 17:40:22 +0000371 /* Allocate temporaries if needed, but do not begin
Fred Drakef66cb5d2001-06-22 17:20:29 +0000372 destruction just yet.
Fred Drakeebcf6a82001-02-01 05:20:20 +0000373 */
374
Fred Drake7408da52001-10-26 17:40:22 +0000375 if (inst->in_weakreflist != NULL)
376 PyObject_ClearWeakRefs((PyObject *) inst);
Fred Drakeebcf6a82001-02-01 05:20:20 +0000377
Fred Drakede3d0602001-10-26 11:27:54 +0000378 /* Proceed with object destruction normally. */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000379}
380\end{verbatim}