blob: 840b67412b48d8a6f7aa0d69f0de86cfb849fc74 [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
150\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000151 Mapping class that references values weakly. Entries in the
152 dictionary will be discarded when no strong reference to the value
Fred Drake7408da52001-10-26 17:40:22 +0000153 exists any more.
Tim Peters5a5b2432003-11-21 22:20:57 +0000154
155 \note{Caution: Because a \class{WeakValueDictionary} is built on top
156 of a Python dictionary, it must not change size when iterating
157 over it. This can be difficult to ensure for a
158 \class{WeakValueDictionary} because actions performed by the
159 program during iteration may cause items in the dictionary
160 to vanish "by magic" (as a side effect of garbage collection).}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000161\end{classdesc}
162
163\begin{datadesc}{ReferenceType}
164 The type object for weak references objects.
165\end{datadesc}
166
167\begin{datadesc}{ProxyType}
168 The type object for proxies of objects which are not callable.
169\end{datadesc}
170
171\begin{datadesc}{CallableProxyType}
172 The type object for proxies of callable objects.
173\end{datadesc}
174
175\begin{datadesc}{ProxyTypes}
176 Sequence containing all the type objects for proxies. This can make
177 it simpler to test if an object is a proxy without being dependent
178 on naming both proxy types.
179\end{datadesc}
180
Fred Drakeac154a12001-04-10 19:57:58 +0000181\begin{excdesc}{ReferenceError}
182 Exception raised when a proxy object is used but the underlying
Fred Drake8c2c3d32001-10-06 06:10:54 +0000183 object has been collected. This is the same as the standard
184 \exception{ReferenceError} exception.
Fred Drakeac154a12001-04-10 19:57:58 +0000185\end{excdesc}
186
Fred Drakeebcf6a82001-02-01 05:20:20 +0000187
188\begin{seealso}
189 \seepep{0205}{Weak References}{The proposal and rationale for this
190 feature, including links to earlier implementations
191 and information about similar features in other
192 languages.}
193\end{seealso}
194
195
196\subsection{Weak Reference Objects
197 \label{weakref-objects}}
198
199Weak reference objects have no attributes or methods, but do allow the
200referent to be obtained, if it still exists, by calling it:
201
202\begin{verbatim}
203>>> import weakref
204>>> class Object:
205... pass
206...
207>>> o = Object()
208>>> r = weakref.ref(o)
209>>> o2 = r()
210>>> o is o2
Martin v. Löwisccabed32003-11-27 19:48:03 +0000211True
Fred Drakeebcf6a82001-02-01 05:20:20 +0000212\end{verbatim}
213
214If the referent no longer exists, calling the reference object returns
Fred Drake21ae4f92004-02-03 20:55:15 +0000215\constant{None}:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000216
217\begin{verbatim}
218>>> del o, o2
219>>> print r()
220None
221\end{verbatim}
222
223Testing that a weak reference object is still live should be done
Fred Drake5d548792001-08-03 03:50:28 +0000224using the expression \code{\var{ref}() is not None}. Normally,
Fred Drakeebcf6a82001-02-01 05:20:20 +0000225application code that needs to use a reference object should follow
226this pattern:
227
228\begin{verbatim}
Fred Drake7408da52001-10-26 17:40:22 +0000229# r is a weak reference object
230o = r()
Fred Drakeebcf6a82001-02-01 05:20:20 +0000231if o is None:
232 # referent has been garbage collected
Georg Brandl9a65d582005-07-02 19:07:30 +0000233 print "Object has been deallocated; can't frobnicate."
Fred Drakeebcf6a82001-02-01 05:20:20 +0000234else:
235 print "Object is still live!"
236 o.do_something_useful()
237\end{verbatim}
238
239Using a separate test for ``liveness'' creates race conditions in
240threaded applications; another thread can cause a weak reference to
Fred Drake7408da52001-10-26 17:40:22 +0000241become invalidated before the weak reference is called; the
Fred Drakeebcf6a82001-02-01 05:20:20 +0000242idiom shown above is safe in threaded applications as well as
243single-threaded applications.
244
Fred Drake0a4dd392004-07-02 18:57:45 +0000245Specialized versions of \class{ref} objects can be created through
246subclassing. This is used in the implementation of the
247\class{WeakValueDictionary} to reduce the memory overhead for each
248entry in the mapping. This may be most useful to associate additional
249information with a reference, but could also be used to insert
250additional processing on calls to retrieve the referent.
251
252This example shows how a subclass of \class{ref} can be used to store
253additional information about an object and affect the value that's
254returned when the referent is accessed:
255
256\begin{verbatim}
257import weakref
258
259class ExtendedRef(weakref.ref):
Fred Drake0a4dd392004-07-02 18:57:45 +0000260 def __init__(self, ob, callback=None, **annotations):
261 super(ExtendedRef, self).__init__(ob, callback)
Georg Brandl376e6222005-07-02 10:44:32 +0000262 self.__counter = 0
263 for k, v in annotations.iteritems():
Fred Drake0a4dd392004-07-02 18:57:45 +0000264 setattr(self, k, v)
265
266 def __call__(self):
267 """Return a pair containing the referent and the number of
268 times the reference has been called.
269 """
Georg Brandl9a65d582005-07-02 19:07:30 +0000270 ob = super(ExtendedRef, self).__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000271 if ob is not None:
272 self.__counter += 1
273 ob = (ob, self.__counter)
274 return ob
275\end{verbatim}
276
Fred Drakeebcf6a82001-02-01 05:20:20 +0000277
Fred Drakecb839882001-03-28 21:15:41 +0000278\subsection{Example \label{weakref-example}}
279
280This simple example shows how an application can use objects IDs to
281retrieve objects that it has seen before. The IDs of the objects can
282then be used in other data structures without forcing the objects to
283remain alive, but the objects can still be retrieved by ID if they
284do.
285
Fred Drake42713102003-12-30 16:15:35 +0000286% Example contributed by Tim Peters.
Fred Drakecb839882001-03-28 21:15:41 +0000287\begin{verbatim}
288import weakref
289
Fred Drakeac154a12001-04-10 19:57:58 +0000290_id2obj_dict = weakref.WeakValueDictionary()
Fred Drakecb839882001-03-28 21:15:41 +0000291
292def remember(obj):
Fred Drake7408da52001-10-26 17:40:22 +0000293 oid = id(obj)
294 _id2obj_dict[oid] = obj
295 return oid
Fred Drakecb839882001-03-28 21:15:41 +0000296
Fred Drake7408da52001-10-26 17:40:22 +0000297def id2obj(oid):
298 return _id2obj_dict[oid]
Fred Drakecb839882001-03-28 21:15:41 +0000299\end{verbatim}
300
301
Fred Drakeebcf6a82001-02-01 05:20:20 +0000302\subsection{Weak References in Extension Types
303 \label{weakref-extension}}
304
305One of the goals of the implementation is to allow any type to
306participate in the weak reference mechanism without incurring the
307overhead on those objects which do not benefit by weak referencing
308(such as numbers).
309
310For an object to be weakly referencable, the extension must include a
Fred Drake7408da52001-10-26 17:40:22 +0000311\ctype{PyObject*} field in the instance structure for the use of the
Fred Drake5e0dfac2001-03-23 04:36:02 +0000312weak reference mechanism; it must be initialized to \NULL{} by the
313object's constructor. It must also set the \member{tp_weaklistoffset}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000314field of the corresponding type object to the offset of the field.
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000315Also, it needs to add \constant{Py_TPFLAGS_HAVE_WEAKREFS} to the
316tp_flags slot. For example, the instance type is defined with the
317following structure:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000318
319\begin{verbatim}
320typedef struct {
321 PyObject_HEAD
322 PyClassObject *in_class; /* The class object */
Martin v. Löwis5e163332001-02-27 18:36:56 +0000323 PyObject *in_dict; /* A dictionary */
324 PyObject *in_weakreflist; /* List of weak references */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000325} PyInstanceObject;
326\end{verbatim}
327
328The statically-declared type object for instances is defined this way:
329
330\begin{verbatim}
331PyTypeObject PyInstance_Type = {
332 PyObject_HEAD_INIT(&PyType_Type)
333 0,
Guido van Rossum14648392001-12-08 18:02:58 +0000334 "module.instance",
Fred Drakeebcf6a82001-02-01 05:20:20 +0000335
Fred Drakef66cb5d2001-06-22 17:20:29 +0000336 /* Lots of stuff omitted for brevity... */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000337
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000338 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS /* tp_flags */
339 0, /* tp_doc */
340 0, /* tp_traverse */
341 0, /* tp_clear */
342 0, /* tp_richcompare */
343 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000344};
345\end{verbatim}
346
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000347The type constructor is responsible for initializing the weak reference
348list to \NULL:
349
350\begin{verbatim}
Tim Peters5a5b2432003-11-21 22:20:57 +0000351static PyObject *
352instance_new() {
353 /* Other initialization stuff omitted for brevity */
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000354
Tim Peters5a5b2432003-11-21 22:20:57 +0000355 self->in_weakreflist = NULL;
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000356
Tim Peters5a5b2432003-11-21 22:20:57 +0000357 return (PyObject *) self;
358}
Raymond Hettinger22c001b2002-08-07 16:18:54 +0000359\end{verbatim}
360
Fred Drakeebcf6a82001-02-01 05:20:20 +0000361The only further addition is that the destructor needs to call the
Fred Drakef66cb5d2001-06-22 17:20:29 +0000362weak reference manager to clear any weak references. This should be
Fred Drake7408da52001-10-26 17:40:22 +0000363done before any other parts of the destruction have occurred, but is
364only required if the weak reference list is non-\NULL:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000365
366\begin{verbatim}
367static void
368instance_dealloc(PyInstanceObject *inst)
369{
Fred Drake7408da52001-10-26 17:40:22 +0000370 /* Allocate temporaries if needed, but do not begin
Fred Drakef66cb5d2001-06-22 17:20:29 +0000371 destruction just yet.
Fred Drakeebcf6a82001-02-01 05:20:20 +0000372 */
373
Fred Drake7408da52001-10-26 17:40:22 +0000374 if (inst->in_weakreflist != NULL)
375 PyObject_ClearWeakRefs((PyObject *) inst);
Fred Drakeebcf6a82001-02-01 05:20:20 +0000376
Fred Drakede3d0602001-10-26 11:27:54 +0000377 /* Proceed with object destruction normally. */
Fred Drakeebcf6a82001-02-01 05:20:20 +0000378}
379\end{verbatim}