blob: fc949e6ce1af31fdd7993365f3367f0b0936fcbf [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
Georg Brandl9a65d582005-07-02 19:07:30 +000013% When making changes to the examples in this file, be sure to update
14% Lib/test/test_weakref.py::libreftest too!
Fred Drakeebcf6a82001-02-01 05:20:20 +000015
16The \module{weakref} module allows the Python programmer to create
17\dfn{weak references} to objects.
18
Tim Peters5a5b2432003-11-21 22:20:57 +000019In the following, the term \dfn{referent} means the
Fred Drake7408da52001-10-26 17:40:22 +000020object which is referred to by a weak reference.
21
Tim Peters5a5b2432003-11-21 22:20:57 +000022A weak reference to an object is not enough to keep the object alive:
23when the only remaining references to a referent are weak references,
24garbage collection is free to destroy the referent and reuse its memory
25for something else. A primary use for weak references is to implement
26caches or mappings holding large objects, where it's desired that a
27large object not be kept alive solely because it appears in a cache or
28mapping. For example, if you have a number of large binary image objects,
29you may wish to associate a name with each. If you used a Python
30dictionary to map names to images, or images to names, the image objects
31would remain alive just because they appeared as values or keys in the
32dictionaries. The \class{WeakKeyDictionary} and
33\class{WeakValueDictionary} classes supplied by the \module{weakref}
34module are an alternative, using weak references to construct mappings
35that don't keep objects alive solely because they appear in the mapping
36objects. If, for example, an image object is a value in a
37\class{WeakValueDictionary}, then when the last remaining
38references to that image object are the weak references held by weak
39mappings, garbage collection can reclaim the object, and its corresponding
40entries in weak mappings are simply deleted.
41
42\class{WeakKeyDictionary} and \class{WeakValueDictionary} use weak
43references in their implementation, setting up callback functions on
44the weak references that notify the weak dictionaries when a key or value
45has been reclaimed by garbage collection. Most programs should find that
46using one of these weak dictionary types is all they need -- it's
47not usually necessary to create your own weak references directly. The
48low-level machinery used by the weak dictionary implementations is exposed
49by the \module{weakref} module for the benefit of advanced uses.
Fred Drakeebcf6a82001-02-01 05:20:20 +000050
Raymond Hettingerf8020e02003-07-02 15:10:38 +000051Not all objects can be weakly referenced; those objects which can
Fred Drake5e0dfac2001-03-23 04:36:02 +000052include class instances, functions written in Python (but not in C),
Raymond Hettinger027bb632004-05-31 03:09:25 +000053methods (both bound and unbound), sets, frozensets, file objects,
Raymond Hettinger34809172004-06-12 06:56:44 +000054generators, type objects, DBcursor objects from the \module{bsddb} module,
Raymond Hettinger027bb632004-05-31 03:09:25 +000055sockets, arrays, deques, and regular expression pattern objects.
56\versionchanged[Added support for files, sockets, arrays, and patterns]{2.4}
57
58Several builtin types such as \class{list} and \class{dict} do not
59directly support weak references but can add support through subclassing:
60
61\begin{verbatim}
62class Dict(dict):
63 pass
64
65obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
66\end{verbatim}
67
68Extension types can easily be made to support weak references; see section
69\ref{weakref-extension}, ``Weak References in Extension Types,'' for more
70information.
Fred Drakeebcf6a82001-02-01 05:20:20 +000071
Fred Drakeebcf6a82001-02-01 05:20:20 +000072
Fred Drake0a4dd392004-07-02 18:57:45 +000073\begin{classdesc}{ref}{object\optional{, callback}}
Fred Drake7408da52001-10-26 17:40:22 +000074 Return a weak reference to \var{object}. The original object can be
75 retrieved by calling the reference object if the referent is still
76 alive; if the referent is no longer alive, calling the reference
Fred Drake21ae4f92004-02-03 20:55:15 +000077 object will cause \constant{None} to be returned. If \var{callback} is
Armin Rigob9359c42005-12-29 17:43:08 +000078 provided and not \constant{None}, and the returned weakref object is
79 still alive, the callback will be called when the object is about to be
Fred Drakeebcf6a82001-02-01 05:20:20 +000080 finalized; the weak reference object will be passed as the only
81 parameter to the callback; the referent will no longer be available.
Fred Drakeebcf6a82001-02-01 05:20:20 +000082
83 It is allowable for many weak references to be constructed for the
84 same object. Callbacks registered for each weak reference will be
85 called from the most recently registered callback to the oldest
86 registered callback.
87
88 Exceptions raised by the callback will be noted on the standard
Andrew M. Kuchlinge7d7e6c2001-02-14 02:39:11 +000089 error output, but cannot be propagated; they are handled in exactly
Fred Drakeebcf6a82001-02-01 05:20:20 +000090 the same way as exceptions raised from an object's
91 \method{__del__()} method.
Tim Peters5a5b2432003-11-21 22:20:57 +000092
Martin v. Löwis5e163332001-02-27 18:36:56 +000093 Weak references are hashable if the \var{object} is hashable. They
94 will maintain their hash value even after the \var{object} was
95 deleted. If \function{hash()} is called the first time only after
96 the \var{object} was deleted, the call will raise
97 \exception{TypeError}.
Tim Peters5a5b2432003-11-21 22:20:57 +000098
Fred Drake3a2c4622001-10-26 03:00:39 +000099 Weak references support tests for equality, but not ordering. If
Fred Drake7408da52001-10-26 17:40:22 +0000100 the referents are still alive, two references have the same
Fred Drakeb03d0cc2001-11-26 21:39:40 +0000101 equality relationship as their referents (regardless of the
Fred Drake7408da52001-10-26 17:40:22 +0000102 \var{callback}). If either referent has been deleted, the
103 references are equal only if the reference objects are the same
104 object.
Fred Drake0a4dd392004-07-02 18:57:45 +0000105
106 \versionchanged[This is now a subclassable type rather than a
107 factory function; it derives from \class{object}]
108 {2.4}
109\end{classdesc}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000110
Fred Drakeebcf6a82001-02-01 05:20:20 +0000111\begin{funcdesc}{proxy}{object\optional{, callback}}
112 Return a proxy to \var{object} which uses a weak reference. This
113 supports use of the proxy in most contexts instead of requiring the
114 explicit dereferencing used with weak reference objects. The
115 returned object will have a type of either \code{ProxyType} or
116 \code{CallableProxyType}, depending on whether \var{object} is
117 callable. Proxy objects are not hashable regardless of the
118 referent; this avoids a number of problems related to their
119 fundamentally mutable nature, and prevent their use as dictionary
Fred Drakee7ec1ef2001-05-10 17:22:17 +0000120 keys. \var{callback} is the same as the parameter of the same name
Fred Drakeebcf6a82001-02-01 05:20:20 +0000121 to the \function{ref()} function.
122\end{funcdesc}
123
124\begin{funcdesc}{getweakrefcount}{object}
125 Return the number of weak references and proxies which refer to
126 \var{object}.
127\end{funcdesc}
128
129\begin{funcdesc}{getweakrefs}{object}
130 Return a list of all weak reference and proxy objects which refer to
131 \var{object}.
132\end{funcdesc}
133
Martin v. Löwis5e163332001-02-27 18:36:56 +0000134\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000135 Mapping class that references keys weakly. Entries in the
136 dictionary will be discarded when there is no longer a strong
137 reference to the key. This can be used to associate additional data
138 with an object owned by other parts of an application without adding
139 attributes to those objects. This can be especially useful with
140 objects that override attribute accesses.
Tim Peters5a5b2432003-11-21 22:20:57 +0000141
142 \note{Caution: Because a \class{WeakKeyDictionary} is built on top
143 of a Python dictionary, it must not change size when iterating
144 over it. This can be difficult to ensure for a
145 \class{WeakKeyDictionary} because actions performed by the
146 program during iteration may cause items in the dictionary
147 to vanish "by magic" (as a side effect of garbage collection).}
Martin v. Löwis5e163332001-02-27 18:36:56 +0000148\end{classdesc}
149
Fred Drake017e68c2006-05-02 06:53:59 +0000150\class{WeakKeyDictionary} objects have the following additional
151methods. These expose the internal references directly. The
152references are not guaranteed to be ``live'' at the time they are
153used, so the result of calling the references needs to be checked
154before being used. This can be used to avoid creating references that
155will cause the garbage collector to keep the keys around longer than
156needed.
157
158\begin{methoddesc}{iterkeyrefs}{}
159 Return an iterator that yields the weak references to the keys.
160 \versionadded{2.5}
161\end{methoddesc}
162
163\begin{methoddesc}{keyrefs}{}
164 Return a list of weak references to the keys.
165 \versionadded{2.5}
166\end{methoddesc}
167
Martin v. Löwis5e163332001-02-27 18:36:56 +0000168\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000169 Mapping class that references values weakly. Entries in the
170 dictionary will be discarded when no strong reference to the value
Fred Drake7408da52001-10-26 17:40:22 +0000171 exists any more.
Tim Peters5a5b2432003-11-21 22:20:57 +0000172
173 \note{Caution: Because a \class{WeakValueDictionary} is built on top
174 of a Python dictionary, it must not change size when iterating
175 over it. This can be difficult to ensure for a
176 \class{WeakValueDictionary} because actions performed by the
177 program during iteration may cause items in the dictionary
178 to vanish "by magic" (as a side effect of garbage collection).}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000179\end{classdesc}
180
Fred Drake017e68c2006-05-02 06:53:59 +0000181\class{WeakValueDictionary} objects have the following additional
182methods. These method have the same issues as the
183\method{iterkeyrefs()} and \method{keyrefs()} methods of
184\class{WeakKeyDictionary} objects.
185
186\begin{methoddesc}{itervaluerefs}{}
187 Return an iterator that yields the weak references to the values.
188 \versionadded{2.5}
189\end{methoddesc}
190
191\begin{methoddesc}{valuerefs}{}
192 Return a list of weak references to the values.
193 \versionadded{2.5}
194\end{methoddesc}
195
Fred Drakeebcf6a82001-02-01 05:20:20 +0000196\begin{datadesc}{ReferenceType}
197 The type object for weak references objects.
198\end{datadesc}
199
200\begin{datadesc}{ProxyType}
201 The type object for proxies of objects which are not callable.
202\end{datadesc}
203
204\begin{datadesc}{CallableProxyType}
205 The type object for proxies of callable objects.
206\end{datadesc}
207
208\begin{datadesc}{ProxyTypes}
209 Sequence containing all the type objects for proxies. This can make
210 it simpler to test if an object is a proxy without being dependent
211 on naming both proxy types.
212\end{datadesc}
213
Fred Drakeac154a12001-04-10 19:57:58 +0000214\begin{excdesc}{ReferenceError}
215 Exception raised when a proxy object is used but the underlying
Fred Drake8c2c3d32001-10-06 06:10:54 +0000216 object has been collected. This is the same as the standard
217 \exception{ReferenceError} exception.
Fred Drakeac154a12001-04-10 19:57:58 +0000218\end{excdesc}
219
Fred Drakeebcf6a82001-02-01 05:20:20 +0000220
221\begin{seealso}
222 \seepep{0205}{Weak References}{The proposal and rationale for this
223 feature, including links to earlier implementations
224 and information about similar features in other
225 languages.}
226\end{seealso}
227
228
229\subsection{Weak Reference Objects
230 \label{weakref-objects}}
231
232Weak reference objects have no attributes or methods, but do allow the
233referent to be obtained, if it still exists, by calling it:
234
235\begin{verbatim}
236>>> import weakref
237>>> class Object:
238... pass
239...
240>>> o = Object()
241>>> r = weakref.ref(o)
242>>> o2 = r()
243>>> o is o2
Martin v. Löwisccabed32003-11-27 19:48:03 +0000244True
Fred Drakeebcf6a82001-02-01 05:20:20 +0000245\end{verbatim}
246
247If the referent no longer exists, calling the reference object returns
Fred Drake21ae4f92004-02-03 20:55:15 +0000248\constant{None}:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000249
250\begin{verbatim}
251>>> del o, o2
252>>> print r()
253None
254\end{verbatim}
255
256Testing that a weak reference object is still live should be done
Fred Drake5d548792001-08-03 03:50:28 +0000257using the expression \code{\var{ref}() is not None}. Normally,
Fred Drakeebcf6a82001-02-01 05:20:20 +0000258application code that needs to use a reference object should follow
259this pattern:
260
261\begin{verbatim}
Fred Drake7408da52001-10-26 17:40:22 +0000262# r is a weak reference object
263o = r()
Fred Drakeebcf6a82001-02-01 05:20:20 +0000264if o is None:
265 # referent has been garbage collected
Georg Brandl9a65d582005-07-02 19:07:30 +0000266 print "Object has been deallocated; can't frobnicate."
Fred Drakeebcf6a82001-02-01 05:20:20 +0000267else:
268 print "Object is still live!"
269 o.do_something_useful()
270\end{verbatim}
271
272Using a separate test for ``liveness'' creates race conditions in
273threaded applications; another thread can cause a weak reference to
Fred Drake7408da52001-10-26 17:40:22 +0000274become invalidated before the weak reference is called; the
Fred Drakeebcf6a82001-02-01 05:20:20 +0000275idiom shown above is safe in threaded applications as well as
276single-threaded applications.
277
Fred Drake0a4dd392004-07-02 18:57:45 +0000278Specialized versions of \class{ref} objects can be created through
279subclassing. This is used in the implementation of the
280\class{WeakValueDictionary} to reduce the memory overhead for each
281entry in the mapping. This may be most useful to associate additional
282information with a reference, but could also be used to insert
283additional processing on calls to retrieve the referent.
284
285This example shows how a subclass of \class{ref} can be used to store
286additional information about an object and affect the value that's
287returned when the referent is accessed:
288
289\begin{verbatim}
290import weakref
291
292class ExtendedRef(weakref.ref):
Fred Drake0a4dd392004-07-02 18:57:45 +0000293 def __init__(self, ob, callback=None, **annotations):
294 super(ExtendedRef, self).__init__(ob, callback)
Georg Brandl376e6222005-07-02 10:44:32 +0000295 self.__counter = 0
296 for k, v in annotations.iteritems():
Fred Drake0a4dd392004-07-02 18:57:45 +0000297 setattr(self, k, v)
298
299 def __call__(self):
300 """Return a pair containing the referent and the number of
301 times the reference has been called.
302 """
Georg Brandl9a65d582005-07-02 19:07:30 +0000303 ob = super(ExtendedRef, self).__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000304 if ob is not None:
305 self.__counter += 1
306 ob = (ob, self.__counter)
307 return ob
308\end{verbatim}
309
Fred Drakeebcf6a82001-02-01 05:20:20 +0000310
Fred Drakecb839882001-03-28 21:15:41 +0000311\subsection{Example \label{weakref-example}}
312
313This simple example shows how an application can use objects IDs to
314retrieve objects that it has seen before. The IDs of the objects can
315then be used in other data structures without forcing the objects to
316remain alive, but the objects can still be retrieved by ID if they
317do.
318
Fred Drake42713102003-12-30 16:15:35 +0000319% Example contributed by Tim Peters.
Fred Drakecb839882001-03-28 21:15:41 +0000320\begin{verbatim}
321import weakref
322
Fred Drakeac154a12001-04-10 19:57:58 +0000323_id2obj_dict = weakref.WeakValueDictionary()
Fred Drakecb839882001-03-28 21:15:41 +0000324
325def remember(obj):
Fred Drake7408da52001-10-26 17:40:22 +0000326 oid = id(obj)
327 _id2obj_dict[oid] = obj
328 return oid
Fred Drakecb839882001-03-28 21:15:41 +0000329
Fred Drake7408da52001-10-26 17:40:22 +0000330def id2obj(oid):
331 return _id2obj_dict[oid]
Fred Drakecb839882001-03-28 21:15:41 +0000332\end{verbatim}
333
334
Fred Drakeebcf6a82001-02-01 05:20:20 +0000335\subsection{Weak References in Extension Types
336 \label{weakref-extension}}
337
338One of the goals of the implementation is to allow any type to
339participate in the weak reference mechanism without incurring the
340overhead on those objects which do not benefit by weak referencing
341(such as numbers).
342
343For an object to be weakly referencable, the extension must include a
Fred Drake7408da52001-10-26 17:40:22 +0000344\ctype{PyObject*} field in the instance structure for the use of the
Fred Drake5e0dfac2001-03-23 04:36:02 +0000345weak reference mechanism; it must be initialized to \NULL{} by the
346object's constructor. It must also set the \member{tp_weaklistoffset}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000347field of the corresponding type object to the offset of the field.
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000348Also, it needs to add \constant{Py_TPFLAGS_HAVE_WEAKREFS} to the
349tp_flags slot. For example, the instance type is defined with the
350following structure:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000351
352\begin{verbatim}
353typedef struct {
354 PyObject_HEAD
355 PyClassObject *in_class; /* The class object */
Martin v. Löwis5e163332001-02-27 18:36:56 +0000356 PyObject *in_dict; /* A dictionary */
357 PyObject *in_weakreflist; /* List of weak references */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000358} PyInstanceObject;
359\end{verbatim}
360
361The statically-declared type object for instances is defined this way:
362
363\begin{verbatim}
364PyTypeObject PyInstance_Type = {
365 PyObject_HEAD_INIT(&PyType_Type)
366 0,
Guido van Rossum14648392001-12-08 18:02:58 +0000367 "module.instance",
Fred Drakeebcf6a82001-02-01 05:20:20 +0000368
Fred Drakef66cb5d2001-06-22 17:20:29 +0000369 /* Lots of stuff omitted for brevity... */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000370
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000371 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS /* tp_flags */
372 0, /* tp_doc */
373 0, /* tp_traverse */
374 0, /* tp_clear */
375 0, /* tp_richcompare */
376 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000377};
378\end{verbatim}
379
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000380The type constructor is responsible for initializing the weak reference
381list to \NULL:
382
383\begin{verbatim}
Tim Peters5a5b2432003-11-21 22:20:57 +0000384static PyObject *
385instance_new() {
386 /* Other initialization stuff omitted for brevity */
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000387
Tim Peters5a5b2432003-11-21 22:20:57 +0000388 self->in_weakreflist = NULL;
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000389
Tim Peters5a5b2432003-11-21 22:20:57 +0000390 return (PyObject *) self;
391}
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000392\end{verbatim}
393
Fred Drakeebcf6a82001-02-01 05:20:20 +0000394The only further addition is that the destructor needs to call the
Fred Drakef66cb5d2001-06-22 17:20:29 +0000395weak reference manager to clear any weak references. This should be
Fred Drake7408da52001-10-26 17:40:22 +0000396done before any other parts of the destruction have occurred, but is
397only required if the weak reference list is non-\NULL:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000398
399\begin{verbatim}
400static void
401instance_dealloc(PyInstanceObject *inst)
402{
Fred Drake7408da52001-10-26 17:40:22 +0000403 /* Allocate temporaries if needed, but do not begin
Fred Drakef66cb5d2001-06-22 17:20:29 +0000404 destruction just yet.
Fred Drakeebcf6a82001-02-01 05:20:20 +0000405 */
406
Fred Drake7408da52001-10-26 17:40:22 +0000407 if (inst->in_weakreflist != NULL)
408 PyObject_ClearWeakRefs((PyObject *) inst);
Fred Drakeebcf6a82001-02-01 05:20:20 +0000409
Fred Drakede3d0602001-10-26 11:27:54 +0000410 /* Proceed with object destruction normally. */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000411}
412\end{verbatim}