1 \section{\module{weakref
} ---
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
}
14 The
\module{weakref
} module allows the Python programmer to create
15 \dfn{weak references
} to objects.
17 In the following, the term
\dfn{referent
} means the
18 object which is referred to by a weak reference.
20 A weak reference to an object is not enough to keep the object alive:
21 when the only remaining references to a referent are weak references,
22 garbage collection is free to destroy the referent and reuse its memory
23 for something else. A primary use for weak references is to implement
24 caches or mappings holding large objects, where it's desired that a
25 large object not be kept alive solely because it appears in a cache or
26 mapping. For example, if you have a number of large binary image objects,
27 you may wish to associate a name with each. If you used a Python
28 dictionary to map names to images, or images to names, the image objects
29 would remain alive just because they appeared as values or keys in the
30 dictionaries. The
\class{WeakKeyDictionary
} and
31 \class{WeakValueDictionary
} classes supplied by the
\module{weakref
}
32 module are an alternative, using weak references to construct mappings
33 that don't keep objects alive solely because they appear in the mapping
34 objects. If, for example, an image object is a value in a
35 \class{WeakValueDictionary
}, then when the last remaining
36 references to that image object are the weak references held by weak
37 mappings, garbage collection can reclaim the object, and its corresponding
38 entries in weak mappings are simply deleted.
40 \class{WeakKeyDictionary
} and
\class{WeakValueDictionary
} use weak
41 references in their implementation, setting up callback functions on
42 the weak references that notify the weak dictionaries when a key or value
43 has been reclaimed by garbage collection. Most programs should find that
44 using one of these weak dictionary types is all they need -- it's
45 not usually necessary to create your own weak references directly. The
46 low-level machinery used by the weak dictionary implementations is exposed
47 by the
\module{weakref
} module for the benefit of advanced uses.
49 Not all objects can be weakly referenced; those objects which can
50 include class instances, functions written in Python (but not in C),
51 and methods (both bound and unbound). Extension types can easily
52 be made to support weak references; see section
\ref{weakref-extension
},
53 ``Weak References in Extension Types,'' for more information.
56 \begin{funcdesc
}{ref
}{object
\optional{, callback
}}
57 Return a weak reference to
\var{object
}. The original object can be
58 retrieved by calling the reference object if the referent is still
59 alive; if the referent is no longer alive, calling the reference
60 object will cause
\constant{None
} to be returned. If
\var{callback
} is
61 provided and not
\constant{None
},
62 it will be called when the object is about to be
63 finalized; the weak reference object will be passed as the only
64 parameter to the callback; the referent will no longer be available.
66 It is allowable for many weak references to be constructed for the
67 same object. Callbacks registered for each weak reference will be
68 called from the most recently registered callback to the oldest
71 Exceptions raised by the callback will be noted on the standard
72 error output, but cannot be propagated; they are handled in exactly
73 the same way as exceptions raised from an object's
74 \method{__del__()
} method.
76 Weak references are hashable if the
\var{object
} is hashable. They
77 will maintain their hash value even after the
\var{object
} was
78 deleted. If
\function{hash()
} is called the first time only after
79 the
\var{object
} was deleted, the call will raise
80 \exception{TypeError
}.
82 Weak references support tests for equality, but not ordering. If
83 the referents are still alive, two references have the same
84 equality relationship as their referents (regardless of the
85 \var{callback
}). If either referent has been deleted, the
86 references are equal only if the reference objects are the same
90 \begin{funcdesc
}{proxy
}{object
\optional{, callback
}}
91 Return a proxy to
\var{object
} which uses a weak reference. This
92 supports use of the proxy in most contexts instead of requiring the
93 explicit dereferencing used with weak reference objects. The
94 returned object will have a type of either
\code{ProxyType
} or
95 \code{CallableProxyType
}, depending on whether
\var{object
} is
96 callable. Proxy objects are not hashable regardless of the
97 referent; this avoids a number of problems related to their
98 fundamentally mutable nature, and prevent their use as dictionary
99 keys.
\var{callback
} is the same as the parameter of the same name
100 to the
\function{ref()
} function.
103 \begin{funcdesc
}{getweakrefcount
}{object
}
104 Return the number of weak references and proxies which refer to
108 \begin{funcdesc
}{getweakrefs
}{object
}
109 Return a list of all weak reference and proxy objects which refer to
113 \begin{classdesc
}{WeakKeyDictionary
}{\optional{dict
}}
114 Mapping class that references keys weakly. Entries in the
115 dictionary will be discarded when there is no longer a strong
116 reference to the key. This can be used to associate additional data
117 with an object owned by other parts of an application without adding
118 attributes to those objects. This can be especially useful with
119 objects that override attribute accesses.
121 \note{Caution: Because a
\class{WeakKeyDictionary
} is built on top
122 of a Python dictionary, it must not change size when iterating
123 over it. This can be difficult to ensure for a
124 \class{WeakKeyDictionary
} because actions performed by the
125 program during iteration may cause items in the dictionary
126 to vanish "by magic" (as a side effect of garbage collection).
}
129 \begin{classdesc
}{WeakValueDictionary
}{\optional{dict
}}
130 Mapping class that references values weakly. Entries in the
131 dictionary will be discarded when no strong reference to the value
134 \note{Caution: Because a
\class{WeakValueDictionary
} is built on top
135 of a Python dictionary, it must not change size when iterating
136 over it. This can be difficult to ensure for a
137 \class{WeakValueDictionary
} because actions performed by the
138 program during iteration may cause items in the dictionary
139 to vanish "by magic" (as a side effect of garbage collection).
}
142 \begin{datadesc
}{ReferenceType
}
143 The type object for weak references objects.
146 \begin{datadesc
}{ProxyType
}
147 The type object for proxies of objects which are not callable.
150 \begin{datadesc
}{CallableProxyType
}
151 The type object for proxies of callable objects.
154 \begin{datadesc
}{ProxyTypes
}
155 Sequence containing all the type objects for proxies. This can make
156 it simpler to test if an object is a proxy without being dependent
157 on naming both proxy types.
160 \begin{excdesc
}{ReferenceError
}
161 Exception raised when a proxy object is used but the underlying
162 object has been collected. This is the same as the standard
163 \exception{ReferenceError
} exception.
168 \seepep{0205}{Weak References
}{The proposal and rationale for this
169 feature, including links to earlier implementations
170 and information about similar features in other
175 \subsection{Weak Reference Objects
176 \label{weakref-objects
}}
178 Weak reference objects have no attributes or methods, but do allow the
179 referent to be obtained, if it still exists, by calling it:
187 >>> r = weakref.ref(o)
193 If the referent no longer exists, calling the reference object returns
202 Testing that a weak reference object is still live should be done
203 using the expression
\code{\var{ref
}() is not None
}. Normally,
204 application code that needs to use a reference object should follow
208 # r is a weak reference object
211 # referent has been garbage collected
212 print "Object has been allocated; can't frobnicate."
214 print "Object is still live!"
215 o.do_something_useful()
218 Using a separate test for ``liveness'' creates race conditions in
219 threaded applications; another thread can cause a weak reference to
220 become invalidated before the weak reference is called; the
221 idiom shown above is safe in threaded applications as well as
222 single-threaded applications.
225 \subsection{Example
\label{weakref-example
}}
227 This simple example shows how an application can use objects IDs to
228 retrieve objects that it has seen before. The IDs of the objects can
229 then be used in other data structures without forcing the objects to
230 remain alive, but the objects can still be retrieved by ID if they
233 % Example contributed by Tim Peters <tim_one@msn.com>.
237 _id2obj_dict = weakref.WeakValueDictionary()
241 _id2obj_dict
[oid
] = obj
245 return _id2obj_dict
[oid
]
249 \subsection{Weak References in Extension Types
250 \label{weakref-extension
}}
252 One of the goals of the implementation is to allow any type to
253 participate in the weak reference mechanism without incurring the
254 overhead on those objects which do not benefit by weak referencing
257 For an object to be weakly referencable, the extension must include a
258 \ctype{PyObject*
} field in the instance structure for the use of the
259 weak reference mechanism; it must be initialized to
\NULL{} by the
260 object's constructor. It must also set the
\member{tp_weaklistoffset
}
261 field of the corresponding type object to the offset of the field.
262 Also, it needs to add
\constant{Py_TPFLAGS_HAVE_WEAKREFS
} to the
263 tp_flags slot. For example, the instance type is defined with the
269 PyClassObject *in_class; /* The class object */
270 PyObject *in_dict; /* A dictionary */
271 PyObject *in_weakreflist; /* List of weak references */
275 The statically-declared type object for instances is defined this way:
278 PyTypeObject PyInstance_Type =
{
279 PyObject_HEAD_INIT(&PyType_Type)
283 /* Lots of stuff omitted for brevity... */
285 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS /* tp_flags */
289 0, /* tp_richcompare */
290 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
294 The type constructor is responsible for initializing the weak reference
300 /* Other initialization stuff omitted for brevity */
302 self->in_weakreflist = NULL;
304 return (PyObject *) self;
308 The only further addition is that the destructor needs to call the
309 weak reference manager to clear any weak references. This should be
310 done before any other parts of the destruction have occurred, but is
311 only required if the weak reference list is non-
\NULL{}:
315 instance_dealloc(PyInstanceObject *inst)
317 /* Allocate temporaries if needed, but do not begin
318 destruction just yet.
321 if (inst->in_weakreflist != NULL)
322 PyObject_ClearWeakRefs((PyObject *) inst);
324 /* Proceed with object destruction normally. */