blob: ca6c08a3c064411b7c04602cc8c06f86da06492c [file] [log] [blame]
Fred Drakeebcf6a82001-02-01 05:20:20 +00001\section{\module{weakref} ---
2 Weak references}
3
4\declaremodule{extension}{weakref}
5\moduleauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
Martin v. Löwis5e163332001-02-27 18:36:56 +00006\moduleauthor{Neil Schemenauer}{nas@arctrix.com}
7\moduleauthor{Martin von L\o"wis}{martin@loewis.home.cs.tu-berlin.de}
Fred Drakeebcf6a82001-02-01 05:20:20 +00008\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
9
10\versionadded{2.1}
11
12
13The \module{weakref} module allows the Python programmer to create
14\dfn{weak references} to objects.
15
16XXX --- need to say more here!
17
18Not all objects can be weakly referenced; those objects which do
Fred Drake5e0dfac2001-03-23 04:36:02 +000019include class instances, functions written in Python (but not in C),
20and methods (both bound and unbound). Extension types can easily
Fred Drakeebcf6a82001-02-01 05:20:20 +000021be made to support weak references; see section \ref{weakref-extension},
22``Weak References in Extension Types,'' for more information.
23
Fred Drakeebcf6a82001-02-01 05:20:20 +000024
25\begin{funcdesc}{ref}{object\optional{, callback}}
26 Return a weak reference to \var{object}. If \var{callback} is
27 provided, it will be called when the object is about to be
28 finalized; the weak reference object will be passed as the only
29 parameter to the callback; the referent will no longer be available.
30 The original object can be retrieved by calling the reference
31 object, if the referent is still alive.
32
33 It is allowable for many weak references to be constructed for the
34 same object. Callbacks registered for each weak reference will be
35 called from the most recently registered callback to the oldest
36 registered callback.
37
38 Exceptions raised by the callback will be noted on the standard
Andrew M. Kuchlinge7d7e6c2001-02-14 02:39:11 +000039 error output, but cannot be propagated; they are handled in exactly
Fred Drakeebcf6a82001-02-01 05:20:20 +000040 the same way as exceptions raised from an object's
41 \method{__del__()} method.
Martin v. Löwis5e163332001-02-27 18:36:56 +000042
43 Weak references are hashable if the \var{object} is hashable. They
44 will maintain their hash value even after the \var{object} was
45 deleted. If \function{hash()} is called the first time only after
46 the \var{object} was deleted, the call will raise
47 \exception{TypeError}.
48
49 Weak references support test for equality, but not ordering. If the
50 \var{object} is still alive, to references are equal if the objects
51 are equal (regardless of the \var{callback}). If the \var{object}
52 has been deleted, they are equal iff they are identical.
Fred Drakeebcf6a82001-02-01 05:20:20 +000053\end{funcdesc}
54
Martin v. Löwis5e163332001-02-27 18:36:56 +000055\begin{funcdesc}{mapping}{\optional{dict\optional{, weakkeys=0}}}
Fred Drakeebcf6a82001-02-01 05:20:20 +000056 Return a weak dictionary. If \var{dict} is given and not
57 \code{None}, the new dictionary will contain the items contained in
58 \var{dict}. The values from \var{dict} must be weakly referencable;
59 if any values which would be inserted into the new mapping are not
60 weakly referencable, \exception{TypeError} will be raised and the
61 new mapping will be empty.
Martin v. Löwis5e163332001-02-27 18:36:56 +000062
63 If the \var{weakkeys} argument is not given or zero, the values in
64 the dictionary are weak. That means the entries in the dictionary
65 will be discarded when no strong reference to the value exists
66 anymore.
67
68 If the \var{weakkeys} argument is nonzero, the keys in the
69 dictionary are weak, i.e. the entry in the dictionary is discarded
70 when the last strong reference to the key is discarded.
Fred Drakeebcf6a82001-02-01 05:20:20 +000071\end{funcdesc}
72
73\begin{funcdesc}{proxy}{object\optional{, callback}}
74 Return a proxy to \var{object} which uses a weak reference. This
75 supports use of the proxy in most contexts instead of requiring the
76 explicit dereferencing used with weak reference objects. The
77 returned object will have a type of either \code{ProxyType} or
78 \code{CallableProxyType}, depending on whether \var{object} is
79 callable. Proxy objects are not hashable regardless of the
80 referent; this avoids a number of problems related to their
81 fundamentally mutable nature, and prevent their use as dictionary
82 keys. \var{callable} is the same as the parameter of the same name
83 to the \function{ref()} function.
84\end{funcdesc}
85
86\begin{funcdesc}{getweakrefcount}{object}
87 Return the number of weak references and proxies which refer to
88 \var{object}.
89\end{funcdesc}
90
91\begin{funcdesc}{getweakrefs}{object}
92 Return a list of all weak reference and proxy objects which refer to
93 \var{object}.
94\end{funcdesc}
95
Martin v. Löwis5e163332001-02-27 18:36:56 +000096\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
97 The class of the mapping objects returned by \function{mapping()}
98 when \var{weakkeys} is true. This can be used for subclassing the
99 implementation if needed.
100\end{classdesc}
101
102\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
103 The class of the mapping objects returned by \function{mapping()}
104 when \var{weakkeys} if false. This can be used for subclassing the
105 implementation if needed.
Fred Drakeebcf6a82001-02-01 05:20:20 +0000106\end{classdesc}
107
108\begin{datadesc}{ReferenceType}
109 The type object for weak references objects.
110\end{datadesc}
111
112\begin{datadesc}{ProxyType}
113 The type object for proxies of objects which are not callable.
114\end{datadesc}
115
116\begin{datadesc}{CallableProxyType}
117 The type object for proxies of callable objects.
118\end{datadesc}
119
120\begin{datadesc}{ProxyTypes}
121 Sequence containing all the type objects for proxies. This can make
122 it simpler to test if an object is a proxy without being dependent
123 on naming both proxy types.
124\end{datadesc}
125
126
127\begin{seealso}
128 \seepep{0205}{Weak References}{The proposal and rationale for this
129 feature, including links to earlier implementations
130 and information about similar features in other
131 languages.}
132\end{seealso}
133
134
135\subsection{Weak Reference Objects
136 \label{weakref-objects}}
137
138Weak reference objects have no attributes or methods, but do allow the
139referent to be obtained, if it still exists, by calling it:
140
141\begin{verbatim}
142>>> import weakref
143>>> class Object:
144... pass
145...
146>>> o = Object()
147>>> r = weakref.ref(o)
148>>> o2 = r()
149>>> o is o2
1501
151\end{verbatim}
152
153If the referent no longer exists, calling the reference object returns
154\code{None}:
155
156\begin{verbatim}
157>>> del o, o2
158>>> print r()
159None
160\end{verbatim}
161
162Testing that a weak reference object is still live should be done
163using the expression \code{\var{ref}.get() is not None}. Normally,
164application code that needs to use a reference object should follow
165this pattern:
166
167\begin{verbatim}
168o = ref.get()
169if o is None:
170 # referent has been garbage collected
171 print "Object has been allocated; can't frobnicate."
172else:
173 print "Object is still live!"
174 o.do_something_useful()
175\end{verbatim}
176
177Using a separate test for ``liveness'' creates race conditions in
178threaded applications; another thread can cause a weak reference to
179become invalidated before the \method{get()} method is called; the
180idiom shown above is safe in threaded applications as well as
181single-threaded applications.
182
183
Fred Drakecb839882001-03-28 21:15:41 +0000184\subsection{Example \label{weakref-example}}
185
186This simple example shows how an application can use objects IDs to
187retrieve objects that it has seen before. The IDs of the objects can
188then be used in other data structures without forcing the objects to
189remain alive, but the objects can still be retrieved by ID if they
190do.
191
192% Example contributed by Tim Peters <tim_one@msn.com>.
193\begin{verbatim}
194import weakref
195
196_id2obj_dict = weakref.mapping()
197
198def remember(obj):
199 _id2obj_dict[id(obj)] = obj
200
201def id2obj(id):
202 return _id2obj_dict.get(id)
203\end{verbatim}
204
205
Fred Drakeebcf6a82001-02-01 05:20:20 +0000206\subsection{Weak References in Extension Types
207 \label{weakref-extension}}
208
209One of the goals of the implementation is to allow any type to
210participate in the weak reference mechanism without incurring the
211overhead on those objects which do not benefit by weak referencing
212(such as numbers).
213
214For an object to be weakly referencable, the extension must include a
215\ctype{PyObject *} field in the instance structure for the use of the
Fred Drake5e0dfac2001-03-23 04:36:02 +0000216weak reference mechanism; it must be initialized to \NULL{} by the
217object's constructor. It must also set the \member{tp_weaklistoffset}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000218field of the corresponding type object to the offset of the field.
219For example, the instance type is defined with the following structure:
220
221\begin{verbatim}
222typedef struct {
223 PyObject_HEAD
224 PyClassObject *in_class; /* The class object */
Martin v. Löwis5e163332001-02-27 18:36:56 +0000225 PyObject *in_dict; /* A dictionary */
226 PyObject *in_weakreflist; /* List of weak references */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000227} PyInstanceObject;
228\end{verbatim}
229
230The statically-declared type object for instances is defined this way:
231
232\begin{verbatim}
233PyTypeObject PyInstance_Type = {
234 PyObject_HEAD_INIT(&PyType_Type)
235 0,
236 "instance",
237
238 /* lots of stuff omitted for brevity */
239
240 offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */
241};
242\end{verbatim}
243
244The only further addition is that the destructor needs to call the
245weak reference manager to clear any weak references and return if the
246object has been resurrected. This needs to occur before any other
247parts of the destruction have occurred:
248
249\begin{verbatim}
250static void
251instance_dealloc(PyInstanceObject *inst)
252{
253 /* allocate tempories if needed, but do not begin
254 destruction here
255 */
256
257 if (!PyObject_ClearWeakRefs((PyObject *) inst))
258 return;
259
260 /* proceed with object destuction normally */
261}
262\end{verbatim}