blob: 6f676a28770d88a17a7cab1634f689ee482c1204 [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
Fred Drake45540b02006-07-29 20:04:42 +000068Extension types can easily be made to support weak references; see
69``\ulink{Weak Reference Support}{../ext/weakref-support.html}'' in
70\citetitle[../ext/ext.html]{Extending and Embedding the Python
71Interpreter}.
72% The referenced section used to appear in this document with the
73% \label weakref-extension. It would be good to be able to generate a
74% redirect for the corresponding HTML page (weakref-extension.html)
75% for on-line versions of this document.
Fred Drakeebcf6a82001-02-01 05:20:20 +000076
Fred Drake0a4dd392004-07-02 18:57:45 +000077\begin{classdesc}{ref}{object\optional{, callback}}
Fred Drake7408da52001-10-26 17:40:22 +000078 Return a weak reference to \var{object}. The original object can be
79 retrieved by calling the reference object if the referent is still
80 alive; if the referent is no longer alive, calling the reference
Fred Drake21ae4f92004-02-03 20:55:15 +000081 object will cause \constant{None} to be returned. If \var{callback} is
Armin Rigob9359c42005-12-29 17:43:08 +000082 provided and not \constant{None}, and the returned weakref object is
83 still alive, the callback will be called when the object is about to be
Fred Drakeebcf6a82001-02-01 05:20:20 +000084 finalized; the weak reference object will be passed as the only
85 parameter to the callback; the referent will no longer be available.
Fred Drakeebcf6a82001-02-01 05:20:20 +000086
87 It is allowable for many weak references to be constructed for the
88 same object. Callbacks registered for each weak reference will be
89 called from the most recently registered callback to the oldest
90 registered callback.
91
92 Exceptions raised by the callback will be noted on the standard
Andrew M. Kuchlinge7d7e6c2001-02-14 02:39:11 +000093 error output, but cannot be propagated; they are handled in exactly
Fred Drakeebcf6a82001-02-01 05:20:20 +000094 the same way as exceptions raised from an object's
95 \method{__del__()} method.
Tim Peters5a5b2432003-11-21 22:20:57 +000096
Martin v. Löwis5e163332001-02-27 18:36:56 +000097 Weak references are hashable if the \var{object} is hashable. They
98 will maintain their hash value even after the \var{object} was
99 deleted. If \function{hash()} is called the first time only after
100 the \var{object} was deleted, the call will raise
101 \exception{TypeError}.
Tim Peters5a5b2432003-11-21 22:20:57 +0000102
Fred Drake3a2c4622001-10-26 03:00:39 +0000103 Weak references support tests for equality, but not ordering. If
Fred Drake7408da52001-10-26 17:40:22 +0000104 the referents are still alive, two references have the same
Fred Drakeb03d0cc2001-11-26 21:39:40 +0000105 equality relationship as their referents (regardless of the
Fred Drake7408da52001-10-26 17:40:22 +0000106 \var{callback}). If either referent has been deleted, the
107 references are equal only if the reference objects are the same
108 object.
Fred Drake0a4dd392004-07-02 18:57:45 +0000109
110 \versionchanged[This is now a subclassable type rather than a
111 factory function; it derives from \class{object}]
112 {2.4}
113\end{classdesc}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000114
Fred Drakeebcf6a82001-02-01 05:20:20 +0000115\begin{funcdesc}{proxy}{object\optional{, callback}}
116 Return a proxy to \var{object} which uses a weak reference. This
117 supports use of the proxy in most contexts instead of requiring the
118 explicit dereferencing used with weak reference objects. The
119 returned object will have a type of either \code{ProxyType} or
120 \code{CallableProxyType}, depending on whether \var{object} is
121 callable. Proxy objects are not hashable regardless of the
122 referent; this avoids a number of problems related to their
123 fundamentally mutable nature, and prevent their use as dictionary
Fred Drakee7ec1ef2001-05-10 17:22:17 +0000124 keys. \var{callback} is the same as the parameter of the same name
Fred Drakeebcf6a82001-02-01 05:20:20 +0000125 to the \function{ref()} function.
126\end{funcdesc}
127
128\begin{funcdesc}{getweakrefcount}{object}
129 Return the number of weak references and proxies which refer to
130 \var{object}.
131\end{funcdesc}
132
133\begin{funcdesc}{getweakrefs}{object}
134 Return a list of all weak reference and proxy objects which refer to
135 \var{object}.
136\end{funcdesc}
137
Martin v. Löwis5e163332001-02-27 18:36:56 +0000138\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000139 Mapping class that references keys weakly. Entries in the
140 dictionary will be discarded when there is no longer a strong
141 reference to the key. This can be used to associate additional data
142 with an object owned by other parts of an application without adding
143 attributes to those objects. This can be especially useful with
144 objects that override attribute accesses.
Tim Peters5a5b2432003-11-21 22:20:57 +0000145
146 \note{Caution: Because a \class{WeakKeyDictionary} is built on top
147 of a Python dictionary, it must not change size when iterating
148 over it. This can be difficult to ensure for a
149 \class{WeakKeyDictionary} because actions performed by the
150 program during iteration may cause items in the dictionary
151 to vanish "by magic" (as a side effect of garbage collection).}
Martin v. Löwis5e163332001-02-27 18:36:56 +0000152\end{classdesc}
153
Fred Drake017e68c2006-05-02 06:53:59 +0000154\class{WeakKeyDictionary} objects have the following additional
155methods. These expose the internal references directly. The
156references are not guaranteed to be ``live'' at the time they are
157used, so the result of calling the references needs to be checked
158before being used. This can be used to avoid creating references that
159will cause the garbage collector to keep the keys around longer than
160needed.
161
162\begin{methoddesc}{iterkeyrefs}{}
163 Return an iterator that yields the weak references to the keys.
164 \versionadded{2.5}
165\end{methoddesc}
166
167\begin{methoddesc}{keyrefs}{}
168 Return a list of weak references to the keys.
169 \versionadded{2.5}
170\end{methoddesc}
171
Martin v. Löwis5e163332001-02-27 18:36:56 +0000172\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
Fred Drakeac154a12001-04-10 19:57:58 +0000173 Mapping class that references values weakly. Entries in the
174 dictionary will be discarded when no strong reference to the value
Fred Drake7408da52001-10-26 17:40:22 +0000175 exists any more.
Tim Peters5a5b2432003-11-21 22:20:57 +0000176
177 \note{Caution: Because a \class{WeakValueDictionary} is built on top
178 of a Python dictionary, it must not change size when iterating
179 over it. This can be difficult to ensure for a
180 \class{WeakValueDictionary} because actions performed by the
181 program during iteration may cause items in the dictionary
182 to vanish "by magic" (as a side effect of garbage collection).}
Fred Drakeebcf6a82001-02-01 05:20:20 +0000183\end{classdesc}
184
Fred Drake017e68c2006-05-02 06:53:59 +0000185\class{WeakValueDictionary} objects have the following additional
186methods. These method have the same issues as the
187\method{iterkeyrefs()} and \method{keyrefs()} methods of
188\class{WeakKeyDictionary} objects.
189
190\begin{methoddesc}{itervaluerefs}{}
191 Return an iterator that yields the weak references to the values.
192 \versionadded{2.5}
193\end{methoddesc}
194
195\begin{methoddesc}{valuerefs}{}
196 Return a list of weak references to the values.
197 \versionadded{2.5}
198\end{methoddesc}
199
Fred Drakeebcf6a82001-02-01 05:20:20 +0000200\begin{datadesc}{ReferenceType}
201 The type object for weak references objects.
202\end{datadesc}
203
204\begin{datadesc}{ProxyType}
205 The type object for proxies of objects which are not callable.
206\end{datadesc}
207
208\begin{datadesc}{CallableProxyType}
209 The type object for proxies of callable objects.
210\end{datadesc}
211
212\begin{datadesc}{ProxyTypes}
213 Sequence containing all the type objects for proxies. This can make
214 it simpler to test if an object is a proxy without being dependent
215 on naming both proxy types.
216\end{datadesc}
217
Fred Drakeac154a12001-04-10 19:57:58 +0000218\begin{excdesc}{ReferenceError}
219 Exception raised when a proxy object is used but the underlying
Fred Drake8c2c3d32001-10-06 06:10:54 +0000220 object has been collected. This is the same as the standard
221 \exception{ReferenceError} exception.
Fred Drakeac154a12001-04-10 19:57:58 +0000222\end{excdesc}
223
Fred Drakeebcf6a82001-02-01 05:20:20 +0000224
225\begin{seealso}
226 \seepep{0205}{Weak References}{The proposal and rationale for this
227 feature, including links to earlier implementations
228 and information about similar features in other
229 languages.}
230\end{seealso}
231
232
233\subsection{Weak Reference Objects
234 \label{weakref-objects}}
235
236Weak reference objects have no attributes or methods, but do allow the
237referent to be obtained, if it still exists, by calling it:
238
239\begin{verbatim}
240>>> import weakref
241>>> class Object:
242... pass
243...
244>>> o = Object()
245>>> r = weakref.ref(o)
246>>> o2 = r()
247>>> o is o2
Martin v. Löwisccabed32003-11-27 19:48:03 +0000248True
Fred Drakeebcf6a82001-02-01 05:20:20 +0000249\end{verbatim}
250
251If the referent no longer exists, calling the reference object returns
Fred Drake21ae4f92004-02-03 20:55:15 +0000252\constant{None}:
Fred Drakeebcf6a82001-02-01 05:20:20 +0000253
254\begin{verbatim}
255>>> del o, o2
256>>> print r()
257None
258\end{verbatim}
259
260Testing that a weak reference object is still live should be done
Fred Drake5d548792001-08-03 03:50:28 +0000261using the expression \code{\var{ref}() is not None}. Normally,
Fred Drakeebcf6a82001-02-01 05:20:20 +0000262application code that needs to use a reference object should follow
263this pattern:
264
265\begin{verbatim}
Fred Drake7408da52001-10-26 17:40:22 +0000266# r is a weak reference object
267o = r()
Fred Drakeebcf6a82001-02-01 05:20:20 +0000268if o is None:
269 # referent has been garbage collected
Georg Brandl9a65d582005-07-02 19:07:30 +0000270 print "Object has been deallocated; can't frobnicate."
Fred Drakeebcf6a82001-02-01 05:20:20 +0000271else:
272 print "Object is still live!"
273 o.do_something_useful()
274\end{verbatim}
275
276Using a separate test for ``liveness'' creates race conditions in
277threaded applications; another thread can cause a weak reference to
Fred Drake7408da52001-10-26 17:40:22 +0000278become invalidated before the weak reference is called; the
Fred Drakeebcf6a82001-02-01 05:20:20 +0000279idiom shown above is safe in threaded applications as well as
280single-threaded applications.
281
Fred Drake0a4dd392004-07-02 18:57:45 +0000282Specialized versions of \class{ref} objects can be created through
283subclassing. This is used in the implementation of the
284\class{WeakValueDictionary} to reduce the memory overhead for each
285entry in the mapping. This may be most useful to associate additional
286information with a reference, but could also be used to insert
287additional processing on calls to retrieve the referent.
288
289This example shows how a subclass of \class{ref} can be used to store
290additional information about an object and affect the value that's
291returned when the referent is accessed:
292
293\begin{verbatim}
294import weakref
295
296class ExtendedRef(weakref.ref):
Fred Drake0a4dd392004-07-02 18:57:45 +0000297 def __init__(self, ob, callback=None, **annotations):
298 super(ExtendedRef, self).__init__(ob, callback)
Georg Brandl376e6222005-07-02 10:44:32 +0000299 self.__counter = 0
300 for k, v in annotations.iteritems():
Fred Drake0a4dd392004-07-02 18:57:45 +0000301 setattr(self, k, v)
302
303 def __call__(self):
304 """Return a pair containing the referent and the number of
305 times the reference has been called.
306 """
Georg Brandl9a65d582005-07-02 19:07:30 +0000307 ob = super(ExtendedRef, self).__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000308 if ob is not None:
309 self.__counter += 1
310 ob = (ob, self.__counter)
311 return ob
312\end{verbatim}
313
Fred Drakeebcf6a82001-02-01 05:20:20 +0000314
Fred Drakecb839882001-03-28 21:15:41 +0000315\subsection{Example \label{weakref-example}}
316
317This simple example shows how an application can use objects IDs to
318retrieve objects that it has seen before. The IDs of the objects can
319then be used in other data structures without forcing the objects to
320remain alive, but the objects can still be retrieved by ID if they
321do.
322
Fred Drake42713102003-12-30 16:15:35 +0000323% Example contributed by Tim Peters.
Fred Drakecb839882001-03-28 21:15:41 +0000324\begin{verbatim}
325import weakref
326
Fred Drakeac154a12001-04-10 19:57:58 +0000327_id2obj_dict = weakref.WeakValueDictionary()
Fred Drakecb839882001-03-28 21:15:41 +0000328
329def remember(obj):
Fred Drake7408da52001-10-26 17:40:22 +0000330 oid = id(obj)
331 _id2obj_dict[oid] = obj
332 return oid
Fred Drakecb839882001-03-28 21:15:41 +0000333
Fred Drake7408da52001-10-26 17:40:22 +0000334def id2obj(oid):
335 return _id2obj_dict[oid]
Fred Drakecb839882001-03-28 21:15:41 +0000336\end{verbatim}