blob: 97f624d25c257e325700ac09dd41514e1014cc2a [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
19include class instances and dictionaries. Extension types can easily
20be made to support weak references; see section \ref{weakref-extension},
21``Weak References in Extension Types,'' for more information.
22
Fred Drakeebcf6a82001-02-01 05:20:20 +000023\strong{Warning:}
24The desired semantics of weak-reference proxy objects are not
25completely clear; it is very difficult to create proxies which behave
26exactly like the type of the referent. The details of these objects
27are likely to change to some degree before the final release as
28experience reports become available.
29
Fred Drakeebcf6a82001-02-01 05:20:20 +000030
31\begin{funcdesc}{ref}{object\optional{, callback}}
32 Return a weak reference to \var{object}. If \var{callback} is
33 provided, it will be called when the object is about to be
34 finalized; the weak reference object will be passed as the only
35 parameter to the callback; the referent will no longer be available.
36 The original object can be retrieved by calling the reference
37 object, if the referent is still alive.
38
39 It is allowable for many weak references to be constructed for the
40 same object. Callbacks registered for each weak reference will be
41 called from the most recently registered callback to the oldest
42 registered callback.
43
44 Exceptions raised by the callback will be noted on the standard
Andrew M. Kuchlinge7d7e6c2001-02-14 02:39:11 +000045 error output, but cannot be propagated; they are handled in exactly
Fred Drakeebcf6a82001-02-01 05:20:20 +000046 the same way as exceptions raised from an object's
47 \method{__del__()} method.
Martin v. Löwis5e163332001-02-27 18:36:56 +000048
49 Weak references are hashable if the \var{object} is hashable. They
50 will maintain their hash value even after the \var{object} was
51 deleted. If \function{hash()} is called the first time only after
52 the \var{object} was deleted, the call will raise
53 \exception{TypeError}.
54
55 Weak references support test for equality, but not ordering. If the
56 \var{object} is still alive, to references are equal if the objects
57 are equal (regardless of the \var{callback}). If the \var{object}
58 has been deleted, they are equal iff they are identical.
59
Fred Drakeebcf6a82001-02-01 05:20:20 +000060\end{funcdesc}
61
Martin v. Löwis5e163332001-02-27 18:36:56 +000062\begin{funcdesc}{mapping}{\optional{dict\optional{, weakkeys=0}}}
Fred Drakeebcf6a82001-02-01 05:20:20 +000063 Return a weak dictionary. If \var{dict} is given and not
64 \code{None}, the new dictionary will contain the items contained in
65 \var{dict}. The values from \var{dict} must be weakly referencable;
66 if any values which would be inserted into the new mapping are not
67 weakly referencable, \exception{TypeError} will be raised and the
68 new mapping will be empty.
Martin v. Löwis5e163332001-02-27 18:36:56 +000069
70 If the \var{weakkeys} argument is not given or zero, the values in
71 the dictionary are weak. That means the entries in the dictionary
72 will be discarded when no strong reference to the value exists
73 anymore.
74
75 If the \var{weakkeys} argument is nonzero, the keys in the
76 dictionary are weak, i.e. the entry in the dictionary is discarded
77 when the last strong reference to the key is discarded.
Fred Drakeebcf6a82001-02-01 05:20:20 +000078\end{funcdesc}
79
80\begin{funcdesc}{proxy}{object\optional{, callback}}
81 Return a proxy to \var{object} which uses a weak reference. This
82 supports use of the proxy in most contexts instead of requiring the
83 explicit dereferencing used with weak reference objects. The
84 returned object will have a type of either \code{ProxyType} or
85 \code{CallableProxyType}, depending on whether \var{object} is
86 callable. Proxy objects are not hashable regardless of the
87 referent; this avoids a number of problems related to their
88 fundamentally mutable nature, and prevent their use as dictionary
89 keys. \var{callable} is the same as the parameter of the same name
90 to the \function{ref()} function.
91\end{funcdesc}
92
93\begin{funcdesc}{getweakrefcount}{object}
94 Return the number of weak references and proxies which refer to
95 \var{object}.
96\end{funcdesc}
97
98\begin{funcdesc}{getweakrefs}{object}
99 Return a list of all weak reference and proxy objects which refer to
100 \var{object}.
101\end{funcdesc}
102
Martin v. Löwis5e163332001-02-27 18:36:56 +0000103\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
104 The class of the mapping objects returned by \function{mapping()}
105 when \var{weakkeys} is true. This can be used for subclassing the
106 implementation if needed.
107\end{classdesc}
108
109\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
110 The class of the mapping objects returned by \function{mapping()}
111 when \var{weakkeys} if false. This can be used for subclassing the
112 implementation if needed.
Fred Drakeebcf6a82001-02-01 05:20:20 +0000113\end{classdesc}
114
115\begin{datadesc}{ReferenceType}
116 The type object for weak references objects.
117\end{datadesc}
118
119\begin{datadesc}{ProxyType}
120 The type object for proxies of objects which are not callable.
121\end{datadesc}
122
123\begin{datadesc}{CallableProxyType}
124 The type object for proxies of callable objects.
125\end{datadesc}
126
127\begin{datadesc}{ProxyTypes}
128 Sequence containing all the type objects for proxies. This can make
129 it simpler to test if an object is a proxy without being dependent
130 on naming both proxy types.
131\end{datadesc}
132
133
134\begin{seealso}
135 \seepep{0205}{Weak References}{The proposal and rationale for this
136 feature, including links to earlier implementations
137 and information about similar features in other
138 languages.}
139\end{seealso}
140
141
142\subsection{Weak Reference Objects
143 \label{weakref-objects}}
144
145Weak reference objects have no attributes or methods, but do allow the
146referent to be obtained, if it still exists, by calling it:
147
148\begin{verbatim}
149>>> import weakref
150>>> class Object:
151... pass
152...
153>>> o = Object()
154>>> r = weakref.ref(o)
155>>> o2 = r()
156>>> o is o2
1571
158\end{verbatim}
159
160If the referent no longer exists, calling the reference object returns
161\code{None}:
162
163\begin{verbatim}
164>>> del o, o2
165>>> print r()
166None
167\end{verbatim}
168
169Testing that a weak reference object is still live should be done
170using the expression \code{\var{ref}.get() is not None}. Normally,
171application code that needs to use a reference object should follow
172this pattern:
173
174\begin{verbatim}
175o = ref.get()
176if o is None:
177 # referent has been garbage collected
178 print "Object has been allocated; can't frobnicate."
179else:
180 print "Object is still live!"
181 o.do_something_useful()
182\end{verbatim}
183
184Using a separate test for ``liveness'' creates race conditions in
185threaded applications; another thread can cause a weak reference to
186become invalidated before the \method{get()} method is called; the
187idiom shown above is safe in threaded applications as well as
188single-threaded applications.
189
190
191\subsection{Weak References in Extension Types
192 \label{weakref-extension}}
193
194One of the goals of the implementation is to allow any type to
195participate in the weak reference mechanism without incurring the
196overhead on those objects which do not benefit by weak referencing
197(such as numbers).
198
199For an object to be weakly referencable, the extension must include a
200\ctype{PyObject *} field in the instance structure for the use of the
201weak reference mechanism; it will be initialized by Python's functions
202for object creation. It must also set the \code{tp_weaklistoffset}
203field of the corresponding type object to the offset of the field.
204For example, the instance type is defined with the following structure:
205
206\begin{verbatim}
207typedef struct {
208 PyObject_HEAD
209 PyClassObject *in_class; /* The class object */
Martin v. Löwis5e163332001-02-27 18:36:56 +0000210 PyObject *in_dict; /* A dictionary */
211 PyObject *in_weakreflist; /* List of weak references */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000212} PyInstanceObject;
213\end{verbatim}
214
215The statically-declared type object for instances is defined this way:
216
217\begin{verbatim}
218PyTypeObject PyInstance_Type = {
219 PyObject_HEAD_INIT(&PyType_Type)
220 0,
221 "instance",
222
223 /* lots of stuff omitted for brevity */
224
225 offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */
226};
227\end{verbatim}
228
229The only further addition is that the destructor needs to call the
230weak reference manager to clear any weak references and return if the
231object has been resurrected. This needs to occur before any other
232parts of the destruction have occurred:
233
234\begin{verbatim}
235static void
236instance_dealloc(PyInstanceObject *inst)
237{
238 /* allocate tempories if needed, but do not begin
239 destruction here
240 */
241
242 if (!PyObject_ClearWeakRefs((PyObject *) inst))
243 return;
244
245 /* proceed with object destuction normally */
246}
247\end{verbatim}