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 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 55 | \begin{funcdesc}{mapping}{\optional{dict\optional{, weakkeys=0}}} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 56 | Return a weak dictionary. If \var{dict} is given and not |
| 57 | \code{None}, the new dictionary will contain the items contained in |
| 58 | \var{dict}. The values from \var{dict} must be weakly referencable; |
| 59 | if any values which would be inserted into the new mapping are not |
| 60 | weakly referencable, \exception{TypeError} will be raised and the |
| 61 | new mapping will be empty. |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 62 | |
| 63 | If the \var{weakkeys} argument is not given or zero, the values in |
| 64 | the dictionary are weak. That means the entries in the dictionary |
| 65 | will be discarded when no strong reference to the value exists |
| 66 | anymore. |
| 67 | |
| 68 | If the \var{weakkeys} argument is nonzero, the keys in the |
| 69 | dictionary are weak, i.e. the entry in the dictionary is discarded |
| 70 | when the last strong reference to the key is discarded. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 71 | \end{funcdesc} |
| 72 | |
| 73 | \begin{funcdesc}{proxy}{object\optional{, callback}} |
| 74 | Return a proxy to \var{object} which uses a weak reference. This |
| 75 | supports use of the proxy in most contexts instead of requiring the |
| 76 | explicit dereferencing used with weak reference objects. The |
| 77 | returned object will have a type of either \code{ProxyType} or |
| 78 | \code{CallableProxyType}, depending on whether \var{object} is |
| 79 | callable. Proxy objects are not hashable regardless of the |
| 80 | referent; this avoids a number of problems related to their |
| 81 | fundamentally mutable nature, and prevent their use as dictionary |
| 82 | keys. \var{callable} is the same as the parameter of the same name |
| 83 | to the \function{ref()} function. |
| 84 | \end{funcdesc} |
| 85 | |
| 86 | \begin{funcdesc}{getweakrefcount}{object} |
| 87 | Return the number of weak references and proxies which refer to |
| 88 | \var{object}. |
| 89 | \end{funcdesc} |
| 90 | |
| 91 | \begin{funcdesc}{getweakrefs}{object} |
| 92 | Return a list of all weak reference and proxy objects which refer to |
| 93 | \var{object}. |
| 94 | \end{funcdesc} |
| 95 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 96 | \begin{classdesc}{WeakKeyDictionary}{\optional{dict}} |
| 97 | The class of the mapping objects returned by \function{mapping()} |
| 98 | when \var{weakkeys} is true. This can be used for subclassing the |
| 99 | implementation if needed. |
| 100 | \end{classdesc} |
| 101 | |
| 102 | \begin{classdesc}{WeakValueDictionary}{\optional{dict}} |
| 103 | The class of the mapping objects returned by \function{mapping()} |
| 104 | when \var{weakkeys} if false. This can be used for subclassing the |
| 105 | implementation if needed. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 106 | \end{classdesc} |
| 107 | |
| 108 | \begin{datadesc}{ReferenceType} |
| 109 | The type object for weak references objects. |
| 110 | \end{datadesc} |
| 111 | |
| 112 | \begin{datadesc}{ProxyType} |
| 113 | The type object for proxies of objects which are not callable. |
| 114 | \end{datadesc} |
| 115 | |
| 116 | \begin{datadesc}{CallableProxyType} |
| 117 | The type object for proxies of callable objects. |
| 118 | \end{datadesc} |
| 119 | |
| 120 | \begin{datadesc}{ProxyTypes} |
| 121 | Sequence containing all the type objects for proxies. This can make |
| 122 | it simpler to test if an object is a proxy without being dependent |
| 123 | on naming both proxy types. |
| 124 | \end{datadesc} |
| 125 | |
| 126 | |
| 127 | \begin{seealso} |
| 128 | \seepep{0205}{Weak References}{The proposal and rationale for this |
| 129 | feature, including links to earlier implementations |
| 130 | and information about similar features in other |
| 131 | languages.} |
| 132 | \end{seealso} |
| 133 | |
| 134 | |
| 135 | \subsection{Weak Reference Objects |
| 136 | \label{weakref-objects}} |
| 137 | |
| 138 | Weak reference objects have no attributes or methods, but do allow the |
| 139 | referent to be obtained, if it still exists, by calling it: |
| 140 | |
| 141 | \begin{verbatim} |
| 142 | >>> import weakref |
| 143 | >>> class Object: |
| 144 | ... pass |
| 145 | ... |
| 146 | >>> o = Object() |
| 147 | >>> r = weakref.ref(o) |
| 148 | >>> o2 = r() |
| 149 | >>> o is o2 |
| 150 | 1 |
| 151 | \end{verbatim} |
| 152 | |
| 153 | If the referent no longer exists, calling the reference object returns |
| 154 | \code{None}: |
| 155 | |
| 156 | \begin{verbatim} |
| 157 | >>> del o, o2 |
| 158 | >>> print r() |
| 159 | None |
| 160 | \end{verbatim} |
| 161 | |
| 162 | Testing that a weak reference object is still live should be done |
| 163 | using the expression \code{\var{ref}.get() is not None}. Normally, |
| 164 | application code that needs to use a reference object should follow |
| 165 | this pattern: |
| 166 | |
| 167 | \begin{verbatim} |
| 168 | o = ref.get() |
| 169 | if o is None: |
| 170 | # referent has been garbage collected |
| 171 | print "Object has been allocated; can't frobnicate." |
| 172 | else: |
| 173 | print "Object is still live!" |
| 174 | o.do_something_useful() |
| 175 | \end{verbatim} |
| 176 | |
| 177 | Using a separate test for ``liveness'' creates race conditions in |
| 178 | threaded applications; another thread can cause a weak reference to |
| 179 | become invalidated before the \method{get()} method is called; the |
| 180 | idiom shown above is safe in threaded applications as well as |
| 181 | single-threaded applications. |
| 182 | |
| 183 | |
| 184 | \subsection{Weak References in Extension Types |
| 185 | \label{weakref-extension}} |
| 186 | |
| 187 | One of the goals of the implementation is to allow any type to |
| 188 | participate in the weak reference mechanism without incurring the |
| 189 | overhead on those objects which do not benefit by weak referencing |
| 190 | (such as numbers). |
| 191 | |
| 192 | For an object to be weakly referencable, the extension must include a |
| 193 | \ctype{PyObject *} field in the instance structure for the use of the |
Fred Drake | 5e0dfac | 2001-03-23 04:36:02 +0000 | [diff] [blame^] | 194 | weak reference mechanism; it must be initialized to \NULL{} by the |
| 195 | object's constructor. It must also set the \member{tp_weaklistoffset} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 196 | field of the corresponding type object to the offset of the field. |
| 197 | For example, the instance type is defined with the following structure: |
| 198 | |
| 199 | \begin{verbatim} |
| 200 | typedef struct { |
| 201 | PyObject_HEAD |
| 202 | PyClassObject *in_class; /* The class object */ |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 203 | PyObject *in_dict; /* A dictionary */ |
| 204 | PyObject *in_weakreflist; /* List of weak references */ |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 205 | } PyInstanceObject; |
| 206 | \end{verbatim} |
| 207 | |
| 208 | The statically-declared type object for instances is defined this way: |
| 209 | |
| 210 | \begin{verbatim} |
| 211 | PyTypeObject PyInstance_Type = { |
| 212 | PyObject_HEAD_INIT(&PyType_Type) |
| 213 | 0, |
| 214 | "instance", |
| 215 | |
| 216 | /* lots of stuff omitted for brevity */ |
| 217 | |
| 218 | offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */ |
| 219 | }; |
| 220 | \end{verbatim} |
| 221 | |
| 222 | The only further addition is that the destructor needs to call the |
| 223 | weak reference manager to clear any weak references and return if the |
| 224 | object has been resurrected. This needs to occur before any other |
| 225 | parts of the destruction have occurred: |
| 226 | |
| 227 | \begin{verbatim} |
| 228 | static void |
| 229 | instance_dealloc(PyInstanceObject *inst) |
| 230 | { |
| 231 | /* allocate tempories if needed, but do not begin |
| 232 | destruction here |
| 233 | */ |
| 234 | |
| 235 | if (!PyObject_ClearWeakRefs((PyObject *) inst)) |
| 236 | return; |
| 237 | |
| 238 | /* proceed with object destuction normally */ |
| 239 | } |
| 240 | \end{verbatim} |