PageRenderTime 56ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/Python-2.7.3/Doc/library/weakref.rst

#
ReStructuredText | 357 lines | 242 code | 115 blank | 0 comment | 0 complexity | 5fd7ac2a98640c5c2eeafa90efeb66c8 MD5 | raw file
Possible License(s): 0BSD
  1. :mod:`weakref` --- Weak references
  2. ==================================
  3. .. module:: weakref
  4. :synopsis: Support for weak references and weak dictionaries.
  5. .. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  6. .. moduleauthor:: Neil Schemenauer <nas@arctrix.com>
  7. .. moduleauthor:: Martin von L??wis <martin@loewis.home.cs.tu-berlin.de>
  8. .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  9. .. versionadded:: 2.1
  10. **Source code:** :source:`Lib/weakref.py`
  11. --------------
  12. The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
  13. references` to objects.
  14. .. When making changes to the examples in this file, be sure to update
  15. Lib/test/test_weakref.py::libreftest too!
  16. In the following, the term :dfn:`referent` means the object which is referred to
  17. by a weak reference.
  18. A weak reference to an object is not enough to keep the object alive: when the
  19. only remaining references to a referent are weak references,
  20. :term:`garbage collection` is free to destroy the referent and reuse its memory
  21. for something else. A primary use for weak references is to implement caches or
  22. mappings holding large objects, where it's desired that a large object not be
  23. kept alive solely because it appears in a cache or mapping.
  24. For example, if you have a number of large binary image objects, you may wish to
  25. associate a name with each. If you used a Python dictionary to map names to
  26. images, or images to names, the image objects would remain alive just because
  27. they appeared as values or keys in the dictionaries. The
  28. :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
  29. the :mod:`weakref` module are an alternative, using weak references to construct
  30. mappings that don't keep objects alive solely because they appear in the mapping
  31. objects. If, for example, an image object is a value in a
  32. :class:`WeakValueDictionary`, then when the last remaining references to that
  33. image object are the weak references held by weak mappings, garbage collection
  34. can reclaim the object, and its corresponding entries in weak mappings are
  35. simply deleted.
  36. :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
  37. in their implementation, setting up callback functions on the weak references
  38. that notify the weak dictionaries when a key or value has been reclaimed by
  39. garbage collection. Most programs should find that using one of these weak
  40. dictionary types is all they need -- it's not usually necessary to create your
  41. own weak references directly. The low-level machinery used by the weak
  42. dictionary implementations is exposed by the :mod:`weakref` module for the
  43. benefit of advanced uses.
  44. .. note::
  45. Weak references to an object are cleared before the object's :meth:`__del__`
  46. is called, to ensure that the weak reference callback (if any) finds the
  47. object still alive.
  48. Not all objects can be weakly referenced; those objects which can include class
  49. instances, functions written in Python (but not in C), methods (both bound and
  50. unbound), sets, frozensets, file objects, :term:`generator`\s, type objects,
  51. :class:`DBcursor` objects from the :mod:`bsddb` module, sockets, arrays, deques,
  52. regular expression pattern objects, and code objects.
  53. .. versionchanged:: 2.4
  54. Added support for files, sockets, arrays, and patterns.
  55. .. versionchanged:: 2.7
  56. Added support for thread.lock, threading.Lock, and code objects.
  57. Several built-in types such as :class:`list` and :class:`dict` do not directly
  58. support weak references but can add support through subclassing::
  59. class Dict(dict):
  60. pass
  61. obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
  62. .. impl-detail::
  63. Other built-in types such as :class:`tuple` and :class:`long` do not support
  64. weak references even when subclassed.
  65. Extension types can easily be made to support weak references; see
  66. :ref:`weakref-support`.
  67. .. class:: ref(object[, callback])
  68. Return a weak reference to *object*. The original object can be retrieved by
  69. calling the reference object if the referent is still alive; if the referent is
  70. no longer alive, calling the reference object will cause :const:`None` to be
  71. returned. If *callback* is provided and not :const:`None`, and the returned
  72. weakref object is still alive, the callback will be called when the object is
  73. about to be finalized; the weak reference object will be passed as the only
  74. parameter to the callback; the referent will no longer be available.
  75. It is allowable for many weak references to be constructed for the same object.
  76. Callbacks registered for each weak reference will be called from the most
  77. recently registered callback to the oldest registered callback.
  78. Exceptions raised by the callback will be noted on the standard error output,
  79. but cannot be propagated; they are handled in exactly the same way as exceptions
  80. raised from an object's :meth:`__del__` method.
  81. Weak references are :term:`hashable` if the *object* is hashable. They will maintain
  82. their hash value even after the *object* was deleted. If :func:`hash` is called
  83. the first time only after the *object* was deleted, the call will raise
  84. :exc:`TypeError`.
  85. Weak references support tests for equality, but not ordering. If the referents
  86. are still alive, two references have the same equality relationship as their
  87. referents (regardless of the *callback*). If either referent has been deleted,
  88. the references are equal only if the reference objects are the same object.
  89. .. versionchanged:: 2.4
  90. This is now a subclassable type rather than a factory function; it derives from
  91. :class:`object`.
  92. .. function:: proxy(object[, callback])
  93. Return a proxy to *object* which uses a weak reference. This supports use of
  94. the proxy in most contexts instead of requiring the explicit dereferencing used
  95. with weak reference objects. The returned object will have a type of either
  96. ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
  97. callable. Proxy objects are not :term:`hashable` regardless of the referent; this
  98. avoids a number of problems related to their fundamentally mutable nature, and
  99. prevent their use as dictionary keys. *callback* is the same as the parameter
  100. of the same name to the :func:`ref` function.
  101. .. function:: getweakrefcount(object)
  102. Return the number of weak references and proxies which refer to *object*.
  103. .. function:: getweakrefs(object)
  104. Return a list of all weak reference and proxy objects which refer to *object*.
  105. .. class:: WeakKeyDictionary([dict])
  106. Mapping class that references keys weakly. Entries in the dictionary will be
  107. discarded when there is no longer a strong reference to the key. This can be
  108. used to associate additional data with an object owned by other parts of an
  109. application without adding attributes to those objects. This can be especially
  110. useful with objects that override attribute accesses.
  111. .. note::
  112. Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
  113. dictionary, it must not change size when iterating over it. This can be
  114. difficult to ensure for a :class:`WeakKeyDictionary` because actions
  115. performed by the program during iteration may cause items in the
  116. dictionary to vanish "by magic" (as a side effect of garbage collection).
  117. :class:`WeakKeyDictionary` objects have the following additional methods. These
  118. expose the internal references directly. The references are not guaranteed to
  119. be "live" at the time they are used, so the result of calling the references
  120. needs to be checked before being used. This can be used to avoid creating
  121. references that will cause the garbage collector to keep the keys around longer
  122. than needed.
  123. .. method:: WeakKeyDictionary.iterkeyrefs()
  124. Return an :term:`iterator` that yields the weak references to the keys.
  125. .. versionadded:: 2.5
  126. .. method:: WeakKeyDictionary.keyrefs()
  127. Return a list of weak references to the keys.
  128. .. versionadded:: 2.5
  129. .. class:: WeakValueDictionary([dict])
  130. Mapping class that references values weakly. Entries in the dictionary will be
  131. discarded when no strong reference to the value exists any more.
  132. .. note::
  133. Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
  134. dictionary, it must not change size when iterating over it. This can be
  135. difficult to ensure for a :class:`WeakValueDictionary` because actions performed
  136. by the program during iteration may cause items in the dictionary to vanish "by
  137. magic" (as a side effect of garbage collection).
  138. :class:`WeakValueDictionary` objects have the following additional methods.
  139. These method have the same issues as the :meth:`iterkeyrefs` and :meth:`keyrefs`
  140. methods of :class:`WeakKeyDictionary` objects.
  141. .. method:: WeakValueDictionary.itervaluerefs()
  142. Return an :term:`iterator` that yields the weak references to the values.
  143. .. versionadded:: 2.5
  144. .. method:: WeakValueDictionary.valuerefs()
  145. Return a list of weak references to the values.
  146. .. versionadded:: 2.5
  147. .. class:: WeakSet([elements])
  148. Set class that keeps weak references to its elements. An element will be
  149. discarded when no strong reference to it exists any more.
  150. .. versionadded:: 2.7
  151. .. data:: ReferenceType
  152. The type object for weak references objects.
  153. .. data:: ProxyType
  154. The type object for proxies of objects which are not callable.
  155. .. data:: CallableProxyType
  156. The type object for proxies of callable objects.
  157. .. data:: ProxyTypes
  158. Sequence containing all the type objects for proxies. This can make it simpler
  159. to test if an object is a proxy without being dependent on naming both proxy
  160. types.
  161. .. exception:: ReferenceError
  162. Exception raised when a proxy object is used but the underlying object has been
  163. collected. This is the same as the standard :exc:`ReferenceError` exception.
  164. .. seealso::
  165. :pep:`0205` - Weak References
  166. The proposal and rationale for this feature, including links to earlier
  167. implementations and information about similar features in other languages.
  168. .. _weakref-objects:
  169. Weak Reference Objects
  170. ----------------------
  171. Weak reference objects have no attributes or methods, but do allow the referent
  172. to be obtained, if it still exists, by calling it:
  173. >>> import weakref
  174. >>> class Object:
  175. ... pass
  176. ...
  177. >>> o = Object()
  178. >>> r = weakref.ref(o)
  179. >>> o2 = r()
  180. >>> o is o2
  181. True
  182. If the referent no longer exists, calling the reference object returns
  183. :const:`None`:
  184. >>> del o, o2
  185. >>> print r()
  186. None
  187. Testing that a weak reference object is still live should be done using the
  188. expression ``ref() is not None``. Normally, application code that needs to use
  189. a reference object should follow this pattern::
  190. # r is a weak reference object
  191. o = r()
  192. if o is None:
  193. # referent has been garbage collected
  194. print "Object has been deallocated; can't frobnicate."
  195. else:
  196. print "Object is still live!"
  197. o.do_something_useful()
  198. Using a separate test for "liveness" creates race conditions in threaded
  199. applications; another thread can cause a weak reference to become invalidated
  200. before the weak reference is called; the idiom shown above is safe in threaded
  201. applications as well as single-threaded applications.
  202. Specialized versions of :class:`ref` objects can be created through subclassing.
  203. This is used in the implementation of the :class:`WeakValueDictionary` to reduce
  204. the memory overhead for each entry in the mapping. This may be most useful to
  205. associate additional information with a reference, but could also be used to
  206. insert additional processing on calls to retrieve the referent.
  207. This example shows how a subclass of :class:`ref` can be used to store
  208. additional information about an object and affect the value that's returned when
  209. the referent is accessed::
  210. import weakref
  211. class ExtendedRef(weakref.ref):
  212. def __init__(self, ob, callback=None, **annotations):
  213. super(ExtendedRef, self).__init__(ob, callback)
  214. self.__counter = 0
  215. for k, v in annotations.iteritems():
  216. setattr(self, k, v)
  217. def __call__(self):
  218. """Return a pair containing the referent and the number of
  219. times the reference has been called.
  220. """
  221. ob = super(ExtendedRef, self).__call__()
  222. if ob is not None:
  223. self.__counter += 1
  224. ob = (ob, self.__counter)
  225. return ob
  226. .. _weakref-example:
  227. Example
  228. -------
  229. This simple example shows how an application can use objects IDs to retrieve
  230. objects that it has seen before. The IDs of the objects can then be used in
  231. other data structures without forcing the objects to remain alive, but the
  232. objects can still be retrieved by ID if they do.
  233. .. Example contributed by Tim Peters.
  234. ::
  235. import weakref
  236. _id2obj_dict = weakref.WeakValueDictionary()
  237. def remember(obj):
  238. oid = id(obj)
  239. _id2obj_dict[oid] = obj
  240. return oid
  241. def id2obj(oid):
  242. return _id2obj_dict[oid]