Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 1 | \section{\module{weakref} --- |
| 2 | Weak references} |
| 3 | |
| 4 | \declaremodule{extension}{weakref} |
Fred Drake | eedf985 | 2001-04-11 19:17:11 +0000 | [diff] [blame] | 5 | \modulesynopsis{Support for weak references and weak dictionaries.} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 6 | \moduleauthor{Fred L. Drake, Jr.}{fdrake@acm.org} |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 7 | \moduleauthor{Neil Schemenauer}{nas@arctrix.com} |
Fred Drake | 0c20904 | 2001-06-29 16:25:07 +0000 | [diff] [blame] | 8 | \moduleauthor{Martin von L\"owis}{martin@loewis.home.cs.tu-berlin.de} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 9 | \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org} |
| 10 | |
| 11 | \versionadded{2.1} |
| 12 | |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 13 | % When making changes to the examples in this file, be sure to update |
| 14 | % Lib/test/test_weakref.py::libreftest too! |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 15 | |
| 16 | The \module{weakref} module allows the Python programmer to create |
| 17 | \dfn{weak references} to objects. |
| 18 | |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 19 | In the following, the term \dfn{referent} means the |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 20 | object which is referred to by a weak reference. |
| 21 | |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 22 | A weak reference to an object is not enough to keep the object alive: |
| 23 | when the only remaining references to a referent are weak references, |
| 24 | garbage collection is free to destroy the referent and reuse its memory |
| 25 | for something else. A primary use for weak references is to implement |
| 26 | caches or mappings holding large objects, where it's desired that a |
| 27 | large object not be kept alive solely because it appears in a cache or |
| 28 | mapping. For example, if you have a number of large binary image objects, |
| 29 | you may wish to associate a name with each. If you used a Python |
| 30 | dictionary to map names to images, or images to names, the image objects |
| 31 | would remain alive just because they appeared as values or keys in the |
| 32 | dictionaries. The \class{WeakKeyDictionary} and |
| 33 | \class{WeakValueDictionary} classes supplied by the \module{weakref} |
| 34 | module are an alternative, using weak references to construct mappings |
| 35 | that don't keep objects alive solely because they appear in the mapping |
| 36 | objects. If, for example, an image object is a value in a |
| 37 | \class{WeakValueDictionary}, then when the last remaining |
| 38 | references to that image object are the weak references held by weak |
| 39 | mappings, garbage collection can reclaim the object, and its corresponding |
| 40 | entries in weak mappings are simply deleted. |
| 41 | |
| 42 | \class{WeakKeyDictionary} and \class{WeakValueDictionary} use weak |
| 43 | references in their implementation, setting up callback functions on |
| 44 | the weak references that notify the weak dictionaries when a key or value |
| 45 | has been reclaimed by garbage collection. Most programs should find that |
| 46 | using one of these weak dictionary types is all they need -- it's |
| 47 | not usually necessary to create your own weak references directly. The |
| 48 | low-level machinery used by the weak dictionary implementations is exposed |
| 49 | by the \module{weakref} module for the benefit of advanced uses. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 50 | |
Raymond Hettinger | f8020e0 | 2003-07-02 15:10:38 +0000 | [diff] [blame] | 51 | Not all objects can be weakly referenced; those objects which can |
Fred Drake | 5e0dfac | 2001-03-23 04:36:02 +0000 | [diff] [blame] | 52 | include class instances, functions written in Python (but not in C), |
Raymond Hettinger | 027bb63 | 2004-05-31 03:09:25 +0000 | [diff] [blame] | 53 | methods (both bound and unbound), sets, frozensets, file objects, |
Raymond Hettinger | 3480917 | 2004-06-12 06:56:44 +0000 | [diff] [blame] | 54 | generators, type objects, DBcursor objects from the \module{bsddb} module, |
Raymond Hettinger | 027bb63 | 2004-05-31 03:09:25 +0000 | [diff] [blame] | 55 | sockets, arrays, deques, and regular expression pattern objects. |
| 56 | \versionchanged[Added support for files, sockets, arrays, and patterns]{2.4} |
| 57 | |
| 58 | Several builtin types such as \class{list} and \class{dict} do not |
| 59 | directly support weak references but can add support through subclassing: |
| 60 | |
| 61 | \begin{verbatim} |
| 62 | class Dict(dict): |
| 63 | pass |
| 64 | |
| 65 | obj = Dict(red=1, green=2, blue=3) # this object is weak referencable |
| 66 | \end{verbatim} |
| 67 | |
| 68 | Extension types can easily be made to support weak references; see section |
| 69 | \ref{weakref-extension}, ``Weak References in Extension Types,'' for more |
| 70 | information. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 71 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 72 | |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 73 | \begin{classdesc}{ref}{object\optional{, callback}} |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 74 | Return a weak reference to \var{object}. The original object can be |
| 75 | retrieved by calling the reference object if the referent is still |
| 76 | alive; if the referent is no longer alive, calling the reference |
Fred Drake | 21ae4f9 | 2004-02-03 20:55:15 +0000 | [diff] [blame] | 77 | object will cause \constant{None} to be returned. If \var{callback} is |
Fred Drake | 4458ece | 2004-02-03 19:44:26 +0000 | [diff] [blame] | 78 | provided and not \constant{None}, |
| 79 | it will be called when the object is about to be |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 80 | finalized; the weak reference object will be passed as the only |
| 81 | parameter to the callback; the referent will no longer be available. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 82 | |
| 83 | It is allowable for many weak references to be constructed for the |
| 84 | same object. Callbacks registered for each weak reference will be |
| 85 | called from the most recently registered callback to the oldest |
| 86 | registered callback. |
| 87 | |
| 88 | Exceptions raised by the callback will be noted on the standard |
Andrew M. Kuchling | e7d7e6c | 2001-02-14 02:39:11 +0000 | [diff] [blame] | 89 | error output, but cannot be propagated; they are handled in exactly |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 90 | the same way as exceptions raised from an object's |
| 91 | \method{__del__()} method. |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 92 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 93 | Weak references are hashable if the \var{object} is hashable. They |
| 94 | will maintain their hash value even after the \var{object} was |
| 95 | deleted. If \function{hash()} is called the first time only after |
| 96 | the \var{object} was deleted, the call will raise |
| 97 | \exception{TypeError}. |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 98 | |
Fred Drake | 3a2c462 | 2001-10-26 03:00:39 +0000 | [diff] [blame] | 99 | Weak references support tests for equality, but not ordering. If |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 100 | the referents are still alive, two references have the same |
Fred Drake | b03d0cc | 2001-11-26 21:39:40 +0000 | [diff] [blame] | 101 | equality relationship as their referents (regardless of the |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 102 | \var{callback}). If either referent has been deleted, the |
| 103 | references are equal only if the reference objects are the same |
| 104 | object. |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 105 | |
| 106 | \versionchanged[This is now a subclassable type rather than a |
| 107 | factory function; it derives from \class{object}] |
| 108 | {2.4} |
| 109 | \end{classdesc} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 110 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 111 | \begin{funcdesc}{proxy}{object\optional{, callback}} |
| 112 | Return a proxy to \var{object} which uses a weak reference. This |
| 113 | supports use of the proxy in most contexts instead of requiring the |
| 114 | explicit dereferencing used with weak reference objects. The |
| 115 | returned object will have a type of either \code{ProxyType} or |
| 116 | \code{CallableProxyType}, depending on whether \var{object} is |
| 117 | callable. Proxy objects are not hashable regardless of the |
| 118 | referent; this avoids a number of problems related to their |
| 119 | fundamentally mutable nature, and prevent their use as dictionary |
Fred Drake | e7ec1ef | 2001-05-10 17:22:17 +0000 | [diff] [blame] | 120 | keys. \var{callback} is the same as the parameter of the same name |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 121 | to the \function{ref()} function. |
| 122 | \end{funcdesc} |
| 123 | |
| 124 | \begin{funcdesc}{getweakrefcount}{object} |
| 125 | Return the number of weak references and proxies which refer to |
| 126 | \var{object}. |
| 127 | \end{funcdesc} |
| 128 | |
| 129 | \begin{funcdesc}{getweakrefs}{object} |
| 130 | Return a list of all weak reference and proxy objects which refer to |
| 131 | \var{object}. |
| 132 | \end{funcdesc} |
| 133 | |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 134 | \begin{classdesc}{WeakKeyDictionary}{\optional{dict}} |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 135 | Mapping class that references keys weakly. Entries in the |
| 136 | dictionary will be discarded when there is no longer a strong |
| 137 | reference to the key. This can be used to associate additional data |
| 138 | with an object owned by other parts of an application without adding |
| 139 | attributes to those objects. This can be especially useful with |
| 140 | objects that override attribute accesses. |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 141 | |
| 142 | \note{Caution: Because a \class{WeakKeyDictionary} is built on top |
| 143 | of a Python dictionary, it must not change size when iterating |
| 144 | over it. This can be difficult to ensure for a |
| 145 | \class{WeakKeyDictionary} because actions performed by the |
| 146 | program during iteration may cause items in the dictionary |
| 147 | to vanish "by magic" (as a side effect of garbage collection).} |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 148 | \end{classdesc} |
| 149 | |
| 150 | \begin{classdesc}{WeakValueDictionary}{\optional{dict}} |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 151 | Mapping class that references values weakly. Entries in the |
| 152 | dictionary will be discarded when no strong reference to the value |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 153 | exists any more. |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 154 | |
| 155 | \note{Caution: Because a \class{WeakValueDictionary} is built on top |
| 156 | of a Python dictionary, it must not change size when iterating |
| 157 | over it. This can be difficult to ensure for a |
| 158 | \class{WeakValueDictionary} because actions performed by the |
| 159 | program during iteration may cause items in the dictionary |
| 160 | to vanish "by magic" (as a side effect of garbage collection).} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 161 | \end{classdesc} |
| 162 | |
| 163 | \begin{datadesc}{ReferenceType} |
| 164 | The type object for weak references objects. |
| 165 | \end{datadesc} |
| 166 | |
| 167 | \begin{datadesc}{ProxyType} |
| 168 | The type object for proxies of objects which are not callable. |
| 169 | \end{datadesc} |
| 170 | |
| 171 | \begin{datadesc}{CallableProxyType} |
| 172 | The type object for proxies of callable objects. |
| 173 | \end{datadesc} |
| 174 | |
| 175 | \begin{datadesc}{ProxyTypes} |
| 176 | Sequence containing all the type objects for proxies. This can make |
| 177 | it simpler to test if an object is a proxy without being dependent |
| 178 | on naming both proxy types. |
| 179 | \end{datadesc} |
| 180 | |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 181 | \begin{excdesc}{ReferenceError} |
| 182 | Exception raised when a proxy object is used but the underlying |
Fred Drake | 8c2c3d3 | 2001-10-06 06:10:54 +0000 | [diff] [blame] | 183 | object has been collected. This is the same as the standard |
| 184 | \exception{ReferenceError} exception. |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 185 | \end{excdesc} |
| 186 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 187 | |
| 188 | \begin{seealso} |
| 189 | \seepep{0205}{Weak References}{The proposal and rationale for this |
| 190 | feature, including links to earlier implementations |
| 191 | and information about similar features in other |
| 192 | languages.} |
| 193 | \end{seealso} |
| 194 | |
| 195 | |
| 196 | \subsection{Weak Reference Objects |
| 197 | \label{weakref-objects}} |
| 198 | |
| 199 | Weak reference objects have no attributes or methods, but do allow the |
| 200 | referent to be obtained, if it still exists, by calling it: |
| 201 | |
| 202 | \begin{verbatim} |
| 203 | >>> import weakref |
| 204 | >>> class Object: |
| 205 | ... pass |
| 206 | ... |
| 207 | >>> o = Object() |
| 208 | >>> r = weakref.ref(o) |
| 209 | >>> o2 = r() |
| 210 | >>> o is o2 |
Martin v. Löwis | ccabed3 | 2003-11-27 19:48:03 +0000 | [diff] [blame] | 211 | True |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 212 | \end{verbatim} |
| 213 | |
| 214 | If the referent no longer exists, calling the reference object returns |
Fred Drake | 21ae4f9 | 2004-02-03 20:55:15 +0000 | [diff] [blame] | 215 | \constant{None}: |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 216 | |
| 217 | \begin{verbatim} |
| 218 | >>> del o, o2 |
| 219 | >>> print r() |
| 220 | None |
| 221 | \end{verbatim} |
| 222 | |
| 223 | Testing that a weak reference object is still live should be done |
Fred Drake | 5d54879 | 2001-08-03 03:50:28 +0000 | [diff] [blame] | 224 | using the expression \code{\var{ref}() is not None}. Normally, |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 225 | application code that needs to use a reference object should follow |
| 226 | this pattern: |
| 227 | |
| 228 | \begin{verbatim} |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 229 | # r is a weak reference object |
| 230 | o = r() |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 231 | if o is None: |
| 232 | # referent has been garbage collected |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 233 | print "Object has been deallocated; can't frobnicate." |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 234 | else: |
| 235 | print "Object is still live!" |
| 236 | o.do_something_useful() |
| 237 | \end{verbatim} |
| 238 | |
| 239 | Using a separate test for ``liveness'' creates race conditions in |
| 240 | threaded applications; another thread can cause a weak reference to |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 241 | become invalidated before the weak reference is called; the |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 242 | idiom shown above is safe in threaded applications as well as |
| 243 | single-threaded applications. |
| 244 | |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 245 | Specialized versions of \class{ref} objects can be created through |
| 246 | subclassing. This is used in the implementation of the |
| 247 | \class{WeakValueDictionary} to reduce the memory overhead for each |
| 248 | entry in the mapping. This may be most useful to associate additional |
| 249 | information with a reference, but could also be used to insert |
| 250 | additional processing on calls to retrieve the referent. |
| 251 | |
| 252 | This example shows how a subclass of \class{ref} can be used to store |
| 253 | additional information about an object and affect the value that's |
| 254 | returned when the referent is accessed: |
| 255 | |
| 256 | \begin{verbatim} |
| 257 | import weakref |
| 258 | |
| 259 | class ExtendedRef(weakref.ref): |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 260 | def __init__(self, ob, callback=None, **annotations): |
| 261 | super(ExtendedRef, self).__init__(ob, callback) |
Georg Brandl | 376e622 | 2005-07-02 10:44:32 +0000 | [diff] [blame] | 262 | self.__counter = 0 |
| 263 | for k, v in annotations.iteritems(): |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 264 | setattr(self, k, v) |
| 265 | |
| 266 | def __call__(self): |
| 267 | """Return a pair containing the referent and the number of |
| 268 | times the reference has been called. |
| 269 | """ |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 270 | ob = super(ExtendedRef, self).__call__() |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 271 | if ob is not None: |
| 272 | self.__counter += 1 |
| 273 | ob = (ob, self.__counter) |
| 274 | return ob |
| 275 | \end{verbatim} |
| 276 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 277 | |
Fred Drake | cb83988 | 2001-03-28 21:15:41 +0000 | [diff] [blame] | 278 | \subsection{Example \label{weakref-example}} |
| 279 | |
| 280 | This simple example shows how an application can use objects IDs to |
| 281 | retrieve objects that it has seen before. The IDs of the objects can |
| 282 | then be used in other data structures without forcing the objects to |
| 283 | remain alive, but the objects can still be retrieved by ID if they |
| 284 | do. |
| 285 | |
Fred Drake | 4271310 | 2003-12-30 16:15:35 +0000 | [diff] [blame] | 286 | % Example contributed by Tim Peters. |
Fred Drake | cb83988 | 2001-03-28 21:15:41 +0000 | [diff] [blame] | 287 | \begin{verbatim} |
| 288 | import weakref |
| 289 | |
Fred Drake | ac154a1 | 2001-04-10 19:57:58 +0000 | [diff] [blame] | 290 | _id2obj_dict = weakref.WeakValueDictionary() |
Fred Drake | cb83988 | 2001-03-28 21:15:41 +0000 | [diff] [blame] | 291 | |
| 292 | def remember(obj): |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 293 | oid = id(obj) |
| 294 | _id2obj_dict[oid] = obj |
| 295 | return oid |
Fred Drake | cb83988 | 2001-03-28 21:15:41 +0000 | [diff] [blame] | 296 | |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 297 | def id2obj(oid): |
| 298 | return _id2obj_dict[oid] |
Fred Drake | cb83988 | 2001-03-28 21:15:41 +0000 | [diff] [blame] | 299 | \end{verbatim} |
| 300 | |
| 301 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 302 | \subsection{Weak References in Extension Types |
| 303 | \label{weakref-extension}} |
| 304 | |
| 305 | One of the goals of the implementation is to allow any type to |
| 306 | participate in the weak reference mechanism without incurring the |
| 307 | overhead on those objects which do not benefit by weak referencing |
| 308 | (such as numbers). |
| 309 | |
| 310 | For an object to be weakly referencable, the extension must include a |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 311 | \ctype{PyObject*} field in the instance structure for the use of the |
Fred Drake | 5e0dfac | 2001-03-23 04:36:02 +0000 | [diff] [blame] | 312 | weak reference mechanism; it must be initialized to \NULL{} by the |
| 313 | object's constructor. It must also set the \member{tp_weaklistoffset} |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 314 | field of the corresponding type object to the offset of the field. |
Raymond Hettinger | 22c001b | 2002-08-07 16:18:54 +0000 | [diff] [blame] | 315 | Also, it needs to add \constant{Py_TPFLAGS_HAVE_WEAKREFS} to the |
| 316 | tp_flags slot. For example, the instance type is defined with the |
| 317 | following structure: |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 318 | |
| 319 | \begin{verbatim} |
| 320 | typedef struct { |
| 321 | PyObject_HEAD |
| 322 | PyClassObject *in_class; /* The class object */ |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 323 | PyObject *in_dict; /* A dictionary */ |
| 324 | PyObject *in_weakreflist; /* List of weak references */ |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 325 | } PyInstanceObject; |
| 326 | \end{verbatim} |
| 327 | |
| 328 | The statically-declared type object for instances is defined this way: |
| 329 | |
| 330 | \begin{verbatim} |
| 331 | PyTypeObject PyInstance_Type = { |
| 332 | PyObject_HEAD_INIT(&PyType_Type) |
| 333 | 0, |
Guido van Rossum | 1464839 | 2001-12-08 18:02:58 +0000 | [diff] [blame] | 334 | "module.instance", |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 335 | |
Fred Drake | f66cb5d | 2001-06-22 17:20:29 +0000 | [diff] [blame] | 336 | /* Lots of stuff omitted for brevity... */ |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 337 | |
Raymond Hettinger | 22c001b | 2002-08-07 16:18:54 +0000 | [diff] [blame] | 338 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS /* tp_flags */ |
| 339 | 0, /* tp_doc */ |
| 340 | 0, /* tp_traverse */ |
| 341 | 0, /* tp_clear */ |
| 342 | 0, /* tp_richcompare */ |
| 343 | offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */ |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 344 | }; |
| 345 | \end{verbatim} |
| 346 | |
Raymond Hettinger | 22c001b | 2002-08-07 16:18:54 +0000 | [diff] [blame] | 347 | The type constructor is responsible for initializing the weak reference |
| 348 | list to \NULL: |
| 349 | |
| 350 | \begin{verbatim} |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 351 | static PyObject * |
| 352 | instance_new() { |
| 353 | /* Other initialization stuff omitted for brevity */ |
Raymond Hettinger | 22c001b | 2002-08-07 16:18:54 +0000 | [diff] [blame] | 354 | |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 355 | self->in_weakreflist = NULL; |
Raymond Hettinger | 22c001b | 2002-08-07 16:18:54 +0000 | [diff] [blame] | 356 | |
Tim Peters | 5a5b243 | 2003-11-21 22:20:57 +0000 | [diff] [blame] | 357 | return (PyObject *) self; |
| 358 | } |
Raymond Hettinger | 22c001b | 2002-08-07 16:18:54 +0000 | [diff] [blame] | 359 | \end{verbatim} |
| 360 | |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 361 | The only further addition is that the destructor needs to call the |
Fred Drake | f66cb5d | 2001-06-22 17:20:29 +0000 | [diff] [blame] | 362 | weak reference manager to clear any weak references. This should be |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 363 | done before any other parts of the destruction have occurred, but is |
| 364 | only required if the weak reference list is non-\NULL: |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 365 | |
| 366 | \begin{verbatim} |
| 367 | static void |
| 368 | instance_dealloc(PyInstanceObject *inst) |
| 369 | { |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 370 | /* Allocate temporaries if needed, but do not begin |
Fred Drake | f66cb5d | 2001-06-22 17:20:29 +0000 | [diff] [blame] | 371 | destruction just yet. |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 372 | */ |
| 373 | |
Fred Drake | 7408da5 | 2001-10-26 17:40:22 +0000 | [diff] [blame] | 374 | if (inst->in_weakreflist != NULL) |
| 375 | PyObject_ClearWeakRefs((PyObject *) inst); |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 376 | |
Fred Drake | de3d060 | 2001-10-26 11:27:54 +0000 | [diff] [blame] | 377 | /* Proceed with object destruction normally. */ |
Fred Drake | ebcf6a8 | 2001-02-01 05:20:20 +0000 | [diff] [blame] | 378 | } |
| 379 | \end{verbatim} |