blob: 12a12200c4e4bf2547e4fe15ec83a14464f88c09 [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),
51and methods (both bound and unbound). Extension types can easily
Fred Drakeebcf6a82001-02-01 05:20:20 +000052be made to support weak references; see section \ref{weakref-extension},
53``Weak References in Extension Types,'' for more information.
54
Fred Drakeebcf6a82001-02-01 05:20:20 +000055
56\begin{funcdesc}{ref}{object\optional{, callback}}
Fred Drake7408da52001-10-26 17:40:22 +000057 Return a weak reference to \var{object}. The original object can be
58 retrieved by calling the reference object if the referent is still
59 alive; if the referent is no longer alive, calling the reference
60 object will cause \code{None} to be returned. If \var{callback} is
Fred Drakeebcf6a82001-02-01 05:20:20 +000061 provided, it will be called when the object is about to be
62 finalized; the weak reference object will be passed as the only
63 parameter to the callback; the referent will no longer be available.
Fred Drakeebcf6a82001-02-01 05:20:20 +000064
65 It is allowable for many weak references to be constructed for the
66 same object. Callbacks registered for each weak reference will be
67 called from the most recently registered callback to the oldest
68 registered callback.
69
70 Exceptions raised by the callback will be noted on the standard
Andrew M. Kuchlinge7d7e6c2001-02-14 02:39:11 +000071 error output, but cannot be propagated; they are handled in exactly
Fred Drakeebcf6a82001-02-01 05:20:20 +000072 the same way as exceptions raised from an object's
73 \method{__del__()} method.
Tim Peters5a5b2432003-11-21 22:20:57 +000074
Martin v. Löwis5e163332001-02-27 18:36:56 +000075 Weak references are hashable if the \var{object} is hashable. They
76 will maintain their hash value even after the \var{object} was
77 deleted. If \function{hash()} is called the first time only after
78 the \var{object} was deleted, the call will raise
79 \exception{TypeError}.
Tim Peters5a5b2432003-11-21 22:20:57 +000080
Fred Drake3a2c4622001-10-26 03:00:39 +000081 Weak references support tests for equality, but not ordering. If
Fred Drake7408da52001-10-26 17:40:22 +000082 the referents are still alive, two references have the same
Fred Drakeb03d0cc2001-11-26 21:39:40 +000083 equality relationship as their referents (regardless of the
Fred Drake7408da52001-10-26 17:40:22 +000084 \var{callback}). If either referent has been deleted, the
85 references are equal only if the reference objects are the same
86 object.
Fred Drakeebcf6a82001-02-01 05:20:20 +000087\end{funcdesc}
88
Fred Drakeebcf6a82001-02-01 05:20:20 +000089\begin{funcdesc}{proxy}{object\optional{, callback}}
90 Return a proxy to \var{object} which uses a weak reference. This
91 supports use of the proxy in most contexts instead of requiring the
92 explicit dereferencing used with weak reference objects. The
93 returned object will have a type of either \code{ProxyType} or
94 \code{CallableProxyType}, depending on whether \var{object} is
95 callable. Proxy objects are not hashable regardless of the
96 referent; this avoids a number of problems related to their
97 fundamentally mutable nature, and prevent their use as dictionary
Fred Drakee7ec1ef2001-05-10 17:22:17 +000098 keys. \var{callback} is the same as the parameter of the same name
Fred Drakeebcf6a82001-02-01 05:20:20 +000099 to the \function{ref()} function.
100\end{funcdesc}
101
102\begin{funcdesc}{getweakrefcount}{object}
103 Return the number of weak references and proxies which refer to
104 \var{object}.
105\end{funcdesc}
106
107\begin{funcdesc}{getweakrefs}{object}
108 Return a list of all weak reference and proxy objects which refer to
109 \var{object}.
110\end{funcdesc}
111
Martin v. Löwis5e163332001-02-27 18:36:56 +0000112\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000113 Mapping class that references keys weakly. Entries in the
114 dictionary will be discarded when there is no longer a strong
115 reference to the key. This can be used to associate additional data
116 with an object owned by other parts of an application without adding
117 attributes to those objects. This can be especially useful with
118 objects that override attribute accesses.
Tim Peters5a5b2432003-11-21 22:20:57 +0000119
120 \note{Caution: Because a \class{WeakKeyDictionary} is built on top
121 of a Python dictionary, it must not change size when iterating
122 over it. This can be difficult to ensure for a
123 \class{WeakKeyDictionary} because actions performed by the
124 program during iteration may cause items in the dictionary
125 to vanish "by magic" (as a side effect of garbage collection).}
Martin v. Löwis5e163332001-02-27 18:36:56 +0000126\end{classdesc}
127
128\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000129 Mapping class that references values weakly. Entries in the
130 dictionary will be discarded when no strong reference to the value
Fred Drake7408da52001-10-26 17:40:22 +0000131 exists any more.
Tim Peters5a5b2432003-11-21 22:20:57 +0000132
133 \note{Caution: Because a \class{WeakValueDictionary} is built on top
134 of a Python dictionary, it must not change size when iterating
135 over it. This can be difficult to ensure for a
136 \class{WeakValueDictionary} because actions performed by the
137 program during iteration may cause items in the dictionary
138 to vanish "by magic" (as a side effect of garbage collection).}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000139\end{classdesc}
140
141\begin{datadesc}{ReferenceType}
142 The type object for weak references objects.
143\end{datadesc}
144
145\begin{datadesc}{ProxyType}
146 The type object for proxies of objects which are not callable.
147\end{datadesc}
148
149\begin{datadesc}{CallableProxyType}
150 The type object for proxies of callable objects.
151\end{datadesc}
152
153\begin{datadesc}{ProxyTypes}
154 Sequence containing all the type objects for proxies. This can make
155 it simpler to test if an object is a proxy without being dependent
156 on naming both proxy types.
157\end{datadesc}
158
Fred Drakeac154a12001-04-10 19:57:58 +0000159\begin{excdesc}{ReferenceError}
160 Exception raised when a proxy object is used but the underlying
Fred Drake8c2c3d32001-10-06 06:10:54 +0000161 object has been collected. This is the same as the standard
162 \exception{ReferenceError} exception.
Fred Drakeac154a12001-04-10 19:57:58 +0000163\end{excdesc}
164
Fred Drakeebcf6a82001-02-01 05:20:20 +0000165
166\begin{seealso}
167 \seepep{0205}{Weak References}{The proposal and rationale for this
168 feature, including links to earlier implementations
169 and information about similar features in other
170 languages.}
171\end{seealso}
172
173
174\subsection{Weak Reference Objects
175 \label{weakref-objects}}
176
177Weak reference objects have no attributes or methods, but do allow the
178referent to be obtained, if it still exists, by calling it:
179
180\begin{verbatim}
181>>> import weakref
182>>> class Object:
183... pass
184...
185>>> o = Object()
186>>> r = weakref.ref(o)
187>>> o2 = r()
188>>> o is o2
Martin v. Löwisccabed32003-11-27 19:48:03 +0000189True
Fred Drakeebcf6a82001-02-01 05:20:20 +0000190\end{verbatim}
191
192If the referent no longer exists, calling the reference object returns
193\code{None}:
194
195\begin{verbatim}
196>>> del o, o2
197>>> print r()
198None
199\end{verbatim}
200
201Testing that a weak reference object is still live should be done
Fred Drake5d548792001-08-03 03:50:28 +0000202using the expression \code{\var{ref}() is not None}. Normally,
Fred Drakeebcf6a82001-02-01 05:20:20 +0000203application code that needs to use a reference object should follow
204this pattern:
205
206\begin{verbatim}
Fred Drake7408da52001-10-26 17:40:22 +0000207# r is a weak reference object
208o = r()
Fred Drakeebcf6a82001-02-01 05:20:20 +0000209if o is None:
210 # referent has been garbage collected
211 print "Object has been allocated; can't frobnicate."
212else:
213 print "Object is still live!"
214 o.do_something_useful()
215\end{verbatim}
216
217Using a separate test for ``liveness'' creates race conditions in
218threaded applications; another thread can cause a weak reference to
Fred Drake7408da52001-10-26 17:40:22 +0000219become invalidated before the weak reference is called; the
Fred Drakeebcf6a82001-02-01 05:20:20 +0000220idiom shown above is safe in threaded applications as well as
221single-threaded applications.
222
223
Fred Drakecb839882001-03-28 21:15:41 +0000224\subsection{Example \label{weakref-example}}
225
226This simple example shows how an application can use objects IDs to
227retrieve objects that it has seen before. The IDs of the objects can
228then be used in other data structures without forcing the objects to
229remain alive, but the objects can still be retrieved by ID if they
230do.
231
Fred Drake42713102003-12-30 16:15:35 +0000232% Example contributed by Tim Peters.
Fred Drakecb839882001-03-28 21:15:41 +0000233\begin{verbatim}
234import weakref
235
Fred Drakeac154a12001-04-10 19:57:58 +0000236_id2obj_dict = weakref.WeakValueDictionary()
Fred Drakecb839882001-03-28 21:15:41 +0000237
238def remember(obj):
Fred Drake7408da52001-10-26 17:40:22 +0000239 oid = id(obj)
240 _id2obj_dict[oid] = obj
241 return oid
Fred Drakecb839882001-03-28 21:15:41 +0000242
Fred Drake7408da52001-10-26 17:40:22 +0000243def id2obj(oid):
244 return _id2obj_dict[oid]
Fred Drakecb839882001-03-28 21:15:41 +0000245\end{verbatim}
246
247
Fred Drakeebcf6a82001-02-01 05:20:20 +0000248\subsection{Weak References in Extension Types
249 \label{weakref-extension}}
250
251One of the goals of the implementation is to allow any type to
252participate in the weak reference mechanism without incurring the
253overhead on those objects which do not benefit by weak referencing
254(such as numbers).
255
256For an object to be weakly referencable, the extension must include a
Fred Drake7408da52001-10-26 17:40:22 +0000257\ctype{PyObject*} field in the instance structure for the use of the
Fred Drake5e0dfac2001-03-23 04:36:02 +0000258weak reference mechanism; it must be initialized to \NULL{} by the
259object's constructor. It must also set the \member{tp_weaklistoffset}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000260field of the corresponding type object to the offset of the field.
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000261Also, it needs to add \constant{Py_TPFLAGS_HAVE_WEAKREFS} to the
262tp_flags slot. For example, the instance type is defined with the
263following structure:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000264
265\begin{verbatim}
266typedef struct {
267 PyObject_HEAD
268 PyClassObject *in_class; /* The class object */
Martin v. Löwis5e163332001-02-27 18:36:56 +0000269 PyObject *in_dict; /* A dictionary */
270 PyObject *in_weakreflist; /* List of weak references */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000271} PyInstanceObject;
272\end{verbatim}
273
274The statically-declared type object for instances is defined this way:
275
276\begin{verbatim}
277PyTypeObject PyInstance_Type = {
278 PyObject_HEAD_INIT(&PyType_Type)
279 0,
Guido van Rossum14648392001-12-08 18:02:58 +0000280 "module.instance",
Fred Drakeebcf6a82001-02-01 05:20:20 +0000281
Fred Drakef66cb5d2001-06-22 17:20:29 +0000282 /* Lots of stuff omitted for brevity... */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000283
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000284 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS /* tp_flags */
285 0, /* tp_doc */
286 0, /* tp_traverse */
287 0, /* tp_clear */
288 0, /* tp_richcompare */
289 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000290};
291\end{verbatim}
292
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000293The type constructor is responsible for initializing the weak reference
294list to \NULL:
295
296\begin{verbatim}
Tim Peters5a5b2432003-11-21 22:20:57 +0000297static PyObject *
298instance_new() {
299 /* Other initialization stuff omitted for brevity */
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000300
Tim Peters5a5b2432003-11-21 22:20:57 +0000301 self->in_weakreflist = NULL;
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000302
Tim Peters5a5b2432003-11-21 22:20:57 +0000303 return (PyObject *) self;
304}
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000305\end{verbatim}
306
Fred Drakeebcf6a82001-02-01 05:20:20 +0000307The only further addition is that the destructor needs to call the
Fred Drakef66cb5d2001-06-22 17:20:29 +0000308weak reference manager to clear any weak references. This should be
Fred Drake7408da52001-10-26 17:40:22 +0000309done before any other parts of the destruction have occurred, but is
310only required if the weak reference list is non-\NULL:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000311
312\begin{verbatim}
313static void
314instance_dealloc(PyInstanceObject *inst)
315{
Fred Drake7408da52001-10-26 17:40:22 +0000316 /* Allocate temporaries if needed, but do not begin
Fred Drakef66cb5d2001-06-22 17:20:29 +0000317 destruction just yet.
Fred Drakeebcf6a82001-02-01 05:20:20 +0000318 */
319
Fred Drake7408da52001-10-26 17:40:22 +0000320 if (inst->in_weakreflist != NULL)
321 PyObject_ClearWeakRefs((PyObject *) inst);
Fred Drakeebcf6a82001-02-01 05:20:20 +0000322
Fred Drakede3d0602001-10-26 11:27:54 +0000323 /* Proceed with object destruction normally. */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000324}
325\end{verbatim}