rest25/library/weakref.rst => rest262/library/weakref.rst
10.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
11
12
13.. versionadded:: 2.1
14
15The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
16references` to objects.
17
n18-.. % When making changes to the examples in this file, be sure to update
n18+.. When making changes to the examples in this file, be sure to update
19-.. % Lib/test/test_weakref.py::libreftest too!
19+   Lib/test/test_weakref.py::libreftest too!
20
21In the following, the term :dfn:`referent` means the object which is referred to
22by a weak reference.
23
24A weak reference to an object is not enough to keep the object alive: when the
n25-only remaining references to a referent are weak references, garbage collection
n25+only remaining references to a referent are weak references,
26-is free to destroy the referent and reuse its memory for something else.  A
26+:term:`garbage collection` is free to destroy the referent and reuse its memory
27-primary use for weak references is to implement caches or mappings holding large
27+for something else.  A primary use for weak references is to implement caches or
28-objects, where it's desired that a large object not be kept alive solely because
28+mappings holding large objects, where it's desired that a large object not be
29-it appears in a cache or mapping.  For example, if you have a number of large
29+kept alive solely because it appears in a cache or mapping.
30-binary image objects, you may wish to associate a name with each.  If you used a
30+ 
31-Python dictionary to map names to images, or images to names, the image objects
31+For example, if you have a number of large binary image objects, you may wish to
32-would remain alive just because they appeared as values or keys in the
32+associate a name with each.  If you used a Python dictionary to map names to
33+images, or images to names, the image objects would remain alive just because
34+they appeared as values or keys in the dictionaries.  The
33-dictionaries.  The :class:`WeakKeyDictionary` and :class:`WeakValueDictionary`
35+:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
34-classes supplied by the :mod:`weakref` module are an alternative, using weak
36+the :mod:`weakref` module are an alternative, using weak references to construct
35-references to construct mappings that don't keep objects alive solely because
37+mappings that don't keep objects alive solely because they appear in the mapping
36-they appear in the mapping objects.  If, for example, an image object is a value
38+objects.  If, for example, an image object is a value in a
37-in a :class:`WeakValueDictionary`, then when the last remaining references to
39+:class:`WeakValueDictionary`, then when the last remaining references to that
38-that image object are the weak references held by weak mappings, garbage
40+image object are the weak references held by weak mappings, garbage collection
39-collection can reclaim the object, and its corresponding entries in weak
41+can reclaim the object, and its corresponding entries in weak mappings are
40-mappings are simply deleted.
42+simply deleted.
41
42:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
43in their implementation, setting up callback functions on the weak references
44that notify the weak dictionaries when a key or value has been reclaimed by
45garbage collection.  Most programs should find that using one of these weak
46dictionary types is all they need -- it's not usually necessary to create your
47own weak references directly.  The low-level machinery used by the weak
48dictionary implementations is exposed by the :mod:`weakref` module for the
49benefit of advanced uses.
50
n53+.. note::
54+ 
55+   Weak references to an object are cleared before the object's :meth:`__del__`
56+   is called, to ensure that the weak reference callback (if any) finds the
57+   object still alive.
58+ 
51Not all objects can be weakly referenced; those objects which can include class
52instances, functions written in Python (but not in C), methods (both bound and
n53-unbound), sets, frozensets, file objects, generators, type objects, DBcursor
n61+unbound), sets, frozensets, file objects, :term:`generator`\s, type objects,
54-objects from the :mod:`bsddb` module, sockets, arrays, deques, and regular
62+:class:`DBcursor` objects from the :mod:`bsddb` module, sockets, arrays, deques,
55-expression pattern objects.
63+and regular expression pattern objects.
56
57.. versionchanged:: 2.4
58   Added support for files, sockets, arrays, and patterns.
59
60Several builtin types such as :class:`list` and :class:`dict` do not directly
61support weak references but can add support through subclassing::
62
63   class Dict(dict):
64       pass
65
n66-   obj = Dict(red=1, green=2, blue=3)   # this object is weak referencable
n74+   obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable
67
n68-Extension types can easily be made to support weak references; see "Weak
n76+Extension types can easily be made to support weak references; see
69-Reference Support (XXX reference: ../ext/weakref-support.html)" in Extending and
77+:ref:`weakref-support`.
70-Embedding the Python Interpreter (XXX reference: ../ext/ext.html).
71- 
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
78.. class:: ref(object[, callback])
79
80   Return a weak reference to *object*.  The original object can be retrieved by
81   calling the reference object if the referent is still alive; if the referent is
82   no longer alive, calling the reference object will cause :const:`None` to be
83   returned.  If *callback* is provided and not :const:`None`, and the returned
88   It is allowable for many weak references to be constructed for the same object.
89   Callbacks registered for each weak reference will be called from the most
90   recently registered callback to the oldest registered callback.
91
92   Exceptions raised by the callback will be noted on the standard error output,
93   but cannot be propagated; they are handled in exactly the same way as exceptions
94   raised from an object's :meth:`__del__` method.
95
n96-   Weak references are hashable if the *object* is hashable.  They will maintain
n98+   Weak references are :term:`hashable` if the *object* is hashable.  They will maintain
97   their hash value even after the *object* was deleted.  If :func:`hash` is called
98   the first time only after the *object* was deleted, the call will raise
99   :exc:`TypeError`.
100
101   Weak references support tests for equality, but not ordering.  If the referents
102   are still alive, two references have the same equality relationship as their
103   referents (regardless of the *callback*).  If either referent has been deleted,
104   the references are equal only if the reference objects are the same object.
109
110
111.. function:: proxy(object[, callback])
112
113   Return a proxy to *object* which uses a weak reference.  This supports use of
114   the proxy in most contexts instead of requiring the explicit dereferencing used
115   with weak reference objects.  The returned object will have a type of either
116   ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
n117-   callable.  Proxy objects are not hashable regardless of the referent; this
n119+   callable.  Proxy objects are not :term:`hashable` regardless of the referent; this
118   avoids a number of problems related to their fundamentally mutable nature, and
119   prevent their use as dictionary keys.  *callback* is the same as the parameter
120   of the same name to the :func:`ref` function.
121
122
123.. function:: getweakrefcount(object)
124
125   Return the number of weak references and proxies which refer to *object*.
135   Mapping class that references keys weakly.  Entries in the dictionary will be
136   discarded when there is no longer a strong reference to the key.  This can be
137   used to associate additional data with an object owned by other parts of an
138   application without adding attributes to those objects.  This can be especially
139   useful with objects that override attribute accesses.
140
141   .. note::
142
n143-      Caution:  Because a :class:`WeakKeyDictionary` is built on top of a Python
n145+      Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
144      dictionary, it must not change size when iterating over it.  This can be
n145-      difficult to ensure for a :class:`WeakKeyDictionary` because actions performed
n147+      difficult to ensure for a :class:`WeakKeyDictionary` because actions
146-      by the program during iteration may cause items in the dictionary to vanish "by
148+      performed by the program during iteration may cause items in the
147-      magic" (as a side effect of garbage collection).
149+      dictionary to vanish "by magic" (as a side effect of garbage collection).
148
149:class:`WeakKeyDictionary` objects have the following additional methods.  These
150expose the internal references directly.  The references are not guaranteed to
151be "live" at the time they are used, so the result of calling the references
152needs to be checked before being used.  This can be used to avoid creating
153references that will cause the garbage collector to keep the keys around longer
154than needed.
155
156
157.. method:: WeakKeyDictionary.iterkeyrefs()
158
n159-   Return an iterator that yields the weak references to the keys.
n161+   Return an :term:`iterator` that yields the weak references to the keys.
160
161   .. versionadded:: 2.5
162
163
164.. method:: WeakKeyDictionary.keyrefs()
165
166   Return a list of weak references to the keys.
167
183
184:class:`WeakValueDictionary` objects have the following additional methods.
185These method have the same issues as the :meth:`iterkeyrefs` and :meth:`keyrefs`
186methods of :class:`WeakKeyDictionary` objects.
187
188
189.. method:: WeakValueDictionary.itervaluerefs()
190
n191-   Return an iterator that yields the weak references to the values.
n193+   Return an :term:`iterator` that yields the weak references to the values.
192
193   .. versionadded:: 2.5
194
195
196.. method:: WeakValueDictionary.valuerefs()
197
198   Return a list of weak references to the values.
199
236
237
238.. _weakref-objects:
239
240Weak Reference Objects
241----------------------
242
243Weak reference objects have no attributes or methods, but do allow the referent
n244-to be obtained, if it still exists, by calling it::
n246+to be obtained, if it still exists, by calling it:
245
246   >>> import weakref
247   >>> class Object:
248   ...     pass
249   ...
250   >>> o = Object()
251   >>> r = weakref.ref(o)
252   >>> o2 = r()
253   >>> o is o2
254   True
255
256If the referent no longer exists, calling the reference object returns
n257-:const:`None`::
n259+:const:`None`:
258
259   >>> del o, o2
260   >>> print r()
261   None
262
263Testing that a weak reference object is still live should be done using the
264expression ``ref() is not None``.  Normally, application code that needs to use
265a reference object should follow this pattern::
313Example
314-------
315
316This simple example shows how an application can use objects IDs to retrieve
317objects that it has seen before.  The IDs of the objects can then be used in
318other data structures without forcing the objects to remain alive, but the
319objects can still be retrieved by ID if they do.
320
t321-.. % Example contributed by Tim Peters.
t323+.. Example contributed by Tim Peters.
322
323::
324
325   import weakref
326
327   _id2obj_dict = weakref.WeakValueDictionary()
328
329   def remember(obj):
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op