blob: 5b5e46015643bd0e20dfcd0e7ff4c422fd12e314 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`weakref` --- Weak references
2==================================
3
4.. module:: weakref
5 :synopsis: 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รถwis <martin@loewis.home.cs.tu-berlin.de>
9.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
10
Raymond Hettinger469271d2011-01-27 20:38:46 +000011**Source code:** :source:`Lib/weakref.py`
12
13--------------
Georg Brandl116aa622007-08-15 14:28:22 +000014
Georg Brandl116aa622007-08-15 14:28:22 +000015The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
16references` to objects.
17
Christian Heimes5b5e81c2007-12-31 16:14:33 +000018.. When making changes to the examples in this file, be sure to update
19 Lib/test/test_weakref.py::libreftest too!
Georg Brandl116aa622007-08-15 14:28:22 +000020
21In the following, the term :dfn:`referent` means the object which is referred to
22by a weak reference.
23
24A weak reference to an object is not enough to keep the object alive: when the
Christian Heimesd8654cf2007-12-02 15:22:16 +000025only remaining references to a referent are weak references,
26:term:`garbage collection` is free to destroy the referent and reuse its memory
Antoine Pitrou9439f042012-08-21 00:07:07 +020027for something else. However, until the object is actually destroyed the weak
28reference may return the object even if there are no strong references to it.
29
30A primary use for weak references is to implement caches or
Christian Heimesd8654cf2007-12-02 15:22:16 +000031mappings holding large objects, where it's desired that a large object not be
Christian Heimesfe337bf2008-03-23 21:54:12 +000032kept alive solely because it appears in a cache or mapping.
33
34For example, if you have a number of large binary image objects, you may wish to
35associate a name with each. If you used a Python dictionary to map names to
36images, or images to names, the image objects would remain alive just because
37they appeared as values or keys in the dictionaries. The
38:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
39the :mod:`weakref` module are an alternative, using weak references to construct
40mappings that don't keep objects alive solely because they appear in the mapping
41objects. If, for example, an image object is a value in a
42:class:`WeakValueDictionary`, then when the last remaining references to that
43image object are the weak references held by weak mappings, garbage collection
44can reclaim the object, and its corresponding entries in weak mappings are
45simply deleted.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
48in their implementation, setting up callback functions on the weak references
49that notify the weak dictionaries when a key or value has been reclaimed by
Georg Brandl3b8cb172007-10-23 06:26:46 +000050garbage collection. :class:`WeakSet` implements the :class:`set` interface,
51but keeps weak references to its elements, just like a
52:class:`WeakKeyDictionary` does.
53
Richard Oudkerk7a3dae02013-05-05 23:05:00 +010054:class:`finalize` provides a straight forward way to register a
55cleanup function to be called when an object is garbage collected.
56This is simpler to use than setting up a callback function on a raw
57weak reference.
58
59Most programs should find that using one of these weak container types
60or :class:`finalize` is all they need -- it's not usually necessary to
61create your own weak references directly. The low-level machinery is
62exposed by the :mod:`weakref` module for the benefit of advanced uses.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64Not all objects can be weakly referenced; those objects which can include class
Georg Brandl2e0b7552007-11-27 12:43:08 +000065instances, functions written in Python (but not in C), instance methods, sets,
Antoine Pitrou11cb9612010-09-15 11:11:28 +000066frozensets, some :term:`file objects <file object>`, :term:`generator`\s, type
67objects, sockets, arrays, deques, regular expression pattern objects, and code
68objects.
Georg Brandl116aa622007-08-15 14:28:22 +000069
Benjamin Petersonbec4d572009-10-10 01:16:07 +000070.. versionchanged:: 3.2
Collin Winter4222e9c2010-03-18 22:46:40 +000071 Added support for thread.lock, threading.Lock, and code objects.
Benjamin Petersonbec4d572009-10-10 01:16:07 +000072
Georg Brandl22b34312009-07-26 14:54:51 +000073Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl116aa622007-08-15 14:28:22 +000074support weak references but can add support through subclassing::
75
76 class Dict(dict):
77 pass
78
Christian Heimesc3f30c42008-02-22 16:37:40 +000079 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl116aa622007-08-15 14:28:22 +000080
Benjamin Peterson905982b2010-05-08 15:26:30 +000081Other built-in types such as :class:`tuple` and :class:`int` do not support weak
82references even when subclassed (This is an implementation detail and may be
83different across various Python implementations.).
Georg Brandlff8c1e52009-10-21 07:17:48 +000084
Georg Brandl116aa622007-08-15 14:28:22 +000085Extension types can easily be made to support weak references; see
86:ref:`weakref-support`.
87
88
89.. class:: ref(object[, callback])
90
91 Return a weak reference to *object*. The original object can be retrieved by
92 calling the reference object if the referent is still alive; if the referent is
93 no longer alive, calling the reference object will cause :const:`None` to be
94 returned. If *callback* is provided and not :const:`None`, and the returned
95 weakref object is still alive, the callback will be called when the object is
96 about to be finalized; the weak reference object will be passed as the only
97 parameter to the callback; the referent will no longer be available.
98
99 It is allowable for many weak references to be constructed for the same object.
100 Callbacks registered for each weak reference will be called from the most
101 recently registered callback to the oldest registered callback.
102
103 Exceptions raised by the callback will be noted on the standard error output,
104 but cannot be propagated; they are handled in exactly the same way as exceptions
105 raised from an object's :meth:`__del__` method.
106
Georg Brandl7f01a132009-09-16 15:58:14 +0000107 Weak references are :term:`hashable` if the *object* is hashable. They will
108 maintain their hash value even after the *object* was deleted. If
109 :func:`hash` is called the first time only after the *object* was deleted,
110 the call will raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 Weak references support tests for equality, but not ordering. If the referents
113 are still alive, two references have the same equality relationship as their
114 referents (regardless of the *callback*). If either referent has been deleted,
115 the references are equal only if the reference objects are the same object.
116
Georg Brandl55ac8f02007-09-01 13:51:09 +0000117 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Mark Dickinson556e94b2013-04-13 15:45:44 +0100119 .. attribute:: __callback__
120
121 This read-only attribute returns the callback currently associated to the
122 weakref. If there is no callback or if the referent of the weakref is
123 no longer alive then this attribute will have value ``None``.
124
Richard Oudkerk7a3dae02013-05-05 23:05:00 +0100125 .. note::
126
127 Like :meth:`__del__` methods, weak reference callbacks can be
128 called during interpreter shutdown when module globals have been
129 overwritten with :const:`None`. This can make writing robust
130 weak reference callbacks a challenge. Callbacks registered
131 using :class:`finalize` do not have to worry about this issue
132 because they will not be run after module teardown has begun.
133
134 .. versionchanged:: 3.4
Mark Dickinson9b6fdf82013-04-13 16:09:18 +0100135 Added the :attr:`__callback__` attribute.
Mark Dickinson556e94b2013-04-13 15:45:44 +0100136
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138.. function:: proxy(object[, callback])
139
140 Return a proxy to *object* which uses a weak reference. This supports use of
141 the proxy in most contexts instead of requiring the explicit dereferencing used
142 with weak reference objects. The returned object will have a type of either
143 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000144 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000145 avoids a number of problems related to their fundamentally mutable nature, and
146 prevent their use as dictionary keys. *callback* is the same as the parameter
147 of the same name to the :func:`ref` function.
148
149
150.. function:: getweakrefcount(object)
151
152 Return the number of weak references and proxies which refer to *object*.
153
154
155.. function:: getweakrefs(object)
156
157 Return a list of all weak reference and proxy objects which refer to *object*.
158
159
160.. class:: WeakKeyDictionary([dict])
161
162 Mapping class that references keys weakly. Entries in the dictionary will be
163 discarded when there is no longer a strong reference to the key. This can be
164 used to associate additional data with an object owned by other parts of an
165 application without adding attributes to those objects. This can be especially
166 useful with objects that override attribute accesses.
167
168 .. note::
169
Christian Heimesfe337bf2008-03-23 21:54:12 +0000170 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000171 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000172 difficult to ensure for a :class:`WeakKeyDictionary` because actions
173 performed by the program during iteration may cause items in the
174 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176:class:`WeakKeyDictionary` objects have the following additional methods. These
177expose the internal references directly. The references are not guaranteed to
178be "live" at the time they are used, so the result of calling the references
179needs to be checked before being used. This can be used to avoid creating
180references that will cause the garbage collector to keep the keys around longer
181than needed.
182
183
Georg Brandl116aa622007-08-15 14:28:22 +0000184.. method:: WeakKeyDictionary.keyrefs()
185
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000186 Return an iterable of the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189.. class:: WeakValueDictionary([dict])
190
191 Mapping class that references values weakly. Entries in the dictionary will be
192 discarded when no strong reference to the value exists any more.
193
194 .. note::
195
196 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
197 dictionary, it must not change size when iterating over it. This can be
198 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
199 by the program during iteration may cause items in the dictionary to vanish "by
200 magic" (as a side effect of garbage collection).
201
202:class:`WeakValueDictionary` objects have the following additional methods.
Barry Warsawecaab832008-09-04 01:42:51 +0000203These method have the same issues as the and :meth:`keyrefs` method of
204:class:`WeakKeyDictionary` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207.. method:: WeakValueDictionary.valuerefs()
208
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000209 Return an iterable of the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000210
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Georg Brandl3b8cb172007-10-23 06:26:46 +0000212.. class:: WeakSet([elements])
213
214 Set class that keeps weak references to its elements. An element will be
215 discarded when no strong reference to it exists any more.
216
217
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100218.. class:: WeakMethod(method)
219
220 A custom :class:`ref` subclass which simulates a weak reference to a bound
221 method (i.e., a method defined on a class and looked up on an instance).
222 Since a bound method is ephemeral, a standard weak reference cannot keep
223 hold of it. :class:`WeakMethod` has special code to recreate the bound
224 method until either the object or the original function dies::
225
226 >>> class C:
227 ... def method(self):
228 ... print("method called!")
229 ...
230 >>> c = C()
231 >>> r = weakref.ref(c.method)
232 >>> r()
233 >>> r = weakref.WeakMethod(c.method)
234 >>> r()
235 <bound method C.method of <__main__.C object at 0x7fc859830220>>
236 >>> r()()
237 method called!
238 >>> del c
239 >>> gc.collect()
240 0
241 >>> r()
242 >>>
243
244 .. versionadded:: 3.4
245
Richard Oudkerk7a3dae02013-05-05 23:05:00 +0100246.. class:: finalize(obj, func, *args, **kwargs)
247
248 Return a callable finalizer object which will be called when *obj*
249 is garbage collected. A finalizer is *alive* until it is called
250 (either explicitly or at garbage collection), and after that it is
251 *dead*. Calling a live finalizer returns the result of evaluating
252 ``func(*arg, **kwargs)``, whereas calling a dead finalizer returns
253 :const:`None`.
254
255 Exceptions raised by finalizer callbacks during garbage collection
256 will be shown on the standard error output, but cannot be
257 propagated. They are handled in the same way as exceptions raised
258 from an object's :meth:`__del__` method or a weak reference's
259 callback.
260
261 When the program exits, each remaining live finalizer is called
262 unless its :attr:`atexit` attribute has been set to false. They
263 are called in reverse order of creation.
264
265 A finalizer will never invoke its callback during the later part of
266 the interpreter shutdown when module globals are liable to have
267 been replaced by :const:`None`.
268
269 .. method:: __call__()
270
271 If *self* is alive then mark it as dead and return the result of
272 calling ``func(*args, **kwargs)``. If *self* is dead then return
273 :const:`None`.
274
275 .. method:: detach()
276
277 If *self* is alive then mark it as dead and return the tuple
278 ``(obj, func, args, kwargs)``. If *self* is dead then return
279 :const:`None`.
280
281 .. method:: peek()
282
283 If *self* is alive then return the tuple ``(obj, func, args,
284 kwargs)``. If *self* is dead then return :const:`None`.
285
286 .. attribute:: alive
287
288 Property which is true if the finalizer is alive, false otherwise.
289
290 .. attribute:: atexit
291
292 A writable boolean property which by default is true. When the
293 program exits, it calls all remaining live finalizers for which
294 :attr:`.atexit` is true. They are called in reverse order of
295 creation.
296
297 .. note::
298
299 It is important to ensure that *func*, *args* and *kwargs* do
300 not own any references to *obj*, either directly or indirectly,
301 since otherwise *obj* will never be garbage collected. In
302 particular, *func* should not be a bound method of *obj*.
303
304 .. versionadded:: 3.4
305
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100306
Georg Brandl116aa622007-08-15 14:28:22 +0000307.. data:: ReferenceType
308
309 The type object for weak references objects.
310
311
312.. data:: ProxyType
313
314 The type object for proxies of objects which are not callable.
315
316
317.. data:: CallableProxyType
318
319 The type object for proxies of callable objects.
320
321
322.. data:: ProxyTypes
323
324 Sequence containing all the type objects for proxies. This can make it simpler
325 to test if an object is a proxy without being dependent on naming both proxy
326 types.
327
328
329.. exception:: ReferenceError
330
331 Exception raised when a proxy object is used but the underlying object has been
332 collected. This is the same as the standard :exc:`ReferenceError` exception.
333
334
335.. seealso::
336
337 :pep:`0205` - Weak References
338 The proposal and rationale for this feature, including links to earlier
339 implementations and information about similar features in other languages.
340
341
342.. _weakref-objects:
343
344Weak Reference Objects
345----------------------
346
Mark Dickinson556e94b2013-04-13 15:45:44 +0100347Weak reference objects have no methods and no attributes besides
348:attr:`ref.__callback__`. A weak reference object allows the referent to be
349obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351 >>> import weakref
352 >>> class Object:
353 ... pass
354 ...
355 >>> o = Object()
356 >>> r = weakref.ref(o)
357 >>> o2 = r()
358 >>> o is o2
359 True
360
361If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000362:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000363
364 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000365 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000366 None
367
368Testing that a weak reference object is still live should be done using the
369expression ``ref() is not None``. Normally, application code that needs to use
370a reference object should follow this pattern::
371
372 # r is a weak reference object
373 o = r()
374 if o is None:
375 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000376 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000377 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000378 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000379 o.do_something_useful()
380
381Using a separate test for "liveness" creates race conditions in threaded
382applications; another thread can cause a weak reference to become invalidated
383before the weak reference is called; the idiom shown above is safe in threaded
384applications as well as single-threaded applications.
385
386Specialized versions of :class:`ref` objects can be created through subclassing.
387This is used in the implementation of the :class:`WeakValueDictionary` to reduce
388the memory overhead for each entry in the mapping. This may be most useful to
389associate additional information with a reference, but could also be used to
390insert additional processing on calls to retrieve the referent.
391
392This example shows how a subclass of :class:`ref` can be used to store
393additional information about an object and affect the value that's returned when
394the referent is accessed::
395
396 import weakref
397
398 class ExtendedRef(weakref.ref):
399 def __init__(self, ob, callback=None, **annotations):
400 super(ExtendedRef, self).__init__(ob, callback)
401 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000402 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000403 setattr(self, k, v)
404
405 def __call__(self):
406 """Return a pair containing the referent and the number of
407 times the reference has been called.
408 """
409 ob = super(ExtendedRef, self).__call__()
410 if ob is not None:
411 self.__counter += 1
412 ob = (ob, self.__counter)
413 return ob
414
415
416.. _weakref-example:
417
418Example
419-------
420
421This simple example shows how an application can use objects IDs to retrieve
422objects that it has seen before. The IDs of the objects can then be used in
423other data structures without forcing the objects to remain alive, but the
424objects can still be retrieved by ID if they do.
425
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000426.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428::
429
430 import weakref
431
432 _id2obj_dict = weakref.WeakValueDictionary()
433
434 def remember(obj):
435 oid = id(obj)
436 _id2obj_dict[oid] = obj
437 return oid
438
439 def id2obj(oid):
440 return _id2obj_dict[oid]
441
Richard Oudkerk7a3dae02013-05-05 23:05:00 +0100442
443.. _finalize-examples:
444
445Finalizer Objects
446-----------------
447
448Often one uses :class:`finalize` to register a callback without
449bothering to keep the returned finalizer object. For instance
450
451 >>> import weakref
452 >>> class Object:
453 ... pass
454 ...
455 >>> kenny = Object()
456 >>> weakref.finalize(kenny, print, "You killed Kenny!") #doctest:+ELLIPSIS
457 <finalize object at ...; for 'Object' at ...>
458 >>> del kenny
459 You killed Kenny!
460
461The finalizer can be called directly as well. However the finalizer
462will invoke the callback at most once.
463
464 >>> def callback(x, y, z):
465 ... print("CALLBACK")
466 ... return x + y + z
467 ...
468 >>> obj = Object()
469 >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
470 >>> assert f.alive
471 >>> assert f() == 6
472 CALLBACK
473 >>> assert not f.alive
474 >>> f() # callback not called because finalizer dead
475 >>> del obj # callback not called because finalizer dead
476
477You can unregister a finalizer using its :meth:`~finalize.detach`
478method. This kills the finalizer and returns the arguments passed to
479the constructor when it was created.
480
481 >>> obj = Object()
482 >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
483 >>> f.detach() #doctest:+ELLIPSIS
484 (<__main__.Object object ...>, <function callback ...>, (1, 2), {'z': 3})
485 >>> newobj, func, args, kwargs = _
486 >>> assert not f.alive
487 >>> assert newobj is obj
488 >>> assert func(*args, **kwargs) == 6
489 CALLBACK
490
491Unless you set the :attr:`~finalize.atexit` attribute to
492:const:`False`, a finalizer will be called when the program exit if it
493is still alive. For instance
494
495 >>> obj = Object()
496 >>> weakref.finalize(obj, print, "obj dead or exiting") #doctest:+ELLIPSIS
497 <finalize object at ...; for 'Object' at ...>
498 >>> exit() #doctest:+SKIP
499 obj dead or exiting
500
501
502Comparing finalizers with :meth:`__del__` methods
503-------------------------------------------------
504
505Suppose we want to create a class whose instances represent temporary
506directories. The directories should be deleted with their contents
507when the first of the following events occurs:
508
509* the object is garbage collected,
510* the object's :meth:`remove` method is called, or
511* the program exits.
512
513We might try to implement the class using a :meth:`__del__` method as
514follows::
515
516 class TempDir:
517 def __init__(self):
518 self.name = tempfile.mkdtemp()
519
520 def remove(self):
521 if self.name is not None:
522 shutil.rmtree(self.name)
523 self.name = None
524
525 @property
526 def removed(self):
527 return self.name is None
528
529 def __del__(self):
530 self.remove()
531
532This solution has a couple of serious problems:
533
534* There is no guarantee that the object will be garbage collected
535 before the program exists, so the directory might be left. This is
536 because reference cycles containing an object with a :meth:`__del__`
537 method can never be collected. And even if the :class:`TempDir`
538 object is not itself part of a reference cycle, it may still be kept
539 alive by some unkown uncollectable reference cycle.
540
541* The :meth:`__del__` method may be called at shutdown after the
542 :mod:`shutil` module has been cleaned up, in which case
543 :attr:`shutil.rmtree` will have been replaced by :const:`None`.
544 This will cause the :meth:`__del__` method to fail and the directory
545 will not be removed.
546
547Using finalizers we can avoid these problems::
548
549 class TempDir:
550 def __init__(self):
551 self.name = tempfile.mkdtemp()
552 self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
553
554 def remove(self):
555 self._finalizer()
556
557 @property
558 def removed(self):
559 return not self._finalizer.alive
560
561Defined like this, even if a :class:`TempDir` object is part of a
562reference cycle, that reference cycle can still be garbage collected.
563If the object never gets garbage collected the finalizer will still be
564called at exit.
565
566.. note::
567
568 If you create a finalizer object in a daemonic thread just as the
569 the program exits then there is the possibility that the finalizer
570 does not get called at exit. However, in a daemonic thread
571 :func:`atexit.register`, ``try: ... finally: ...`` and ``with: ...``
572 do not guarantee that cleanup occurs either.