source: vendor/python/2.5/Doc/lib/libweakref.tex

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

File size: 12.9 KB
Line 
1\section{\module{weakref} ---
2 Weak references}
3
4\declaremodule{extension}{weakref}
5\modulesynopsis{Support for weak references and weak dictionaries.}
6\moduleauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
7\moduleauthor{Neil Schemenauer}{nas@arctrix.com}
8\moduleauthor{Martin von L\"owis}{martin@loewis.home.cs.tu-berlin.de}
9\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
10
11\versionadded{2.1}
12
13% When making changes to the examples in this file, be sure to update
14% Lib/test/test_weakref.py::libreftest too!
15
16The \module{weakref} module allows the Python programmer to create
17\dfn{weak references} to objects.
18
19In the following, the term \dfn{referent} means the
20object which is referred to by a weak reference.
21
22A 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.
50
51Not all objects can be weakly referenced; those objects which can
52include class instances, functions written in Python (but not in C),
53methods (both bound and unbound), sets, frozensets, file objects,
54generators, type objects, DBcursor objects from the \module{bsddb} module,
55sockets, 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
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.
76
77\begin{classdesc}{ref}{object\optional{, callback}}
78 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
81 object will cause \constant{None} to be returned. If \var{callback} is
82 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
84 finalized; the weak reference object will be passed as the only
85 parameter to the callback; the referent will no longer be available.
86
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
93 error output, but cannot be propagated; they are handled in exactly
94 the same way as exceptions raised from an object's
95 \method{__del__()} method.
96
97 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}.
102
103 Weak references support tests for equality, but not ordering. If
104 the referents are still alive, two references have the same
105 equality relationship as their referents (regardless of the
106 \var{callback}). If either referent has been deleted, the
107 references are equal only if the reference objects are the same
108 object.
109
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}
114
115\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
124 keys. \var{callback} is the same as the parameter of the same name
125 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
138\begin{classdesc}{WeakKeyDictionary}{\optional{dict}}
139 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.
145
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).}
152\end{classdesc}
153
154\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
172\begin{classdesc}{WeakValueDictionary}{\optional{dict}}
173 Mapping class that references values weakly. Entries in the
174 dictionary will be discarded when no strong reference to the value
175 exists any more.
176
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).}
183\end{classdesc}
184
185\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
200\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
218\begin{excdesc}{ReferenceError}
219 Exception raised when a proxy object is used but the underlying
220 object has been collected. This is the same as the standard
221 \exception{ReferenceError} exception.
222\end{excdesc}
223
224
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
248True
249\end{verbatim}
250
251If the referent no longer exists, calling the reference object returns
252\constant{None}:
253
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
261using the expression \code{\var{ref}() is not None}. Normally,
262application code that needs to use a reference object should follow
263this pattern:
264
265\begin{verbatim}
266# r is a weak reference object
267o = r()
268if o is None:
269 # referent has been garbage collected
270 print "Object has been deallocated; can't frobnicate."
271else:
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
278become invalidated before the weak reference is called; the
279idiom shown above is safe in threaded applications as well as
280single-threaded applications.
281
282Specialized 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):
297 def __init__(self, ob, callback=None, **annotations):
298 super(ExtendedRef, self).__init__(ob, callback)
299 self.__counter = 0
300 for k, v in annotations.iteritems():
301 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 """
307 ob = super(ExtendedRef, self).__call__()
308 if ob is not None:
309 self.__counter += 1
310 ob = (ob, self.__counter)
311 return ob
312\end{verbatim}
313
314
315\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
323% Example contributed by Tim Peters.
324\begin{verbatim}
325import weakref
326
327_id2obj_dict = weakref.WeakValueDictionary()
328
329def remember(obj):
330 oid = id(obj)
331 _id2obj_dict[oid] = obj
332 return oid
333
334def id2obj(oid):
335 return _id2obj_dict[oid]
336\end{verbatim}
Note: See TracBrowser for help on using the repository browser.