17db96d56Sopenharmony_ci.. _mod-weakref:
27db96d56Sopenharmony_ci
37db96d56Sopenharmony_ci:mod:`weakref` --- Weak references
47db96d56Sopenharmony_ci==================================
57db96d56Sopenharmony_ci
67db96d56Sopenharmony_ci.. module:: weakref
77db96d56Sopenharmony_ci   :synopsis: Support for weak references and weak dictionaries.
87db96d56Sopenharmony_ci
97db96d56Sopenharmony_ci.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
107db96d56Sopenharmony_ci.. moduleauthor:: Neil Schemenauer <nas@arctrix.com>
117db96d56Sopenharmony_ci.. moduleauthor:: Martin von Löwis <martin@loewis.home.cs.tu-berlin.de>
127db96d56Sopenharmony_ci.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
137db96d56Sopenharmony_ci
147db96d56Sopenharmony_ci**Source code:** :source:`Lib/weakref.py`
157db96d56Sopenharmony_ci
167db96d56Sopenharmony_ci--------------
177db96d56Sopenharmony_ci
187db96d56Sopenharmony_ciThe :mod:`weakref` module allows the Python programmer to create :dfn:`weak
197db96d56Sopenharmony_cireferences` to objects.
207db96d56Sopenharmony_ci
217db96d56Sopenharmony_ci.. When making changes to the examples in this file, be sure to update
227db96d56Sopenharmony_ci   Lib/test/test_weakref.py::libreftest too!
237db96d56Sopenharmony_ci
247db96d56Sopenharmony_ciIn the following, the term :dfn:`referent` means the object which is referred to
257db96d56Sopenharmony_ciby a weak reference.
267db96d56Sopenharmony_ci
277db96d56Sopenharmony_ciA weak reference to an object is not enough to keep the object alive: when the
287db96d56Sopenharmony_cionly remaining references to a referent are weak references,
297db96d56Sopenharmony_ci:term:`garbage collection` is free to destroy the referent and reuse its memory
307db96d56Sopenharmony_cifor something else.  However, until the object is actually destroyed the weak
317db96d56Sopenharmony_cireference may return the object even if there are no strong references to it.
327db96d56Sopenharmony_ci
337db96d56Sopenharmony_ciA primary use for weak references is to implement caches or
347db96d56Sopenharmony_cimappings holding large objects, where it's desired that a large object not be
357db96d56Sopenharmony_cikept alive solely because it appears in a cache or mapping.
367db96d56Sopenharmony_ci
377db96d56Sopenharmony_ciFor example, if you have a number of large binary image objects, you may wish to
387db96d56Sopenharmony_ciassociate a name with each.  If you used a Python dictionary to map names to
397db96d56Sopenharmony_ciimages, or images to names, the image objects would remain alive just because
407db96d56Sopenharmony_cithey appeared as values or keys in the dictionaries.  The
417db96d56Sopenharmony_ci:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
427db96d56Sopenharmony_cithe :mod:`weakref` module are an alternative, using weak references to construct
437db96d56Sopenharmony_cimappings that don't keep objects alive solely because they appear in the mapping
447db96d56Sopenharmony_ciobjects.  If, for example, an image object is a value in a
457db96d56Sopenharmony_ci:class:`WeakValueDictionary`, then when the last remaining references to that
467db96d56Sopenharmony_ciimage object are the weak references held by weak mappings, garbage collection
477db96d56Sopenharmony_cican reclaim the object, and its corresponding entries in weak mappings are
487db96d56Sopenharmony_cisimply deleted.
497db96d56Sopenharmony_ci
507db96d56Sopenharmony_ci:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
517db96d56Sopenharmony_ciin their implementation, setting up callback functions on the weak references
527db96d56Sopenharmony_cithat notify the weak dictionaries when a key or value has been reclaimed by
537db96d56Sopenharmony_cigarbage collection.  :class:`WeakSet` implements the :class:`set` interface,
547db96d56Sopenharmony_cibut keeps weak references to its elements, just like a
557db96d56Sopenharmony_ci:class:`WeakKeyDictionary` does.
567db96d56Sopenharmony_ci
577db96d56Sopenharmony_ci:class:`finalize` provides a straight forward way to register a
587db96d56Sopenharmony_cicleanup function to be called when an object is garbage collected.
597db96d56Sopenharmony_ciThis is simpler to use than setting up a callback function on a raw
607db96d56Sopenharmony_ciweak reference, since the module automatically ensures that the finalizer
617db96d56Sopenharmony_ciremains alive until the object is collected.
627db96d56Sopenharmony_ci
637db96d56Sopenharmony_ciMost programs should find that using one of these weak container types
647db96d56Sopenharmony_cior :class:`finalize` is all they need -- it's not usually necessary to
657db96d56Sopenharmony_cicreate your own weak references directly.  The low-level machinery is
667db96d56Sopenharmony_ciexposed by the :mod:`weakref` module for the benefit of advanced uses.
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ciNot all objects can be weakly referenced. Objects which support weak references
697db96d56Sopenharmony_ciinclude class instances, functions written in Python (but not in C), instance methods,
707db96d56Sopenharmony_cisets, frozensets, some :term:`file objects <file object>`, :term:`generators <generator>`,
717db96d56Sopenharmony_citype objects, sockets, arrays, deques, regular expression pattern objects, and code
727db96d56Sopenharmony_ciobjects.
737db96d56Sopenharmony_ci
747db96d56Sopenharmony_ci.. versionchanged:: 3.2
757db96d56Sopenharmony_ci   Added support for thread.lock, threading.Lock, and code objects.
767db96d56Sopenharmony_ci
777db96d56Sopenharmony_ciSeveral built-in types such as :class:`list` and :class:`dict` do not directly
787db96d56Sopenharmony_cisupport weak references but can add support through subclassing::
797db96d56Sopenharmony_ci
807db96d56Sopenharmony_ci   class Dict(dict):
817db96d56Sopenharmony_ci       pass
827db96d56Sopenharmony_ci
837db96d56Sopenharmony_ci   obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable
847db96d56Sopenharmony_ci
857db96d56Sopenharmony_ci.. impl-detail::
867db96d56Sopenharmony_ci
877db96d56Sopenharmony_ci   Other built-in types such as :class:`tuple` and :class:`int` do not support weak
887db96d56Sopenharmony_ci   references even when subclassed.
897db96d56Sopenharmony_ci
907db96d56Sopenharmony_ciExtension types can easily be made to support weak references; see
917db96d56Sopenharmony_ci:ref:`weakref-support`.
927db96d56Sopenharmony_ci
937db96d56Sopenharmony_ciWhen ``__slots__`` are defined for a given type, weak reference support is
947db96d56Sopenharmony_cidisabled unless a ``'__weakref__'`` string is also present in the sequence of
957db96d56Sopenharmony_cistrings in the ``__slots__`` declaration.
967db96d56Sopenharmony_ciSee :ref:`__slots__ documentation <slots>` for details.
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ci.. class:: ref(object[, callback])
997db96d56Sopenharmony_ci
1007db96d56Sopenharmony_ci   Return a weak reference to *object*.  The original object can be retrieved by
1017db96d56Sopenharmony_ci   calling the reference object if the referent is still alive; if the referent is
1027db96d56Sopenharmony_ci   no longer alive, calling the reference object will cause :const:`None` to be
1037db96d56Sopenharmony_ci   returned.  If *callback* is provided and not :const:`None`, and the returned
1047db96d56Sopenharmony_ci   weakref object is still alive, the callback will be called when the object is
1057db96d56Sopenharmony_ci   about to be finalized; the weak reference object will be passed as the only
1067db96d56Sopenharmony_ci   parameter to the callback; the referent will no longer be available.
1077db96d56Sopenharmony_ci
1087db96d56Sopenharmony_ci   It is allowable for many weak references to be constructed for the same object.
1097db96d56Sopenharmony_ci   Callbacks registered for each weak reference will be called from the most
1107db96d56Sopenharmony_ci   recently registered callback to the oldest registered callback.
1117db96d56Sopenharmony_ci
1127db96d56Sopenharmony_ci   Exceptions raised by the callback will be noted on the standard error output,
1137db96d56Sopenharmony_ci   but cannot be propagated; they are handled in exactly the same way as exceptions
1147db96d56Sopenharmony_ci   raised from an object's :meth:`__del__` method.
1157db96d56Sopenharmony_ci
1167db96d56Sopenharmony_ci   Weak references are :term:`hashable` if the *object* is hashable.  They will
1177db96d56Sopenharmony_ci   maintain their hash value even after the *object* was deleted.  If
1187db96d56Sopenharmony_ci   :func:`hash` is called the first time only after the *object* was deleted,
1197db96d56Sopenharmony_ci   the call will raise :exc:`TypeError`.
1207db96d56Sopenharmony_ci
1217db96d56Sopenharmony_ci   Weak references support tests for equality, but not ordering.  If the referents
1227db96d56Sopenharmony_ci   are still alive, two references have the same equality relationship as their
1237db96d56Sopenharmony_ci   referents (regardless of the *callback*).  If either referent has been deleted,
1247db96d56Sopenharmony_ci   the references are equal only if the reference objects are the same object.
1257db96d56Sopenharmony_ci
1267db96d56Sopenharmony_ci   This is a subclassable type rather than a factory function.
1277db96d56Sopenharmony_ci
1287db96d56Sopenharmony_ci   .. attribute:: __callback__
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ci      This read-only attribute returns the callback currently associated to the
1317db96d56Sopenharmony_ci      weakref.  If there is no callback or if the referent of the weakref is
1327db96d56Sopenharmony_ci      no longer alive then this attribute will have value ``None``.
1337db96d56Sopenharmony_ci
1347db96d56Sopenharmony_ci   .. versionchanged:: 3.4
1357db96d56Sopenharmony_ci      Added the :attr:`__callback__` attribute.
1367db96d56Sopenharmony_ci
1377db96d56Sopenharmony_ci
1387db96d56Sopenharmony_ci.. function:: proxy(object[, callback])
1397db96d56Sopenharmony_ci
1407db96d56Sopenharmony_ci   Return a proxy to *object* which uses a weak reference.  This supports use of
1417db96d56Sopenharmony_ci   the proxy in most contexts instead of requiring the explicit dereferencing used
1427db96d56Sopenharmony_ci   with weak reference objects.  The returned object will have a type of either
1437db96d56Sopenharmony_ci   ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
1447db96d56Sopenharmony_ci   callable.  Proxy objects are not :term:`hashable` regardless of the referent; this
1457db96d56Sopenharmony_ci   avoids a number of problems related to their fundamentally mutable nature, and
1467db96d56Sopenharmony_ci   prevents their use as dictionary keys.  *callback* is the same as the parameter
1477db96d56Sopenharmony_ci   of the same name to the :func:`ref` function.
1487db96d56Sopenharmony_ci
1497db96d56Sopenharmony_ci   Accessing an attribute of the proxy object after the referent is
1507db96d56Sopenharmony_ci   garbage collected raises :exc:`ReferenceError`.
1517db96d56Sopenharmony_ci
1527db96d56Sopenharmony_ci   .. versionchanged:: 3.8
1537db96d56Sopenharmony_ci      Extended the operator support on proxy objects to include the matrix
1547db96d56Sopenharmony_ci      multiplication operators ``@`` and ``@=``.
1557db96d56Sopenharmony_ci
1567db96d56Sopenharmony_ci
1577db96d56Sopenharmony_ci.. function:: getweakrefcount(object)
1587db96d56Sopenharmony_ci
1597db96d56Sopenharmony_ci   Return the number of weak references and proxies which refer to *object*.
1607db96d56Sopenharmony_ci
1617db96d56Sopenharmony_ci
1627db96d56Sopenharmony_ci.. function:: getweakrefs(object)
1637db96d56Sopenharmony_ci
1647db96d56Sopenharmony_ci   Return a list of all weak reference and proxy objects which refer to *object*.
1657db96d56Sopenharmony_ci
1667db96d56Sopenharmony_ci
1677db96d56Sopenharmony_ci.. class:: WeakKeyDictionary([dict])
1687db96d56Sopenharmony_ci
1697db96d56Sopenharmony_ci   Mapping class that references keys weakly.  Entries in the dictionary will be
1707db96d56Sopenharmony_ci   discarded when there is no longer a strong reference to the key.  This can be
1717db96d56Sopenharmony_ci   used to associate additional data with an object owned by other parts of an
1727db96d56Sopenharmony_ci   application without adding attributes to those objects.  This can be especially
1737db96d56Sopenharmony_ci   useful with objects that override attribute accesses.
1747db96d56Sopenharmony_ci
1757db96d56Sopenharmony_ci   Note that when a key with equal value to an existing key (but not equal identity)
1767db96d56Sopenharmony_ci   is inserted into the dictionary, it replaces the value but does not replace the
1777db96d56Sopenharmony_ci   existing key. Due to this, when the reference to the original key is deleted, it
1787db96d56Sopenharmony_ci   also deletes the entry in the dictionary::
1797db96d56Sopenharmony_ci
1807db96d56Sopenharmony_ci      >>> class T(str): pass
1817db96d56Sopenharmony_ci      ...
1827db96d56Sopenharmony_ci      >>> k1, k2 = T(), T()
1837db96d56Sopenharmony_ci      >>> d = weakref.WeakKeyDictionary()
1847db96d56Sopenharmony_ci      >>> d[k1] = 1   # d = {k1: 1}
1857db96d56Sopenharmony_ci      >>> d[k2] = 2   # d = {k1: 2}
1867db96d56Sopenharmony_ci      >>> del k1      # d = {}
1877db96d56Sopenharmony_ci
1887db96d56Sopenharmony_ci   A workaround would be to remove the key prior to reassignment::
1897db96d56Sopenharmony_ci
1907db96d56Sopenharmony_ci      >>> class T(str): pass
1917db96d56Sopenharmony_ci      ...
1927db96d56Sopenharmony_ci      >>> k1, k2 = T(), T()
1937db96d56Sopenharmony_ci      >>> d = weakref.WeakKeyDictionary()
1947db96d56Sopenharmony_ci      >>> d[k1] = 1   # d = {k1: 1}
1957db96d56Sopenharmony_ci      >>> del d[k1]
1967db96d56Sopenharmony_ci      >>> d[k2] = 2   # d = {k2: 2}
1977db96d56Sopenharmony_ci      >>> del k1      # d = {k2: 2}
1987db96d56Sopenharmony_ci
1997db96d56Sopenharmony_ci   .. versionchanged:: 3.9
2007db96d56Sopenharmony_ci      Added support for ``|`` and ``|=`` operators, specified in :pep:`584`.
2017db96d56Sopenharmony_ci
2027db96d56Sopenharmony_ci:class:`WeakKeyDictionary` objects have an additional method that
2037db96d56Sopenharmony_ciexposes the internal references directly.  The references are not guaranteed to
2047db96d56Sopenharmony_cibe "live" at the time they are used, so the result of calling the references
2057db96d56Sopenharmony_cineeds to be checked before being used.  This can be used to avoid creating
2067db96d56Sopenharmony_cireferences that will cause the garbage collector to keep the keys around longer
2077db96d56Sopenharmony_cithan needed.
2087db96d56Sopenharmony_ci
2097db96d56Sopenharmony_ci
2107db96d56Sopenharmony_ci.. method:: WeakKeyDictionary.keyrefs()
2117db96d56Sopenharmony_ci
2127db96d56Sopenharmony_ci   Return an iterable of the weak references to the keys.
2137db96d56Sopenharmony_ci
2147db96d56Sopenharmony_ci
2157db96d56Sopenharmony_ci.. class:: WeakValueDictionary([dict])
2167db96d56Sopenharmony_ci
2177db96d56Sopenharmony_ci   Mapping class that references values weakly.  Entries in the dictionary will be
2187db96d56Sopenharmony_ci   discarded when no strong reference to the value exists any more.
2197db96d56Sopenharmony_ci
2207db96d56Sopenharmony_ci   .. versionchanged:: 3.9
2217db96d56Sopenharmony_ci      Added support for ``|`` and ``|=`` operators, as specified in :pep:`584`.
2227db96d56Sopenharmony_ci
2237db96d56Sopenharmony_ci:class:`WeakValueDictionary` objects have an additional method that has the
2247db96d56Sopenharmony_cisame issues as the :meth:`keyrefs` method of :class:`WeakKeyDictionary`
2257db96d56Sopenharmony_ciobjects.
2267db96d56Sopenharmony_ci
2277db96d56Sopenharmony_ci
2287db96d56Sopenharmony_ci.. method:: WeakValueDictionary.valuerefs()
2297db96d56Sopenharmony_ci
2307db96d56Sopenharmony_ci   Return an iterable of the weak references to the values.
2317db96d56Sopenharmony_ci
2327db96d56Sopenharmony_ci
2337db96d56Sopenharmony_ci.. class:: WeakSet([elements])
2347db96d56Sopenharmony_ci
2357db96d56Sopenharmony_ci   Set class that keeps weak references to its elements.  An element will be
2367db96d56Sopenharmony_ci   discarded when no strong reference to it exists any more.
2377db96d56Sopenharmony_ci
2387db96d56Sopenharmony_ci
2397db96d56Sopenharmony_ci.. class:: WeakMethod(method[, callback])
2407db96d56Sopenharmony_ci
2417db96d56Sopenharmony_ci   A custom :class:`ref` subclass which simulates a weak reference to a bound
2427db96d56Sopenharmony_ci   method (i.e., a method defined on a class and looked up on an instance).
2437db96d56Sopenharmony_ci   Since a bound method is ephemeral, a standard weak reference cannot keep
2447db96d56Sopenharmony_ci   hold of it.  :class:`WeakMethod` has special code to recreate the bound
2457db96d56Sopenharmony_ci   method until either the object or the original function dies::
2467db96d56Sopenharmony_ci
2477db96d56Sopenharmony_ci      >>> class C:
2487db96d56Sopenharmony_ci      ...     def method(self):
2497db96d56Sopenharmony_ci      ...         print("method called!")
2507db96d56Sopenharmony_ci      ...
2517db96d56Sopenharmony_ci      >>> c = C()
2527db96d56Sopenharmony_ci      >>> r = weakref.ref(c.method)
2537db96d56Sopenharmony_ci      >>> r()
2547db96d56Sopenharmony_ci      >>> r = weakref.WeakMethod(c.method)
2557db96d56Sopenharmony_ci      >>> r()
2567db96d56Sopenharmony_ci      <bound method C.method of <__main__.C object at 0x7fc859830220>>
2577db96d56Sopenharmony_ci      >>> r()()
2587db96d56Sopenharmony_ci      method called!
2597db96d56Sopenharmony_ci      >>> del c
2607db96d56Sopenharmony_ci      >>> gc.collect()
2617db96d56Sopenharmony_ci      0
2627db96d56Sopenharmony_ci      >>> r()
2637db96d56Sopenharmony_ci      >>>
2647db96d56Sopenharmony_ci
2657db96d56Sopenharmony_ci   *callback* is the same as the parameter of the same name to the :func:`ref` function.
2667db96d56Sopenharmony_ci
2677db96d56Sopenharmony_ci   .. versionadded:: 3.4
2687db96d56Sopenharmony_ci
2697db96d56Sopenharmony_ci.. class:: finalize(obj, func, /, *args, **kwargs)
2707db96d56Sopenharmony_ci
2717db96d56Sopenharmony_ci   Return a callable finalizer object which will be called when *obj*
2727db96d56Sopenharmony_ci   is garbage collected. Unlike an ordinary weak reference, a finalizer
2737db96d56Sopenharmony_ci   will always survive until the reference object is collected, greatly
2747db96d56Sopenharmony_ci   simplifying lifecycle management.
2757db96d56Sopenharmony_ci
2767db96d56Sopenharmony_ci   A finalizer is considered *alive* until it is called (either explicitly
2777db96d56Sopenharmony_ci   or at garbage collection), and after that it is *dead*.  Calling a live
2787db96d56Sopenharmony_ci   finalizer returns the result of evaluating ``func(*arg, **kwargs)``,
2797db96d56Sopenharmony_ci   whereas calling a dead finalizer returns :const:`None`.
2807db96d56Sopenharmony_ci
2817db96d56Sopenharmony_ci   Exceptions raised by finalizer callbacks during garbage collection
2827db96d56Sopenharmony_ci   will be shown on the standard error output, but cannot be
2837db96d56Sopenharmony_ci   propagated.  They are handled in the same way as exceptions raised
2847db96d56Sopenharmony_ci   from an object's :meth:`__del__` method or a weak reference's
2857db96d56Sopenharmony_ci   callback.
2867db96d56Sopenharmony_ci
2877db96d56Sopenharmony_ci   When the program exits, each remaining live finalizer is called
2887db96d56Sopenharmony_ci   unless its :attr:`atexit` attribute has been set to false.  They
2897db96d56Sopenharmony_ci   are called in reverse order of creation.
2907db96d56Sopenharmony_ci
2917db96d56Sopenharmony_ci   A finalizer will never invoke its callback during the later part of
2927db96d56Sopenharmony_ci   the :term:`interpreter shutdown` when module globals are liable to have
2937db96d56Sopenharmony_ci   been replaced by :const:`None`.
2947db96d56Sopenharmony_ci
2957db96d56Sopenharmony_ci   .. method:: __call__()
2967db96d56Sopenharmony_ci
2977db96d56Sopenharmony_ci      If *self* is alive then mark it as dead and return the result of
2987db96d56Sopenharmony_ci      calling ``func(*args, **kwargs)``.  If *self* is dead then return
2997db96d56Sopenharmony_ci      :const:`None`.
3007db96d56Sopenharmony_ci
3017db96d56Sopenharmony_ci   .. method:: detach()
3027db96d56Sopenharmony_ci
3037db96d56Sopenharmony_ci      If *self* is alive then mark it as dead and return the tuple
3047db96d56Sopenharmony_ci      ``(obj, func, args, kwargs)``.  If *self* is dead then return
3057db96d56Sopenharmony_ci      :const:`None`.
3067db96d56Sopenharmony_ci
3077db96d56Sopenharmony_ci   .. method:: peek()
3087db96d56Sopenharmony_ci
3097db96d56Sopenharmony_ci      If *self* is alive then return the tuple ``(obj, func, args,
3107db96d56Sopenharmony_ci      kwargs)``.  If *self* is dead then return :const:`None`.
3117db96d56Sopenharmony_ci
3127db96d56Sopenharmony_ci   .. attribute:: alive
3137db96d56Sopenharmony_ci
3147db96d56Sopenharmony_ci      Property which is true if the finalizer is alive, false otherwise.
3157db96d56Sopenharmony_ci
3167db96d56Sopenharmony_ci   .. attribute:: atexit
3177db96d56Sopenharmony_ci
3187db96d56Sopenharmony_ci      A writable boolean property which by default is true.  When the
3197db96d56Sopenharmony_ci      program exits, it calls all remaining live finalizers for which
3207db96d56Sopenharmony_ci      :attr:`.atexit` is true.  They are called in reverse order of
3217db96d56Sopenharmony_ci      creation.
3227db96d56Sopenharmony_ci
3237db96d56Sopenharmony_ci   .. note::
3247db96d56Sopenharmony_ci
3257db96d56Sopenharmony_ci      It is important to ensure that *func*, *args* and *kwargs* do
3267db96d56Sopenharmony_ci      not own any references to *obj*, either directly or indirectly,
3277db96d56Sopenharmony_ci      since otherwise *obj* will never be garbage collected.  In
3287db96d56Sopenharmony_ci      particular, *func* should not be a bound method of *obj*.
3297db96d56Sopenharmony_ci
3307db96d56Sopenharmony_ci   .. versionadded:: 3.4
3317db96d56Sopenharmony_ci
3327db96d56Sopenharmony_ci
3337db96d56Sopenharmony_ci.. data:: ReferenceType
3347db96d56Sopenharmony_ci
3357db96d56Sopenharmony_ci   The type object for weak references objects.
3367db96d56Sopenharmony_ci
3377db96d56Sopenharmony_ci
3387db96d56Sopenharmony_ci.. data:: ProxyType
3397db96d56Sopenharmony_ci
3407db96d56Sopenharmony_ci   The type object for proxies of objects which are not callable.
3417db96d56Sopenharmony_ci
3427db96d56Sopenharmony_ci
3437db96d56Sopenharmony_ci.. data:: CallableProxyType
3447db96d56Sopenharmony_ci
3457db96d56Sopenharmony_ci   The type object for proxies of callable objects.
3467db96d56Sopenharmony_ci
3477db96d56Sopenharmony_ci
3487db96d56Sopenharmony_ci.. data:: ProxyTypes
3497db96d56Sopenharmony_ci
3507db96d56Sopenharmony_ci   Sequence containing all the type objects for proxies.  This can make it simpler
3517db96d56Sopenharmony_ci   to test if an object is a proxy without being dependent on naming both proxy
3527db96d56Sopenharmony_ci   types.
3537db96d56Sopenharmony_ci
3547db96d56Sopenharmony_ci
3557db96d56Sopenharmony_ci.. seealso::
3567db96d56Sopenharmony_ci
3577db96d56Sopenharmony_ci   :pep:`205` - Weak References
3587db96d56Sopenharmony_ci      The proposal and rationale for this feature, including links to earlier
3597db96d56Sopenharmony_ci      implementations and information about similar features in other languages.
3607db96d56Sopenharmony_ci
3617db96d56Sopenharmony_ci
3627db96d56Sopenharmony_ci.. _weakref-objects:
3637db96d56Sopenharmony_ci
3647db96d56Sopenharmony_ciWeak Reference Objects
3657db96d56Sopenharmony_ci----------------------
3667db96d56Sopenharmony_ci
3677db96d56Sopenharmony_ciWeak reference objects have no methods and no attributes besides
3687db96d56Sopenharmony_ci:attr:`ref.__callback__`. A weak reference object allows the referent to be
3697db96d56Sopenharmony_ciobtained, if it still exists, by calling it:
3707db96d56Sopenharmony_ci
3717db96d56Sopenharmony_ci   >>> import weakref
3727db96d56Sopenharmony_ci   >>> class Object:
3737db96d56Sopenharmony_ci   ...     pass
3747db96d56Sopenharmony_ci   ...
3757db96d56Sopenharmony_ci   >>> o = Object()
3767db96d56Sopenharmony_ci   >>> r = weakref.ref(o)
3777db96d56Sopenharmony_ci   >>> o2 = r()
3787db96d56Sopenharmony_ci   >>> o is o2
3797db96d56Sopenharmony_ci   True
3807db96d56Sopenharmony_ci
3817db96d56Sopenharmony_ciIf the referent no longer exists, calling the reference object returns
3827db96d56Sopenharmony_ci:const:`None`:
3837db96d56Sopenharmony_ci
3847db96d56Sopenharmony_ci   >>> del o, o2
3857db96d56Sopenharmony_ci   >>> print(r())
3867db96d56Sopenharmony_ci   None
3877db96d56Sopenharmony_ci
3887db96d56Sopenharmony_ciTesting that a weak reference object is still live should be done using the
3897db96d56Sopenharmony_ciexpression ``ref() is not None``.  Normally, application code that needs to use
3907db96d56Sopenharmony_cia reference object should follow this pattern::
3917db96d56Sopenharmony_ci
3927db96d56Sopenharmony_ci   # r is a weak reference object
3937db96d56Sopenharmony_ci   o = r()
3947db96d56Sopenharmony_ci   if o is None:
3957db96d56Sopenharmony_ci       # referent has been garbage collected
3967db96d56Sopenharmony_ci       print("Object has been deallocated; can't frobnicate.")
3977db96d56Sopenharmony_ci   else:
3987db96d56Sopenharmony_ci       print("Object is still live!")
3997db96d56Sopenharmony_ci       o.do_something_useful()
4007db96d56Sopenharmony_ci
4017db96d56Sopenharmony_ciUsing a separate test for "liveness" creates race conditions in threaded
4027db96d56Sopenharmony_ciapplications; another thread can cause a weak reference to become invalidated
4037db96d56Sopenharmony_cibefore the weak reference is called; the idiom shown above is safe in threaded
4047db96d56Sopenharmony_ciapplications as well as single-threaded applications.
4057db96d56Sopenharmony_ci
4067db96d56Sopenharmony_ciSpecialized versions of :class:`ref` objects can be created through subclassing.
4077db96d56Sopenharmony_ciThis is used in the implementation of the :class:`WeakValueDictionary` to reduce
4087db96d56Sopenharmony_cithe memory overhead for each entry in the mapping.  This may be most useful to
4097db96d56Sopenharmony_ciassociate additional information with a reference, but could also be used to
4107db96d56Sopenharmony_ciinsert additional processing on calls to retrieve the referent.
4117db96d56Sopenharmony_ci
4127db96d56Sopenharmony_ciThis example shows how a subclass of :class:`ref` can be used to store
4137db96d56Sopenharmony_ciadditional information about an object and affect the value that's returned when
4147db96d56Sopenharmony_cithe referent is accessed::
4157db96d56Sopenharmony_ci
4167db96d56Sopenharmony_ci   import weakref
4177db96d56Sopenharmony_ci
4187db96d56Sopenharmony_ci   class ExtendedRef(weakref.ref):
4197db96d56Sopenharmony_ci       def __init__(self, ob, callback=None, /, **annotations):
4207db96d56Sopenharmony_ci           super().__init__(ob, callback)
4217db96d56Sopenharmony_ci           self.__counter = 0
4227db96d56Sopenharmony_ci           for k, v in annotations.items():
4237db96d56Sopenharmony_ci               setattr(self, k, v)
4247db96d56Sopenharmony_ci
4257db96d56Sopenharmony_ci       def __call__(self):
4267db96d56Sopenharmony_ci           """Return a pair containing the referent and the number of
4277db96d56Sopenharmony_ci           times the reference has been called.
4287db96d56Sopenharmony_ci           """
4297db96d56Sopenharmony_ci           ob = super().__call__()
4307db96d56Sopenharmony_ci           if ob is not None:
4317db96d56Sopenharmony_ci               self.__counter += 1
4327db96d56Sopenharmony_ci               ob = (ob, self.__counter)
4337db96d56Sopenharmony_ci           return ob
4347db96d56Sopenharmony_ci
4357db96d56Sopenharmony_ci
4367db96d56Sopenharmony_ci.. _weakref-example:
4377db96d56Sopenharmony_ci
4387db96d56Sopenharmony_ciExample
4397db96d56Sopenharmony_ci-------
4407db96d56Sopenharmony_ci
4417db96d56Sopenharmony_ciThis simple example shows how an application can use object IDs to retrieve
4427db96d56Sopenharmony_ciobjects that it has seen before.  The IDs of the objects can then be used in
4437db96d56Sopenharmony_ciother data structures without forcing the objects to remain alive, but the
4447db96d56Sopenharmony_ciobjects can still be retrieved by ID if they do.
4457db96d56Sopenharmony_ci
4467db96d56Sopenharmony_ci.. Example contributed by Tim Peters.
4477db96d56Sopenharmony_ci
4487db96d56Sopenharmony_ci::
4497db96d56Sopenharmony_ci
4507db96d56Sopenharmony_ci   import weakref
4517db96d56Sopenharmony_ci
4527db96d56Sopenharmony_ci   _id2obj_dict = weakref.WeakValueDictionary()
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ci   def remember(obj):
4557db96d56Sopenharmony_ci       oid = id(obj)
4567db96d56Sopenharmony_ci       _id2obj_dict[oid] = obj
4577db96d56Sopenharmony_ci       return oid
4587db96d56Sopenharmony_ci
4597db96d56Sopenharmony_ci   def id2obj(oid):
4607db96d56Sopenharmony_ci       return _id2obj_dict[oid]
4617db96d56Sopenharmony_ci
4627db96d56Sopenharmony_ci
4637db96d56Sopenharmony_ci.. _finalize-examples:
4647db96d56Sopenharmony_ci
4657db96d56Sopenharmony_ciFinalizer Objects
4667db96d56Sopenharmony_ci-----------------
4677db96d56Sopenharmony_ci
4687db96d56Sopenharmony_ciThe main benefit of using :class:`finalize` is that it makes it simple
4697db96d56Sopenharmony_cito register a callback without needing to preserve the returned finalizer
4707db96d56Sopenharmony_ciobject.  For instance
4717db96d56Sopenharmony_ci
4727db96d56Sopenharmony_ci    >>> import weakref
4737db96d56Sopenharmony_ci    >>> class Object:
4747db96d56Sopenharmony_ci    ...     pass
4757db96d56Sopenharmony_ci    ...
4767db96d56Sopenharmony_ci    >>> kenny = Object()
4777db96d56Sopenharmony_ci    >>> weakref.finalize(kenny, print, "You killed Kenny!")  #doctest:+ELLIPSIS
4787db96d56Sopenharmony_ci    <finalize object at ...; for 'Object' at ...>
4797db96d56Sopenharmony_ci    >>> del kenny
4807db96d56Sopenharmony_ci    You killed Kenny!
4817db96d56Sopenharmony_ci
4827db96d56Sopenharmony_ciThe finalizer can be called directly as well.  However the finalizer
4837db96d56Sopenharmony_ciwill invoke the callback at most once.
4847db96d56Sopenharmony_ci
4857db96d56Sopenharmony_ci    >>> def callback(x, y, z):
4867db96d56Sopenharmony_ci    ...     print("CALLBACK")
4877db96d56Sopenharmony_ci    ...     return x + y + z
4887db96d56Sopenharmony_ci    ...
4897db96d56Sopenharmony_ci    >>> obj = Object()
4907db96d56Sopenharmony_ci    >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
4917db96d56Sopenharmony_ci    >>> assert f.alive
4927db96d56Sopenharmony_ci    >>> assert f() == 6
4937db96d56Sopenharmony_ci    CALLBACK
4947db96d56Sopenharmony_ci    >>> assert not f.alive
4957db96d56Sopenharmony_ci    >>> f()                     # callback not called because finalizer dead
4967db96d56Sopenharmony_ci    >>> del obj                 # callback not called because finalizer dead
4977db96d56Sopenharmony_ci
4987db96d56Sopenharmony_ciYou can unregister a finalizer using its :meth:`~finalize.detach`
4997db96d56Sopenharmony_cimethod.  This kills the finalizer and returns the arguments passed to
5007db96d56Sopenharmony_cithe constructor when it was created.
5017db96d56Sopenharmony_ci
5027db96d56Sopenharmony_ci    >>> obj = Object()
5037db96d56Sopenharmony_ci    >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
5047db96d56Sopenharmony_ci    >>> f.detach()                                           #doctest:+ELLIPSIS
5057db96d56Sopenharmony_ci    (<...Object object ...>, <function callback ...>, (1, 2), {'z': 3})
5067db96d56Sopenharmony_ci    >>> newobj, func, args, kwargs = _
5077db96d56Sopenharmony_ci    >>> assert not f.alive
5087db96d56Sopenharmony_ci    >>> assert newobj is obj
5097db96d56Sopenharmony_ci    >>> assert func(*args, **kwargs) == 6
5107db96d56Sopenharmony_ci    CALLBACK
5117db96d56Sopenharmony_ci
5127db96d56Sopenharmony_ciUnless you set the :attr:`~finalize.atexit` attribute to
5137db96d56Sopenharmony_ci:const:`False`, a finalizer will be called when the program exits if it
5147db96d56Sopenharmony_ciis still alive.  For instance
5157db96d56Sopenharmony_ci
5167db96d56Sopenharmony_ci.. doctest::
5177db96d56Sopenharmony_ci   :options: +SKIP
5187db96d56Sopenharmony_ci
5197db96d56Sopenharmony_ci   >>> obj = Object()
5207db96d56Sopenharmony_ci   >>> weakref.finalize(obj, print, "obj dead or exiting")
5217db96d56Sopenharmony_ci   <finalize object at ...; for 'Object' at ...>
5227db96d56Sopenharmony_ci   >>> exit()
5237db96d56Sopenharmony_ci   obj dead or exiting
5247db96d56Sopenharmony_ci
5257db96d56Sopenharmony_ci
5267db96d56Sopenharmony_ciComparing finalizers with :meth:`__del__` methods
5277db96d56Sopenharmony_ci-------------------------------------------------
5287db96d56Sopenharmony_ci
5297db96d56Sopenharmony_ciSuppose we want to create a class whose instances represent temporary
5307db96d56Sopenharmony_cidirectories.  The directories should be deleted with their contents
5317db96d56Sopenharmony_ciwhen the first of the following events occurs:
5327db96d56Sopenharmony_ci
5337db96d56Sopenharmony_ci* the object is garbage collected,
5347db96d56Sopenharmony_ci* the object's :meth:`remove` method is called, or
5357db96d56Sopenharmony_ci* the program exits.
5367db96d56Sopenharmony_ci
5377db96d56Sopenharmony_ciWe might try to implement the class using a :meth:`__del__` method as
5387db96d56Sopenharmony_cifollows::
5397db96d56Sopenharmony_ci
5407db96d56Sopenharmony_ci    class TempDir:
5417db96d56Sopenharmony_ci        def __init__(self):
5427db96d56Sopenharmony_ci            self.name = tempfile.mkdtemp()
5437db96d56Sopenharmony_ci
5447db96d56Sopenharmony_ci        def remove(self):
5457db96d56Sopenharmony_ci            if self.name is not None:
5467db96d56Sopenharmony_ci                shutil.rmtree(self.name)
5477db96d56Sopenharmony_ci                self.name = None
5487db96d56Sopenharmony_ci
5497db96d56Sopenharmony_ci        @property
5507db96d56Sopenharmony_ci        def removed(self):
5517db96d56Sopenharmony_ci            return self.name is None
5527db96d56Sopenharmony_ci
5537db96d56Sopenharmony_ci        def __del__(self):
5547db96d56Sopenharmony_ci            self.remove()
5557db96d56Sopenharmony_ci
5567db96d56Sopenharmony_ciStarting with Python 3.4, :meth:`__del__` methods no longer prevent
5577db96d56Sopenharmony_cireference cycles from being garbage collected, and module globals are
5587db96d56Sopenharmony_cino longer forced to :const:`None` during :term:`interpreter shutdown`.
5597db96d56Sopenharmony_ciSo this code should work without any issues on CPython.
5607db96d56Sopenharmony_ci
5617db96d56Sopenharmony_ciHowever, handling of :meth:`__del__` methods is notoriously implementation
5627db96d56Sopenharmony_cispecific, since it depends on internal details of the interpreter's garbage
5637db96d56Sopenharmony_cicollector implementation.
5647db96d56Sopenharmony_ci
5657db96d56Sopenharmony_ciA more robust alternative can be to define a finalizer which only references
5667db96d56Sopenharmony_cithe specific functions and objects that it needs, rather than having access
5677db96d56Sopenharmony_cito the full state of the object::
5687db96d56Sopenharmony_ci
5697db96d56Sopenharmony_ci    class TempDir:
5707db96d56Sopenharmony_ci        def __init__(self):
5717db96d56Sopenharmony_ci            self.name = tempfile.mkdtemp()
5727db96d56Sopenharmony_ci            self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
5737db96d56Sopenharmony_ci
5747db96d56Sopenharmony_ci        def remove(self):
5757db96d56Sopenharmony_ci            self._finalizer()
5767db96d56Sopenharmony_ci
5777db96d56Sopenharmony_ci        @property
5787db96d56Sopenharmony_ci        def removed(self):
5797db96d56Sopenharmony_ci            return not self._finalizer.alive
5807db96d56Sopenharmony_ci
5817db96d56Sopenharmony_ciDefined like this, our finalizer only receives a reference to the details
5827db96d56Sopenharmony_ciit needs to clean up the directory appropriately. If the object never gets
5837db96d56Sopenharmony_cigarbage collected the finalizer will still be called at exit.
5847db96d56Sopenharmony_ci
5857db96d56Sopenharmony_ciThe other advantage of weakref based finalizers is that they can be used to
5867db96d56Sopenharmony_ciregister finalizers for classes where the definition is controlled by a
5877db96d56Sopenharmony_cithird party, such as running code when a module is unloaded::
5887db96d56Sopenharmony_ci
5897db96d56Sopenharmony_ci    import weakref, sys
5907db96d56Sopenharmony_ci    def unloading_module():
5917db96d56Sopenharmony_ci        # implicit reference to the module globals from the function body
5927db96d56Sopenharmony_ci    weakref.finalize(sys.modules[__name__], unloading_module)
5937db96d56Sopenharmony_ci
5947db96d56Sopenharmony_ci
5957db96d56Sopenharmony_ci.. note::
5967db96d56Sopenharmony_ci
5977db96d56Sopenharmony_ci   If you create a finalizer object in a daemonic thread just as the program
5987db96d56Sopenharmony_ci   exits then there is the possibility that the finalizer
5997db96d56Sopenharmony_ci   does not get called at exit.  However, in a daemonic thread
6007db96d56Sopenharmony_ci   :func:`atexit.register`, ``try: ... finally: ...`` and ``with: ...``
6017db96d56Sopenharmony_ci   do not guarantee that cleanup occurs either.
602