blob: d88b0516f584b08d48f74ee6597d398472e7d2d5 [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
17XXX --- need to say more here!
18
19Not all objects can be weakly referenced; those objects which do
Fred Drake5e0dfac2001-03-23 04:36:02 +000020include class instances, functions written in Python (but not in C),
21and methods (both bound and unbound). Extension types can easily
Fred Drakeebcf6a82001-02-01 05:20:20 +000022be made to support weak references; see section \ref{weakref-extension},
23``Weak References in Extension Types,'' for more information.
24
Fred Drakeebcf6a82001-02-01 05:20:20 +000025
26\begin{funcdesc}{ref}{object\optional{, callback}}
27 Return a weak reference to \var{object}. If \var{callback} is
28 provided, it will be called when the object is about to be
29 finalized; the weak reference object will be passed as the only
30 parameter to the callback; the referent will no longer be available.
31 The original object can be retrieved by calling the reference
32 object, if the referent is still alive.
33
34 It is allowable for many weak references to be constructed for the
35 same object. Callbacks registered for each weak reference will be
36 called from the most recently registered callback to the oldest
37 registered callback.
38
39 Exceptions raised by the callback will be noted on the standard
Andrew M. Kuchlinge7d7e6c2001-02-14 02:39:11 +000040 error output, but cannot be propagated; they are handled in exactly
Fred Drakeebcf6a82001-02-01 05:20:20 +000041 the same way as exceptions raised from an object's
42 \method{__del__()} method.
Martin v. Löwis5e163332001-02-27 18:36:56 +000043
44 Weak references are hashable if the \var{object} is hashable. They
45 will maintain their hash value even after the \var{object} was
46 deleted. If \function{hash()} is called the first time only after
47 the \var{object} was deleted, the call will raise
48 \exception{TypeError}.
49
50 Weak references support test for equality, but not ordering. If the
51 \var{object} is still alive, to references are equal if the objects
52 are equal (regardless of the \var{callback}). If the \var{object}
53 has been deleted, they are equal iff they are identical.
Fred Drakeebcf6a82001-02-01 05:20:20 +000054\end{funcdesc}
55
Fred Drakeebcf6a82001-02-01 05:20:20 +000056\begin{funcdesc}{proxy}{object\optional{, callback}}
57 Return a proxy to \var{object} which uses a weak reference. This
58 supports use of the proxy in most contexts instead of requiring the
59 explicit dereferencing used with weak reference objects. The
60 returned object will have a type of either \code{ProxyType} or
61 \code{CallableProxyType}, depending on whether \var{object} is
62 callable. Proxy objects are not hashable regardless of the
63 referent; this avoids a number of problems related to their
64 fundamentally mutable nature, and prevent their use as dictionary
Fred Drakee7ec1ef2001-05-10 17:22:17 +000065 keys. \var{callback} is the same as the parameter of the same name
Fred Drakeebcf6a82001-02-01 05:20:20 +000066 to the \function{ref()} function.
67\end{funcdesc}
68
69\begin{funcdesc}{getweakrefcount}{object}
70 Return the number of weak references and proxies which refer to
71 \var{object}.
72\end{funcdesc}
73
74\begin{funcdesc}{getweakrefs}{object}
75 Return a list of all weak reference and proxy objects which refer to
76 \var{object}.
77\end{funcdesc}
78
Martin v. Löwis5e163332001-02-27 18:36:56 +000079\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +000080 Mapping class that references keys weakly. Entries in the
81 dictionary will be discarded when there is no longer a strong
82 reference to the key. This can be used to associate additional data
83 with an object owned by other parts of an application without adding
84 attributes to those objects. This can be especially useful with
85 objects that override attribute accesses.
Martin v. Löwis5e163332001-02-27 18:36:56 +000086\end{classdesc}
87
88\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +000089 Mapping class that references values weakly. Entries in the
90 dictionary will be discarded when no strong reference to the value
91 exists anymore.
Fred Drakeebcf6a82001-02-01 05:20:20 +000092\end{classdesc}
93
94\begin{datadesc}{ReferenceType}
95 The type object for weak references objects.
96\end{datadesc}
97
98\begin{datadesc}{ProxyType}
99 The type object for proxies of objects which are not callable.
100\end{datadesc}
101
102\begin{datadesc}{CallableProxyType}
103 The type object for proxies of callable objects.
104\end{datadesc}
105
106\begin{datadesc}{ProxyTypes}
107 Sequence containing all the type objects for proxies. This can make
108 it simpler to test if an object is a proxy without being dependent
109 on naming both proxy types.
110\end{datadesc}
111
Fred Drakeac154a12001-04-10 19:57:58 +0000112\begin{excdesc}{ReferenceError}
113 Exception raised when a proxy object is used but the underlying
Fred Drake8c2c3d32001-10-06 06:10:54 +0000114 object has been collected. This is the same as the standard
115 \exception{ReferenceError} exception.
Fred Drakeac154a12001-04-10 19:57:58 +0000116\end{excdesc}
117
Fred Drakeebcf6a82001-02-01 05:20:20 +0000118
119\begin{seealso}
120 \seepep{0205}{Weak References}{The proposal and rationale for this
121 feature, including links to earlier implementations
122 and information about similar features in other
123 languages.}
124\end{seealso}
125
126
127\subsection{Weak Reference Objects
128 \label{weakref-objects}}
129
130Weak reference objects have no attributes or methods, but do allow the
131referent to be obtained, if it still exists, by calling it:
132
133\begin{verbatim}
134>>> import weakref
135>>> class Object:
136... pass
137...
138>>> o = Object()
139>>> r = weakref.ref(o)
140>>> o2 = r()
141>>> o is o2
1421
143\end{verbatim}
144
145If the referent no longer exists, calling the reference object returns
146\code{None}:
147
148\begin{verbatim}
149>>> del o, o2
150>>> print r()
151None
152\end{verbatim}
153
154Testing that a weak reference object is still live should be done
Fred Drake5d548792001-08-03 03:50:28 +0000155using the expression \code{\var{ref}() is not None}. Normally,
Fred Drakeebcf6a82001-02-01 05:20:20 +0000156application code that needs to use a reference object should follow
157this pattern:
158
159\begin{verbatim}
Fred Drake5d548792001-08-03 03:50:28 +0000160o = ref()
Fred Drakeebcf6a82001-02-01 05:20:20 +0000161if o is None:
162 # referent has been garbage collected
163 print "Object has been allocated; can't frobnicate."
164else:
165 print "Object is still live!"
166 o.do_something_useful()
167\end{verbatim}
168
169Using a separate test for ``liveness'' creates race conditions in
170threaded applications; another thread can cause a weak reference to
171become invalidated before the \method{get()} method is called; the
172idiom shown above is safe in threaded applications as well as
173single-threaded applications.
174
175
Fred Drakecb839882001-03-28 21:15:41 +0000176\subsection{Example \label{weakref-example}}
177
178This simple example shows how an application can use objects IDs to
179retrieve objects that it has seen before. The IDs of the objects can
180then be used in other data structures without forcing the objects to
181remain alive, but the objects can still be retrieved by ID if they
182do.
183
184% Example contributed by Tim Peters <tim_one@msn.com>.
185\begin{verbatim}
186import weakref
187
Fred Drakeac154a12001-04-10 19:57:58 +0000188_id2obj_dict = weakref.WeakValueDictionary()
Fred Drakecb839882001-03-28 21:15:41 +0000189
190def remember(obj):
191 _id2obj_dict[id(obj)] = obj
192
193def id2obj(id):
Fred Drake5d548792001-08-03 03:50:28 +0000194 return _id2obj_dict(id)
Fred Drakecb839882001-03-28 21:15:41 +0000195\end{verbatim}
196
197
Fred Drakeebcf6a82001-02-01 05:20:20 +0000198\subsection{Weak References in Extension Types
199 \label{weakref-extension}}
200
201One of the goals of the implementation is to allow any type to
202participate in the weak reference mechanism without incurring the
203overhead on those objects which do not benefit by weak referencing
204(such as numbers).
205
206For an object to be weakly referencable, the extension must include a
207\ctype{PyObject *} field in the instance structure for the use of the
Fred Drake5e0dfac2001-03-23 04:36:02 +0000208weak reference mechanism; it must be initialized to \NULL{} by the
209object's constructor. It must also set the \member{tp_weaklistoffset}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000210field of the corresponding type object to the offset of the field.
211For example, the instance type is defined with the following structure:
212
213\begin{verbatim}
214typedef struct {
215 PyObject_HEAD
216 PyClassObject *in_class; /* The class object */
Martin v. Löwis5e163332001-02-27 18:36:56 +0000217 PyObject *in_dict; /* A dictionary */
218 PyObject *in_weakreflist; /* List of weak references */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000219} PyInstanceObject;
220\end{verbatim}
221
222The statically-declared type object for instances is defined this way:
223
224\begin{verbatim}
225PyTypeObject PyInstance_Type = {
226 PyObject_HEAD_INIT(&PyType_Type)
227 0,
228 "instance",
229
Fred Drakef66cb5d2001-06-22 17:20:29 +0000230 /* Lots of stuff omitted for brevity... */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000231
232 offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */
233};
234\end{verbatim}
235
236The only further addition is that the destructor needs to call the
Fred Drakef66cb5d2001-06-22 17:20:29 +0000237weak reference manager to clear any weak references. This should be
238done before any other parts of the destruction have occurred:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000239
240\begin{verbatim}
241static void
242instance_dealloc(PyInstanceObject *inst)
243{
Fred Drakef66cb5d2001-06-22 17:20:29 +0000244 /* Allocate tempories if needed, but do not begin
245 destruction just yet.
Fred Drakeebcf6a82001-02-01 05:20:20 +0000246 */
247
Fred Drakef66cb5d2001-06-22 17:20:29 +0000248 PyObject_ClearWeakRefs((PyObject *) inst);
Fred Drakeebcf6a82001-02-01 05:20:20 +0000249
Fred Drakef66cb5d2001-06-22 17:20:29 +0000250 /* Proceed with object destuction normally. */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000251}
252\end{verbatim}