1.. _mod-weakref:
2
3:mod:`weakref` --- Weak references
4==================================
5
6.. module:: weakref
7   :synopsis: Support for weak references and weak dictionaries.
8
9.. moduleauthor:: Fred L. Drake, Jr. <[email protected]>
10.. moduleauthor:: Neil Schemenauer <[email protected]>
11.. moduleauthor:: Martin von Löwis <[email protected]>
12.. sectionauthor:: Fred L. Drake, Jr. <[email protected]>
13
14**Source code:** :source:`Lib/weakref.py`
15
16--------------
17
18The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
19references` to objects.
20
21.. When making changes to the examples in this file, be sure to update
22   Lib/test/test_weakref.py::libreftest too!
23
24In the following, the term :dfn:`referent` means the object which is referred to
25by a weak reference.
26
27A weak reference to an object is not enough to keep the object alive: when the
28only remaining references to a referent are weak references,
29:term:`garbage collection` is free to destroy the referent and reuse its memory
30for something else.  However, until the object is actually destroyed the weak
31reference may return the object even if there are no strong references to it.
32
33A primary use for weak references is to implement caches or
34mappings holding large objects, where it's desired that a large object not be
35kept alive solely because it appears in a cache or mapping.
36
37For example, if you have a number of large binary image objects, you may wish to
38associate a name with each.  If you used a Python dictionary to map names to
39images, or images to names, the image objects would remain alive just because
40they appeared as values or keys in the dictionaries.  The
41:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
42the :mod:`weakref` module are an alternative, using weak references to construct
43mappings that don't keep objects alive solely because they appear in the mapping
44objects.  If, for example, an image object is a value in a
45:class:`WeakValueDictionary`, then when the last remaining references to that
46image object are the weak references held by weak mappings, garbage collection
47can reclaim the object, and its corresponding entries in weak mappings are
48simply deleted.
49
50:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
51in their implementation, setting up callback functions on the weak references
52that notify the weak dictionaries when a key or value has been reclaimed by
53garbage collection.  :class:`WeakSet` implements the :class:`set` interface,
54but keeps weak references to its elements, just like a
55:class:`WeakKeyDictionary` does.
56
57:class:`finalize` provides a straight forward way to register a
58cleanup function to be called when an object is garbage collected.
59This is simpler to use than setting up a callback function on a raw
60weak reference, since the module automatically ensures that the finalizer
61remains alive until the object is collected.
62
63Most programs should find that using one of these weak container types
64or :class:`finalize` is all they need -- it's not usually necessary to
65create your own weak references directly.  The low-level machinery is
66exposed by the :mod:`weakref` module for the benefit of advanced uses.
67
68Not all objects can be weakly referenced. Objects which support weak references
69include class instances, functions written in Python (but not in C), instance methods,
70sets, frozensets, some :term:`file objects <file object>`, :term:`generators <generator>`,
71type objects, sockets, arrays, deques, regular expression pattern objects, and code
72objects.
73
74.. versionchanged:: 3.2
75   Added support for thread.lock, threading.Lock, and code objects.
76
77Several built-in types such as :class:`list` and :class:`dict` do not directly
78support weak references but can add support through subclassing::
79
80   class Dict(dict):
81       pass
82
83   obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable
84
85.. impl-detail::
86
87   Other built-in types such as :class:`tuple` and :class:`int` do not support weak
88   references even when subclassed.
89
90Extension types can easily be made to support weak references; see
91:ref:`weakref-support`.
92
93When ``__slots__`` are defined for a given type, weak reference support is
94disabled unless a ``'__weakref__'`` string is also present in the sequence of
95strings in the ``__slots__`` declaration.
96See :ref:`__slots__ documentation <slots>` for details.
97
98.. class:: ref(object[, callback])
99
100   Return a weak reference to *object*.  The original object can be retrieved by
101   calling the reference object if the referent is still alive; if the referent is
102   no longer alive, calling the reference object will cause :const:`None` to be
103   returned.  If *callback* is provided and not :const:`None`, and the returned
104   weakref object is still alive, the callback will be called when the object is
105   about to be finalized; the weak reference object will be passed as the only
106   parameter to the callback; the referent will no longer be available.
107
108   It is allowable for many weak references to be constructed for the same object.
109   Callbacks registered for each weak reference will be called from the most
110   recently registered callback to the oldest registered callback.
111
112   Exceptions raised by the callback will be noted on the standard error output,
113   but cannot be propagated; they are handled in exactly the same way as exceptions
114   raised from an object's :meth:`__del__` method.
115
116   Weak references are :term:`hashable` if the *object* is hashable.  They will
117   maintain their hash value even after the *object* was deleted.  If
118   :func:`hash` is called the first time only after the *object* was deleted,
119   the call will raise :exc:`TypeError`.
120
121   Weak references support tests for equality, but not ordering.  If the referents
122   are still alive, two references have the same equality relationship as their
123   referents (regardless of the *callback*).  If either referent has been deleted,
124   the references are equal only if the reference objects are the same object.
125
126   This is a subclassable type rather than a factory function.
127
128   .. attribute:: __callback__
129
130      This read-only attribute returns the callback currently associated to the
131      weakref.  If there is no callback or if the referent of the weakref is
132      no longer alive then this attribute will have value ``None``.
133
134   .. versionchanged:: 3.4
135      Added the :attr:`__callback__` attribute.
136
137
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
144   callable.  Proxy objects are not :term:`hashable` regardless of the referent; this
145   avoids a number of problems related to their fundamentally mutable nature, and
146   prevents their use as dictionary keys.  *callback* is the same as the parameter
147   of the same name to the :func:`ref` function.
148
149   Accessing an attribute of the proxy object after the referent is
150   garbage collected raises :exc:`ReferenceError`.
151
152   .. versionchanged:: 3.8
153      Extended the operator support on proxy objects to include the matrix
154      multiplication operators ``@`` and ``@=``.
155
156
157.. function:: getweakrefcount(object)
158
159   Return the number of weak references and proxies which refer to *object*.
160
161
162.. function:: getweakrefs(object)
163
164   Return a list of all weak reference and proxy objects which refer to *object*.
165
166
167.. class:: WeakKeyDictionary([dict])
168
169   Mapping class that references keys weakly.  Entries in the dictionary will be
170   discarded when there is no longer a strong reference to the key.  This can be
171   used to associate additional data with an object owned by other parts of an
172   application without adding attributes to those objects.  This can be especially
173   useful with objects that override attribute accesses.
174
175   Note that when a key with equal value to an existing key (but not equal identity)
176   is inserted into the dictionary, it replaces the value but does not replace the
177   existing key. Due to this, when the reference to the original key is deleted, it
178   also deletes the entry in the dictionary::
179
180      >>> class T(str): pass
181      ...
182      >>> k1, k2 = T(), T()
183      >>> d = weakref.WeakKeyDictionary()
184      >>> d[k1] = 1   # d = {k1: 1}
185      >>> d[k2] = 2   # d = {k1: 2}
186      >>> del k1      # d = {}
187
188   A workaround would be to remove the key prior to reassignment::
189
190      >>> class T(str): pass
191      ...
192      >>> k1, k2 = T(), T()
193      >>> d = weakref.WeakKeyDictionary()
194      >>> d[k1] = 1   # d = {k1: 1}
195      >>> del d[k1]
196      >>> d[k2] = 2   # d = {k2: 2}
197      >>> del k1      # d = {k2: 2}
198
199   .. versionchanged:: 3.9
200      Added support for ``|`` and ``|=`` operators, specified in :pep:`584`.
201
202:class:`WeakKeyDictionary` objects have an additional method that
203exposes the internal references directly.  The references are not guaranteed to
204be "live" at the time they are used, so the result of calling the references
205needs to be checked before being used.  This can be used to avoid creating
206references that will cause the garbage collector to keep the keys around longer
207than needed.
208
209
210.. method:: WeakKeyDictionary.keyrefs()
211
212   Return an iterable of the weak references to the keys.
213
214
215.. class:: WeakValueDictionary([dict])
216
217   Mapping class that references values weakly.  Entries in the dictionary will be
218   discarded when no strong reference to the value exists any more.
219
220   .. versionchanged:: 3.9
221      Added support for ``|`` and ``|=`` operators, as specified in :pep:`584`.
222
223:class:`WeakValueDictionary` objects have an additional method that has the
224same issues as the :meth:`keyrefs` method of :class:`WeakKeyDictionary`
225objects.
226
227
228.. method:: WeakValueDictionary.valuerefs()
229
230   Return an iterable of the weak references to the values.
231
232
233.. class:: WeakSet([elements])
234
235   Set class that keeps weak references to its elements.  An element will be
236   discarded when no strong reference to it exists any more.
237
238
239.. class:: WeakMethod(method[, callback])
240
241   A custom :class:`ref` subclass which simulates a weak reference to a bound
242   method (i.e., a method defined on a class and looked up on an instance).
243   Since a bound method is ephemeral, a standard weak reference cannot keep
244   hold of it.  :class:`WeakMethod` has special code to recreate the bound
245   method until either the object or the original function dies::
246
247      >>> class C:
248      ...     def method(self):
249      ...         print("method called!")
250      ...
251      >>> c = C()
252      >>> r = weakref.ref(c.method)
253      >>> r()
254      >>> r = weakref.WeakMethod(c.method)
255      >>> r()
256      <bound method C.method of <__main__.C object at 0x7fc859830220>>
257      >>> r()()
258      method called!
259      >>> del c
260      >>> gc.collect()
261      0
262      >>> r()
263      >>>
264
265   *callback* is the same as the parameter of the same name to the :func:`ref` function.
266
267   .. versionadded:: 3.4
268
269.. class:: finalize(obj, func, /, *args, **kwargs)
270
271   Return a callable finalizer object which will be called when *obj*
272   is garbage collected. Unlike an ordinary weak reference, a finalizer
273   will always survive until the reference object is collected, greatly
274   simplifying lifecycle management.
275
276   A finalizer is considered *alive* until it is called (either explicitly
277   or at garbage collection), and after that it is *dead*.  Calling a live
278   finalizer returns the result of evaluating ``func(*arg, **kwargs)``,
279   whereas calling a dead finalizer returns :const:`None`.
280
281   Exceptions raised by finalizer callbacks during garbage collection
282   will be shown on the standard error output, but cannot be
283   propagated.  They are handled in the same way as exceptions raised
284   from an object's :meth:`__del__` method or a weak reference's
285   callback.
286
287   When the program exits, each remaining live finalizer is called
288   unless its :attr:`atexit` attribute has been set to false.  They
289   are called in reverse order of creation.
290
291   A finalizer will never invoke its callback during the later part of
292   the :term:`interpreter shutdown` when module globals are liable to have
293   been replaced by :const:`None`.
294
295   .. method:: __call__()
296
297      If *self* is alive then mark it as dead and return the result of
298      calling ``func(*args, **kwargs)``.  If *self* is dead then return
299      :const:`None`.
300
301   .. method:: detach()
302
303      If *self* is alive then mark it as dead and return the tuple
304      ``(obj, func, args, kwargs)``.  If *self* is dead then return
305      :const:`None`.
306
307   .. method:: peek()
308
309      If *self* is alive then return the tuple ``(obj, func, args,
310      kwargs)``.  If *self* is dead then return :const:`None`.
311
312   .. attribute:: alive
313
314      Property which is true if the finalizer is alive, false otherwise.
315
316   .. attribute:: atexit
317
318      A writable boolean property which by default is true.  When the
319      program exits, it calls all remaining live finalizers for which
320      :attr:`.atexit` is true.  They are called in reverse order of
321      creation.
322
323   .. note::
324
325      It is important to ensure that *func*, *args* and *kwargs* do
326      not own any references to *obj*, either directly or indirectly,
327      since otherwise *obj* will never be garbage collected.  In
328      particular, *func* should not be a bound method of *obj*.
329
330   .. versionadded:: 3.4
331
332
333.. data:: ReferenceType
334
335   The type object for weak references objects.
336
337
338.. data:: ProxyType
339
340   The type object for proxies of objects which are not callable.
341
342
343.. data:: CallableProxyType
344
345   The type object for proxies of callable objects.
346
347
348.. data:: ProxyTypes
349
350   Sequence containing all the type objects for proxies.  This can make it simpler
351   to test if an object is a proxy without being dependent on naming both proxy
352   types.
353
354
355.. seealso::
356
357   :pep:`205` - Weak References
358      The proposal and rationale for this feature, including links to earlier
359      implementations and information about similar features in other languages.
360
361
362.. _weakref-objects:
363
364Weak Reference Objects
365----------------------
366
367Weak reference objects have no methods and no attributes besides
368:attr:`ref.__callback__`. A weak reference object allows the referent to be
369obtained, if it still exists, by calling it:
370
371   >>> import weakref
372   >>> class Object:
373   ...     pass
374   ...
375   >>> o = Object()
376   >>> r = weakref.ref(o)
377   >>> o2 = r()
378   >>> o is o2
379   True
380
381If the referent no longer exists, calling the reference object returns
382:const:`None`:
383
384   >>> del o, o2
385   >>> print(r())
386   None
387
388Testing that a weak reference object is still live should be done using the
389expression ``ref() is not None``.  Normally, application code that needs to use
390a reference object should follow this pattern::
391
392   # r is a weak reference object
393   o = r()
394   if o is None:
395       # referent has been garbage collected
396       print("Object has been deallocated; can't frobnicate.")
397   else:
398       print("Object is still live!")
399       o.do_something_useful()
400
401Using a separate test for "liveness" creates race conditions in threaded
402applications; another thread can cause a weak reference to become invalidated
403before the weak reference is called; the idiom shown above is safe in threaded
404applications as well as single-threaded applications.
405
406Specialized versions of :class:`ref` objects can be created through subclassing.
407This is used in the implementation of the :class:`WeakValueDictionary` to reduce
408the memory overhead for each entry in the mapping.  This may be most useful to
409associate additional information with a reference, but could also be used to
410insert additional processing on calls to retrieve the referent.
411
412This example shows how a subclass of :class:`ref` can be used to store
413additional information about an object and affect the value that's returned when
414the referent is accessed::
415
416   import weakref
417
418   class ExtendedRef(weakref.ref):
419       def __init__(self, ob, callback=None, /, **annotations):
420           super().__init__(ob, callback)
421           self.__counter = 0
422           for k, v in annotations.items():
423               setattr(self, k, v)
424
425       def __call__(self):
426           """Return a pair containing the referent and the number of
427           times the reference has been called.
428           """
429           ob = super().__call__()
430           if ob is not None:
431               self.__counter += 1
432               ob = (ob, self.__counter)
433           return ob
434
435
436.. _weakref-example:
437
438Example
439-------
440
441This simple example shows how an application can use object IDs to retrieve
442objects that it has seen before.  The IDs of the objects can then be used in
443other data structures without forcing the objects to remain alive, but the
444objects can still be retrieved by ID if they do.
445
446.. Example contributed by Tim Peters.
447
448::
449
450   import weakref
451
452   _id2obj_dict = weakref.WeakValueDictionary()
453
454   def remember(obj):
455       oid = id(obj)
456       _id2obj_dict[oid] = obj
457       return oid
458
459   def id2obj(oid):
460       return _id2obj_dict[oid]
461
462
463.. _finalize-examples:
464
465Finalizer Objects
466-----------------
467
468The main benefit of using :class:`finalize` is that it makes it simple
469to register a callback without needing to preserve the returned finalizer
470object.  For instance
471
472    >>> import weakref
473    >>> class Object:
474    ...     pass
475    ...
476    >>> kenny = Object()
477    >>> weakref.finalize(kenny, print, "You killed Kenny!")  #doctest:+ELLIPSIS
478    <finalize object at ...; for 'Object' at ...>
479    >>> del kenny
480    You killed Kenny!
481
482The finalizer can be called directly as well.  However the finalizer
483will invoke the callback at most once.
484
485    >>> def callback(x, y, z):
486    ...     print("CALLBACK")
487    ...     return x + y + z
488    ...
489    >>> obj = Object()
490    >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
491    >>> assert f.alive
492    >>> assert f() == 6
493    CALLBACK
494    >>> assert not f.alive
495    >>> f()                     # callback not called because finalizer dead
496    >>> del obj                 # callback not called because finalizer dead
497
498You can unregister a finalizer using its :meth:`~finalize.detach`
499method.  This kills the finalizer and returns the arguments passed to
500the constructor when it was created.
501
502    >>> obj = Object()
503    >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
504    >>> f.detach()                                           #doctest:+ELLIPSIS
505    (<...Object object ...>, <function callback ...>, (1, 2), {'z': 3})
506    >>> newobj, func, args, kwargs = _
507    >>> assert not f.alive
508    >>> assert newobj is obj
509    >>> assert func(*args, **kwargs) == 6
510    CALLBACK
511
512Unless you set the :attr:`~finalize.atexit` attribute to
513:const:`False`, a finalizer will be called when the program exits if it
514is still alive.  For instance
515
516.. doctest::
517   :options: +SKIP
518
519   >>> obj = Object()
520   >>> weakref.finalize(obj, print, "obj dead or exiting")
521   <finalize object at ...; for 'Object' at ...>
522   >>> exit()
523   obj dead or exiting
524
525
526Comparing finalizers with :meth:`__del__` methods
527-------------------------------------------------
528
529Suppose we want to create a class whose instances represent temporary
530directories.  The directories should be deleted with their contents
531when the first of the following events occurs:
532
533* the object is garbage collected,
534* the object's :meth:`remove` method is called, or
535* the program exits.
536
537We might try to implement the class using a :meth:`__del__` method as
538follows::
539
540    class TempDir:
541        def __init__(self):
542            self.name = tempfile.mkdtemp()
543
544        def remove(self):
545            if self.name is not None:
546                shutil.rmtree(self.name)
547                self.name = None
548
549        @property
550        def removed(self):
551            return self.name is None
552
553        def __del__(self):
554            self.remove()
555
556Starting with Python 3.4, :meth:`__del__` methods no longer prevent
557reference cycles from being garbage collected, and module globals are
558no longer forced to :const:`None` during :term:`interpreter shutdown`.
559So this code should work without any issues on CPython.
560
561However, handling of :meth:`__del__` methods is notoriously implementation
562specific, since it depends on internal details of the interpreter's garbage
563collector implementation.
564
565A more robust alternative can be to define a finalizer which only references
566the specific functions and objects that it needs, rather than having access
567to the full state of the object::
568
569    class TempDir:
570        def __init__(self):
571            self.name = tempfile.mkdtemp()
572            self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
573
574        def remove(self):
575            self._finalizer()
576
577        @property
578        def removed(self):
579            return not self._finalizer.alive
580
581Defined like this, our finalizer only receives a reference to the details
582it needs to clean up the directory appropriately. If the object never gets
583garbage collected the finalizer will still be called at exit.
584
585The other advantage of weakref based finalizers is that they can be used to
586register finalizers for classes where the definition is controlled by a
587third party, such as running code when a module is unloaded::
588
589    import weakref, sys
590    def unloading_module():
591        # implicit reference to the module globals from the function body
592    weakref.finalize(sys.modules[__name__], unloading_module)
593
594
595.. note::
596
597   If you create a finalizer object in a daemonic thread just as the program
598   exits then there is the possibility that the finalizer
599   does not get called at exit.  However, in a daemonic thread
600   :func:`atexit.register`, ``try: ... finally: ...`` and ``with: ...``
601   do not guarantee that cleanup occurs either.
602