Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 1 | \section{\module{weakref} --- |
| 2 | Weak references} |
| 3 | |
| 4 | \declaremodule{extension}{weakref} |
| 5 | \moduleauthor{Fred L. Drake, Jr.}{fdrake@acm.org} |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 6 | \moduleauthor{Neil Schemenauer}{nas@arctrix.com} |
| 7 | \moduleauthor{Martin von L\o"wis}{martin@loewis.home.cs.tu-berlin.de} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 8 | \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org} |
| 9 | |
| 10 | \versionadded{2.1} |
| 11 | |
| 12 | |
| 13 | The \module{weakref} module allows the Python programmer to create |
| 14 | \dfn{weak references} to objects. |
| 15 | |
| 16 | XXX --- need to say more here! |
| 17 | |
| 18 | Not all objects can be weakly referenced; those objects which do |
Fred Drake | 5e0dfac | 2001-03-23 04:36:02 +0000 | [diff] [blame] | 19 | include class instances, functions written in Python (but not in C), |
| 20 | and methods (both bound and unbound). Extension types can easily |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 21 | be made to support weak references; see section \ref{weakref-extension}, |
| 22 | ``Weak References in Extension Types,'' for more information. |
| 23 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 24 | |
| 25 | \begin{funcdesc}{ref}{object\optional{, callback}} |
| 26 | Return a weak reference to \var{object}. If \var{callback} is |
| 27 | provided, it will be called when the object is about to be |
| 28 | finalized; the weak reference object will be passed as the only |
| 29 | parameter to the callback; the referent will no longer be available. |
| 30 | The original object can be retrieved by calling the reference |
| 31 | object, if the referent is still alive. |
| 32 | |
| 33 | It is allowable for many weak references to be constructed for the |
| 34 | same object. Callbacks registered for each weak reference will be |
| 35 | called from the most recently registered callback to the oldest |
| 36 | registered callback. |
| 37 | |
| 38 | Exceptions raised by the callback will be noted on the standard |
Andrew M. Kuchling | e7d7e6c | 2001-02-14 02:39:11 +0000 | [diff] [blame] | 39 | error output, but cannot be propagated; they are handled in exactly |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 40 | the same way as exceptions raised from an object's |
| 41 | \method{__del__()} method. |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 42 | |
| 43 | Weak references are hashable if the \var{object} is hashable. They |
| 44 | will maintain their hash value even after the \var{object} was |
| 45 | deleted. If \function{hash()} is called the first time only after |
| 46 | the \var{object} was deleted, the call will raise |
| 47 | \exception{TypeError}. |
| 48 | |
| 49 | Weak references support test for equality, but not ordering. If the |
| 50 | \var{object} is still alive, to references are equal if the objects |
| 51 | are equal (regardless of the \var{callback}). If the \var{object} |
| 52 | has been deleted, they are equal iff they are identical. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 53 | \end{funcdesc} |
| 54 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 55 | \begin{funcdesc}{proxy}{object\optional{, callback}} |
| 56 | Return a proxy to \var{object} which uses a weak reference. This |
| 57 | supports use of the proxy in most contexts instead of requiring the |
| 58 | explicit dereferencing used with weak reference objects. The |
| 59 | returned object will have a type of either \code{ProxyType} or |
| 60 | \code{CallableProxyType}, depending on whether \var{object} is |
| 61 | callable. Proxy objects are not hashable regardless of the |
| 62 | referent; this avoids a number of problems related to their |
| 63 | fundamentally mutable nature, and prevent their use as dictionary |
| 64 | keys. \var{callable} is the same as the parameter of the same name |
| 65 | to the \function{ref()} function. |
| 66 | \end{funcdesc} |
| 67 | |
| 68 | \begin{funcdesc}{getweakrefcount}{object} |
| 69 | Return the number of weak references and proxies which refer to |
| 70 | \var{object}. |
| 71 | \end{funcdesc} |
| 72 | |
| 73 | \begin{funcdesc}{getweakrefs}{object} |
| 74 | Return a list of all weak reference and proxy objects which refer to |
| 75 | \var{object}. |
| 76 | \end{funcdesc} |
| 77 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 78 | \begin{classdesc}{WeakKeyDictionary}{\optional{dict}} |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 79 | Mapping class that references keys weakly. Entries in the |
| 80 | dictionary will be discarded when there is no longer a strong |
| 81 | reference to the key. This can be used to associate additional data |
| 82 | with an object owned by other parts of an application without adding |
| 83 | attributes to those objects. This can be especially useful with |
| 84 | objects that override attribute accesses. |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 85 | \end{classdesc} |
| 86 | |
| 87 | \begin{classdesc}{WeakValueDictionary}{\optional{dict}} |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 88 | Mapping class that references values weakly. Entries in the |
| 89 | dictionary will be discarded when no strong reference to the value |
| 90 | exists anymore. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 91 | \end{classdesc} |
| 92 | |
| 93 | \begin{datadesc}{ReferenceType} |
| 94 | The type object for weak references objects. |
| 95 | \end{datadesc} |
| 96 | |
| 97 | \begin{datadesc}{ProxyType} |
| 98 | The type object for proxies of objects which are not callable. |
| 99 | \end{datadesc} |
| 100 | |
| 101 | \begin{datadesc}{CallableProxyType} |
| 102 | The type object for proxies of callable objects. |
| 103 | \end{datadesc} |
| 104 | |
| 105 | \begin{datadesc}{ProxyTypes} |
| 106 | Sequence containing all the type objects for proxies. This can make |
| 107 | it simpler to test if an object is a proxy without being dependent |
| 108 | on naming both proxy types. |
| 109 | \end{datadesc} |
| 110 | |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 111 | \begin{excdesc}{ReferenceError} |
| 112 | Exception raised when a proxy object is used but the underlying |
| 113 | object has been collected. |
| 114 | \end{excdesc} |
| 115 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 116 | |
| 117 | \begin{seealso} |
| 118 | \seepep{0205}{Weak References}{The proposal and rationale for this |
| 119 | feature, including links to earlier implementations |
| 120 | and information about similar features in other |
| 121 | languages.} |
| 122 | \end{seealso} |
| 123 | |
| 124 | |
| 125 | \subsection{Weak Reference Objects |
| 126 | \label{weakref-objects}} |
| 127 | |
| 128 | Weak reference objects have no attributes or methods, but do allow the |
| 129 | referent to be obtained, if it still exists, by calling it: |
| 130 | |
| 131 | \begin{verbatim} |
| 132 | >>> import weakref |
| 133 | >>> class Object: |
| 134 | ... pass |
| 135 | ... |
| 136 | >>> o = Object() |
| 137 | >>> r = weakref.ref(o) |
| 138 | >>> o2 = r() |
| 139 | >>> o is o2 |
| 140 | 1 |
| 141 | \end{verbatim} |
| 142 | |
| 143 | If the referent no longer exists, calling the reference object returns |
| 144 | \code{None}: |
| 145 | |
| 146 | \begin{verbatim} |
| 147 | >>> del o, o2 |
| 148 | >>> print r() |
| 149 | None |
| 150 | \end{verbatim} |
| 151 | |
| 152 | Testing that a weak reference object is still live should be done |
| 153 | using the expression \code{\var{ref}.get() is not None}. Normally, |
| 154 | application code that needs to use a reference object should follow |
| 155 | this pattern: |
| 156 | |
| 157 | \begin{verbatim} |
| 158 | o = ref.get() |
| 159 | if o is None: |
| 160 | # referent has been garbage collected |
| 161 | print "Object has been allocated; can't frobnicate." |
| 162 | else: |
| 163 | print "Object is still live!" |
| 164 | o.do_something_useful() |
| 165 | \end{verbatim} |
| 166 | |
| 167 | Using a separate test for ``liveness'' creates race conditions in |
| 168 | threaded applications; another thread can cause a weak reference to |
| 169 | become invalidated before the \method{get()} method is called; the |
| 170 | idiom shown above is safe in threaded applications as well as |
| 171 | single-threaded applications. |
| 172 | |
| 173 | |
Fred Drake | cb83988 | 2001-03-28 21:15:41 +0000 | [diff] [blame] | 174 | \subsection{Example \label{weakref-example}} |
| 175 | |
| 176 | This simple example shows how an application can use objects IDs to |
| 177 | retrieve objects that it has seen before. The IDs of the objects can |
| 178 | then be used in other data structures without forcing the objects to |
| 179 | remain alive, but the objects can still be retrieved by ID if they |
| 180 | do. |
| 181 | |
| 182 | % Example contributed by Tim Peters <tim_one@msn.com>. |
| 183 | \begin{verbatim} |
| 184 | import weakref |
| 185 | |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 186 | _id2obj_dict = weakref.WeakValueDictionary() |
Fred Drake | cb83988 | 2001-03-28 21:15:41 +0000 | [diff] [blame] | 187 | |
| 188 | def remember(obj): |
| 189 | _id2obj_dict[id(obj)] = obj |
| 190 | |
| 191 | def id2obj(id): |
| 192 | return _id2obj_dict.get(id) |
| 193 | \end{verbatim} |
| 194 | |
| 195 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 196 | \subsection{Weak References in Extension Types |
| 197 | \label{weakref-extension}} |
| 198 | |
| 199 | One of the goals of the implementation is to allow any type to |
| 200 | participate in the weak reference mechanism without incurring the |
| 201 | overhead on those objects which do not benefit by weak referencing |
| 202 | (such as numbers). |
| 203 | |
| 204 | For an object to be weakly referencable, the extension must include a |
| 205 | \ctype{PyObject *} field in the instance structure for the use of the |
Fred Drake | 5e0dfac | 2001-03-23 04:36:02 +0000 | [diff] [blame] | 206 | weak reference mechanism; it must be initialized to \NULL{} by the |
| 207 | object's constructor. It must also set the \member{tp_weaklistoffset} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 208 | field of the corresponding type object to the offset of the field. |
| 209 | For example, the instance type is defined with the following structure: |
| 210 | |
| 211 | \begin{verbatim} |
| 212 | typedef struct { |
| 213 | PyObject_HEAD |
| 214 | PyClassObject *in_class; /* The class object */ |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 215 | PyObject *in_dict; /* A dictionary */ |
| 216 | PyObject *in_weakreflist; /* List of weak references */ |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 217 | } PyInstanceObject; |
| 218 | \end{verbatim} |
| 219 | |
| 220 | The statically-declared type object for instances is defined this way: |
| 221 | |
| 222 | \begin{verbatim} |
| 223 | PyTypeObject PyInstance_Type = { |
| 224 | PyObject_HEAD_INIT(&PyType_Type) |
| 225 | 0, |
| 226 | "instance", |
| 227 | |
| 228 | /* lots of stuff omitted for brevity */ |
| 229 | |
| 230 | offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */ |
| 231 | }; |
| 232 | \end{verbatim} |
| 233 | |
| 234 | The only further addition is that the destructor needs to call the |
| 235 | weak reference manager to clear any weak references and return if the |
| 236 | object has been resurrected. This needs to occur before any other |
| 237 | parts of the destruction have occurred: |
| 238 | |
| 239 | \begin{verbatim} |
| 240 | static void |
| 241 | instance_dealloc(PyInstanceObject *inst) |
| 242 | { |
| 243 | /* allocate tempories if needed, but do not begin |
| 244 | destruction here |
| 245 | */ |
| 246 | |
| 247 | if (!PyObject_ClearWeakRefs((PyObject *) inst)) |
| 248 | return; |
| 249 | |
| 250 | /* proceed with object destuction normally */ |
| 251 | } |
| 252 | \end{verbatim} |