summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fweakref.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/library%2Fweakref.html')
-rw-r--r--devdocs/python~3.12/library%2Fweakref.html223
1 files changed, 223 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fweakref.html b/devdocs/python~3.12/library%2Fweakref.html
new file mode 100644
index 00000000..0fa6dac3
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fweakref.html
@@ -0,0 +1,223 @@
+ <span id="weakref-weak-references"></span><span id="mod-weakref"></span><h1>weakref — Weak references</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/weakref.py">Lib/weakref.py</a></p> <p>The <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code>weakref</code></a> module allows the Python programmer to create <em class="dfn">weak references</em> to objects.</p> <p>In the following, the term <em class="dfn">referent</em> means the object which is referred to by a weak reference.</p> <p>A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, <a class="reference internal" href="../glossary#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.</p> <p>A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.</p> <p>For example, if you have a number of large binary image objects, you may wish to associate a name with each. If you used a Python dictionary to map names to images, or images to names, the image objects would remain alive just because they appeared as values or keys in the dictionaries. The <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code>WeakKeyDictionary</code></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code>WeakValueDictionary</code></a> classes supplied by the <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code>weakref</code></a> module are an alternative, using weak references to construct mappings that don’t keep objects alive solely because they appear in the mapping objects. If, for example, an image object is a value in a <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code>WeakValueDictionary</code></a>, then when the last remaining references to that image object are the weak references held by weak mappings, garbage collection can reclaim the object, and its corresponding entries in weak mappings are simply deleted.</p> <p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code>WeakKeyDictionary</code></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code>WeakValueDictionary</code></a> use weak references in their implementation, setting up callback functions on the weak references that notify the weak dictionaries when a key or value has been reclaimed by garbage collection. <a class="reference internal" href="#weakref.WeakSet" title="weakref.WeakSet"><code>WeakSet</code></a> implements the <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a> interface, but keeps weak references to its elements, just like a <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code>WeakKeyDictionary</code></a> does.</p> <p><a class="reference internal" href="#weakref.finalize" title="weakref.finalize"><code>finalize</code></a> provides a straight forward way to register a cleanup function to be called when an object is garbage collected. This is simpler to use than setting up a callback function on a raw weak reference, since the module automatically ensures that the finalizer remains alive until the object is collected.</p> <p>Most programs should find that using one of these weak container types or <a class="reference internal" href="#weakref.finalize" title="weakref.finalize"><code>finalize</code></a> is all they need – it’s not usually necessary to create your own weak references directly. The low-level machinery is exposed by the <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code>weakref</code></a> module for the benefit of advanced uses.</p> <p>Not all objects can be weakly referenced. Objects which support weak references include class instances, functions written in Python (but not in C), instance methods, sets, frozensets, some <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file objects</span></a>, <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generators</span></a>, type objects, sockets, arrays, deques, regular expression pattern objects, and code objects.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Added support for thread.lock, threading.Lock, and code objects.</p> </div> <p>Several built-in types such as <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> and <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> do not directly support weak references but can add support through subclassing:</p> <pre data-language="python">class Dict(dict):
+ pass
+
+obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
+</pre> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> Other built-in types such as <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> and <a class="reference internal" href="functions#int" title="int"><code>int</code></a> do not support weak references even when subclassed.</p> </div> <p>Extension types can easily be made to support weak references; see <a class="reference internal" href="../extending/newtypes#weakref-support"><span class="std std-ref">Weak Reference Support</span></a>.</p> <p>When <code>__slots__</code> are defined for a given type, weak reference support is disabled unless a <code>'__weakref__'</code> string is also present in the sequence of strings in the <code>__slots__</code> declaration. See <a class="reference internal" href="../reference/datamodel#slots"><span class="std std-ref">__slots__ documentation</span></a> for details.</p> <dl class="py class"> <dt class="sig sig-object py" id="weakref.ref">
+<code>class weakref.ref(object[, callback])</code> </dt> <dd>
+<p>Return a weak reference to <em>object</em>. The original object can be retrieved by calling the reference object if the referent is still alive; if the referent is no longer alive, calling the reference object will cause <a class="reference internal" href="constants#None" title="None"><code>None</code></a> to be returned. If <em>callback</em> is provided and not <a class="reference internal" href="constants#None" title="None"><code>None</code></a>, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available.</p> <p>It is allowable for many weak references to be constructed for the same object. Callbacks registered for each weak reference will be called from the most recently registered callback to the oldest registered callback.</p> <p>Exceptions raised by the callback will be noted on the standard error output, but cannot be propagated; they are handled in exactly the same way as exceptions raised from an object’s <a class="reference internal" href="../reference/datamodel#object.__del__" title="object.__del__"><code>__del__()</code></a> method.</p> <p>Weak references are <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a> if the <em>object</em> is hashable. They will maintain their hash value even after the <em>object</em> was deleted. If <a class="reference internal" href="functions#hash" title="hash"><code>hash()</code></a> is called the first time only after the <em>object</em> was deleted, the call will raise <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> <p>Weak references support tests for equality, but not ordering. If the referents are still alive, two references have the same equality relationship as their referents (regardless of the <em>callback</em>). If either referent has been deleted, the references are equal only if the reference objects are the same object.</p> <p>This is a subclassable type rather than a factory function.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="weakref.ref.__callback__">
+<code>__callback__</code> </dt> <dd>
+<p>This read-only attribute returns the callback currently associated to the weakref. If there is no callback or if the referent of the weakref is no longer alive then this attribute will have value <code>None</code>.</p> </dd>
+</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Added the <a class="reference internal" href="#weakref.ref.__callback__" title="weakref.ref.__callback__"><code>__callback__</code></a> attribute.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="weakref.proxy">
+<code>weakref.proxy(object[, callback])</code> </dt> <dd>
+<p>Return a proxy to <em>object</em> which uses a weak reference. This supports use of the proxy in most contexts instead of requiring the explicit dereferencing used with weak reference objects. The returned object will have a type of either <code>ProxyType</code> or <code>CallableProxyType</code>, depending on whether <em>object</em> is callable. Proxy objects are not <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a> regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevents their use as dictionary keys. <em>callback</em> is the same as the parameter of the same name to the <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code>ref()</code></a> function.</p> <p>Accessing an attribute of the proxy object after the referent is garbage collected raises <a class="reference internal" href="exceptions#ReferenceError" title="ReferenceError"><code>ReferenceError</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Extended the operator support on proxy objects to include the matrix multiplication operators <code>@</code> and <code>@=</code>.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="weakref.getweakrefcount">
+<code>weakref.getweakrefcount(object)</code> </dt> <dd>
+<p>Return the number of weak references and proxies which refer to <em>object</em>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="weakref.getweakrefs">
+<code>weakref.getweakrefs(object)</code> </dt> <dd>
+<p>Return a list of all weak reference and proxy objects which refer to <em>object</em>.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="weakref.WeakKeyDictionary">
+<code>class weakref.WeakKeyDictionary([dict])</code> </dt> <dd>
+<p>Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to associate additional data with an object owned by other parts of an application without adding attributes to those objects. This can be especially useful with objects that override attribute accesses.</p> <p>Note that when a key with equal value to an existing key (but not equal identity) is inserted into the dictionary, it replaces the value but does not replace the existing key. Due to this, when the reference to the original key is deleted, it also deletes the entry in the dictionary:</p> <pre data-language="python">&gt;&gt;&gt; class T(str): pass
+...
+&gt;&gt;&gt; k1, k2 = T(), T()
+&gt;&gt;&gt; d = weakref.WeakKeyDictionary()
+&gt;&gt;&gt; d[k1] = 1 # d = {k1: 1}
+&gt;&gt;&gt; d[k2] = 2 # d = {k1: 2}
+&gt;&gt;&gt; del k1 # d = {}
+</pre> <p>A workaround would be to remove the key prior to reassignment:</p> <pre data-language="python">&gt;&gt;&gt; class T(str): pass
+...
+&gt;&gt;&gt; k1, k2 = T(), T()
+&gt;&gt;&gt; d = weakref.WeakKeyDictionary()
+&gt;&gt;&gt; d[k1] = 1 # d = {k1: 1}
+&gt;&gt;&gt; del d[k1]
+&gt;&gt;&gt; d[k2] = 2 # d = {k2: 2}
+&gt;&gt;&gt; del k1 # d = {k2: 2}
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added support for <code>|</code> and <code>|=</code> operators, specified in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0584/"><strong>PEP 584</strong></a>.</p> </div> </dd>
+</dl> <p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code>WeakKeyDictionary</code></a> objects have an additional method that exposes the internal references directly. The references are not guaranteed to be “live” at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed.</p> <dl class="py method"> <dt class="sig sig-object py" id="weakref.WeakKeyDictionary.keyrefs">
+<code>WeakKeyDictionary.keyrefs()</code> </dt> <dd>
+<p>Return an iterable of the weak references to the keys.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="weakref.WeakValueDictionary">
+<code>class weakref.WeakValueDictionary([dict])</code> </dt> <dd>
+<p>Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists any more.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added support for <code>|</code> and <code>|=</code> operators, as specified in <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0584/"><strong>PEP 584</strong></a>.</p> </div> </dd>
+</dl> <p><a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code>WeakValueDictionary</code></a> objects have an additional method that has the same issues as the <a class="reference internal" href="#weakref.WeakKeyDictionary.keyrefs" title="weakref.WeakKeyDictionary.keyrefs"><code>WeakKeyDictionary.keyrefs()</code></a> method.</p> <dl class="py method"> <dt class="sig sig-object py" id="weakref.WeakValueDictionary.valuerefs">
+<code>WeakValueDictionary.valuerefs()</code> </dt> <dd>
+<p>Return an iterable of the weak references to the values.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="weakref.WeakSet">
+<code>class weakref.WeakSet([elements])</code> </dt> <dd>
+<p>Set class that keeps weak references to its elements. An element will be discarded when no strong reference to it exists any more.</p> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="weakref.WeakMethod">
+<code>class weakref.WeakMethod(method[, callback])</code> </dt> <dd>
+<p>A custom <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code>ref</code></a> subclass which simulates a weak reference to a bound method (i.e., a method defined on a class and looked up on an instance). Since a bound method is ephemeral, a standard weak reference cannot keep hold of it. <a class="reference internal" href="#weakref.WeakMethod" title="weakref.WeakMethod"><code>WeakMethod</code></a> has special code to recreate the bound method until either the object or the original function dies:</p> <pre data-language="python">&gt;&gt;&gt; class C:
+... def method(self):
+... print("method called!")
+...
+&gt;&gt;&gt; c = C()
+&gt;&gt;&gt; r = weakref.ref(c.method)
+&gt;&gt;&gt; r()
+&gt;&gt;&gt; r = weakref.WeakMethod(c.method)
+&gt;&gt;&gt; r()
+&lt;bound method C.method of &lt;__main__.C object at 0x7fc859830220&gt;&gt;
+&gt;&gt;&gt; r()()
+method called!
+&gt;&gt;&gt; del c
+&gt;&gt;&gt; gc.collect()
+0
+&gt;&gt;&gt; r()
+&gt;&gt;&gt;
+</pre> <p><em>callback</em> is the same as the parameter of the same name to the <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code>ref()</code></a> function.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="weakref.finalize">
+<code>class weakref.finalize(obj, func, /, *args, **kwargs)</code> </dt> <dd>
+<p>Return a callable finalizer object which will be called when <em>obj</em> is garbage collected. Unlike an ordinary weak reference, a finalizer will always survive until the reference object is collected, greatly simplifying lifecycle management.</p> <p>A finalizer is considered <em>alive</em> until it is called (either explicitly or at garbage collection), and after that it is <em>dead</em>. Calling a live finalizer returns the result of evaluating <code>func(*arg, **kwargs)</code>, whereas calling a dead finalizer returns <a class="reference internal" href="constants#None" title="None"><code>None</code></a>.</p> <p>Exceptions raised by finalizer callbacks during garbage collection will be shown on the standard error output, but cannot be propagated. They are handled in the same way as exceptions raised from an object’s <a class="reference internal" href="../reference/datamodel#object.__del__" title="object.__del__"><code>__del__()</code></a> method or a weak reference’s callback.</p> <p>When the program exits, each remaining live finalizer is called unless its <a class="reference internal" href="atexit#module-atexit" title="atexit: Register and execute cleanup functions."><code>atexit</code></a> attribute has been set to false. They are called in reverse order of creation.</p> <p>A finalizer will never invoke its callback during the later part of the <a class="reference internal" href="../glossary#term-interpreter-shutdown"><span class="xref std std-term">interpreter shutdown</span></a> when module globals are liable to have been replaced by <a class="reference internal" href="constants#None" title="None"><code>None</code></a>.</p> <dl class="py method"> <dt class="sig sig-object py" id="weakref.finalize.__call__">
+<code>__call__()</code> </dt> <dd>
+<p>If <em>self</em> is alive then mark it as dead and return the result of calling <code>func(*args, **kwargs)</code>. If <em>self</em> is dead then return <a class="reference internal" href="constants#None" title="None"><code>None</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="weakref.finalize.detach">
+<code>detach()</code> </dt> <dd>
+<p>If <em>self</em> is alive then mark it as dead and return the tuple <code>(obj, func, args, kwargs)</code>. If <em>self</em> is dead then return <a class="reference internal" href="constants#None" title="None"><code>None</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="weakref.finalize.peek">
+<code>peek()</code> </dt> <dd>
+<p>If <em>self</em> is alive then return the tuple <code>(obj, func, args,
+kwargs)</code>. If <em>self</em> is dead then return <a class="reference internal" href="constants#None" title="None"><code>None</code></a>.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="weakref.finalize.alive">
+<code>alive</code> </dt> <dd>
+<p>Property which is true if the finalizer is alive, false otherwise.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="weakref.finalize.atexit">
+<code>atexit</code> </dt> <dd>
+<p>A writable boolean property which by default is true. When the program exits, it calls all remaining live finalizers for which <a class="reference internal" href="#weakref.finalize.atexit" title="weakref.finalize.atexit"><code>atexit</code></a> is true. They are called in reverse order of creation.</p> </dd>
+</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>It is important to ensure that <em>func</em>, <em>args</em> and <em>kwargs</em> do not own any references to <em>obj</em>, either directly or indirectly, since otherwise <em>obj</em> will never be garbage collected. In particular, <em>func</em> should not be a bound method of <em>obj</em>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="weakref.ReferenceType">
+<code>weakref.ReferenceType</code> </dt> <dd>
+<p>The type object for weak references objects.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="weakref.ProxyType">
+<code>weakref.ProxyType</code> </dt> <dd>
+<p>The type object for proxies of objects which are not callable.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="weakref.CallableProxyType">
+<code>weakref.CallableProxyType</code> </dt> <dd>
+<p>The type object for proxies of callable objects.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="weakref.ProxyTypes">
+<code>weakref.ProxyTypes</code> </dt> <dd>
+<p>Sequence containing all the type objects for proxies. This can make it simpler to test if an object is a proxy without being dependent on naming both proxy types.</p> </dd>
+</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
+<span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0205/"><strong>PEP 205</strong></a> - Weak References</dt>
+<dd>
+<p>The proposal and rationale for this feature, including links to earlier implementations and information about similar features in other languages.</p> </dd> </dl> </div> <section id="weak-reference-objects"> <span id="weakref-objects"></span><h2>Weak Reference Objects</h2> <p>Weak reference objects have no methods and no attributes besides <a class="reference internal" href="#weakref.ref.__callback__" title="weakref.ref.__callback__"><code>ref.__callback__</code></a>. A weak reference object allows the referent to be obtained, if it still exists, by calling it:</p> <pre data-language="python">&gt;&gt;&gt; import weakref
+&gt;&gt;&gt; class Object:
+... pass
+...
+&gt;&gt;&gt; o = Object()
+&gt;&gt;&gt; r = weakref.ref(o)
+&gt;&gt;&gt; o2 = r()
+&gt;&gt;&gt; o is o2
+True
+</pre> <p>If the referent no longer exists, calling the reference object returns <a class="reference internal" href="constants#None" title="None"><code>None</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; del o, o2
+&gt;&gt;&gt; print(r())
+None
+</pre> <p>Testing that a weak reference object is still live should be done using the expression <code>ref() is not None</code>. Normally, application code that needs to use a reference object should follow this pattern:</p> <pre data-language="python"># r is a weak reference object
+o = r()
+if o is None:
+ # referent has been garbage collected
+ print("Object has been deallocated; can't frobnicate.")
+else:
+ print("Object is still live!")
+ o.do_something_useful()
+</pre> <p>Using a separate test for “liveness” creates race conditions in threaded applications; another thread can cause a weak reference to become invalidated before the weak reference is called; the idiom shown above is safe in threaded applications as well as single-threaded applications.</p> <p>Specialized versions of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code>ref</code></a> objects can be created through subclassing. This is used in the implementation of the <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code>WeakValueDictionary</code></a> to reduce the memory overhead for each entry in the mapping. This may be most useful to associate additional information with a reference, but could also be used to insert additional processing on calls to retrieve the referent.</p> <p>This example shows how a subclass of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code>ref</code></a> can be used to store additional information about an object and affect the value that’s returned when the referent is accessed:</p> <pre data-language="python">import weakref
+
+class ExtendedRef(weakref.ref):
+ def __init__(self, ob, callback=None, /, **annotations):
+ super().__init__(ob, callback)
+ self.__counter = 0
+ for k, v in annotations.items():
+ setattr(self, k, v)
+
+ def __call__(self):
+ """Return a pair containing the referent and the number of
+ times the reference has been called.
+ """
+ ob = super().__call__()
+ if ob is not None:
+ self.__counter += 1
+ ob = (ob, self.__counter)
+ return ob
+</pre> </section> <section id="example"> <span id="weakref-example"></span><h2>Example</h2> <p>This simple example shows how an application can use object IDs to retrieve objects that it has seen before. The IDs of the objects can then be used in other data structures without forcing the objects to remain alive, but the objects can still be retrieved by ID if they do.</p> <pre data-language="python">import weakref
+
+_id2obj_dict = weakref.WeakValueDictionary()
+
+def remember(obj):
+ oid = id(obj)
+ _id2obj_dict[oid] = obj
+ return oid
+
+def id2obj(oid):
+ return _id2obj_dict[oid]
+</pre> </section> <section id="finalizer-objects"> <span id="finalize-examples"></span><h2>Finalizer Objects</h2> <p>The main benefit of using <a class="reference internal" href="#weakref.finalize" title="weakref.finalize"><code>finalize</code></a> is that it makes it simple to register a callback without needing to preserve the returned finalizer object. For instance</p> <pre data-language="python">&gt;&gt;&gt; import weakref
+&gt;&gt;&gt; class Object:
+... pass
+...
+&gt;&gt;&gt; kenny = Object()
+&gt;&gt;&gt; weakref.finalize(kenny, print, "You killed Kenny!")
+&lt;finalize object at ...; for 'Object' at ...&gt;
+&gt;&gt;&gt; del kenny
+You killed Kenny!
+</pre> <p>The finalizer can be called directly as well. However the finalizer will invoke the callback at most once.</p> <pre data-language="python">&gt;&gt;&gt; def callback(x, y, z):
+... print("CALLBACK")
+... return x + y + z
+...
+&gt;&gt;&gt; obj = Object()
+&gt;&gt;&gt; f = weakref.finalize(obj, callback, 1, 2, z=3)
+&gt;&gt;&gt; assert f.alive
+&gt;&gt;&gt; assert f() == 6
+CALLBACK
+&gt;&gt;&gt; assert not f.alive
+&gt;&gt;&gt; f() # callback not called because finalizer dead
+&gt;&gt;&gt; del obj # callback not called because finalizer dead
+</pre> <p>You can unregister a finalizer using its <a class="reference internal" href="#weakref.finalize.detach" title="weakref.finalize.detach"><code>detach()</code></a> method. This kills the finalizer and returns the arguments passed to the constructor when it was created.</p> <pre data-language="python">&gt;&gt;&gt; obj = Object()
+&gt;&gt;&gt; f = weakref.finalize(obj, callback, 1, 2, z=3)
+&gt;&gt;&gt; f.detach()
+(&lt;...Object object ...&gt;, &lt;function callback ...&gt;, (1, 2), {'z': 3})
+&gt;&gt;&gt; newobj, func, args, kwargs = _
+&gt;&gt;&gt; assert not f.alive
+&gt;&gt;&gt; assert newobj is obj
+&gt;&gt;&gt; assert func(*args, **kwargs) == 6
+CALLBACK
+</pre> <p>Unless you set the <a class="reference internal" href="#weakref.finalize.atexit" title="weakref.finalize.atexit"><code>atexit</code></a> attribute to <a class="reference internal" href="constants#False" title="False"><code>False</code></a>, a finalizer will be called when the program exits if it is still alive. For instance</p> <pre data-language="pycon3">&gt;&gt;&gt; obj = Object()
+&gt;&gt;&gt; weakref.finalize(obj, print, "obj dead or exiting")
+&lt;finalize object at ...; for 'Object' at ...&gt;
+&gt;&gt;&gt; exit()
+obj dead or exiting
+</pre> </section> <section id="comparing-finalizers-with-del-methods"> <h2>Comparing finalizers with __del__() methods</h2> <p>Suppose we want to create a class whose instances represent temporary directories. The directories should be deleted with their contents when the first of the following events occurs:</p> <ul class="simple"> <li>the object is garbage collected,</li> <li>the object’s <code>remove()</code> method is called, or</li> <li>the program exits.</li> </ul> <p>We might try to implement the class using a <a class="reference internal" href="../reference/datamodel#object.__del__" title="object.__del__"><code>__del__()</code></a> method as follows:</p> <pre data-language="python">class TempDir:
+ def __init__(self):
+ self.name = tempfile.mkdtemp()
+
+ def remove(self):
+ if self.name is not None:
+ shutil.rmtree(self.name)
+ self.name = None
+
+ @property
+ def removed(self):
+ return self.name is None
+
+ def __del__(self):
+ self.remove()
+</pre> <p>Starting with Python 3.4, <a class="reference internal" href="../reference/datamodel#object.__del__" title="object.__del__"><code>__del__()</code></a> methods no longer prevent reference cycles from being garbage collected, and module globals are no longer forced to <a class="reference internal" href="constants#None" title="None"><code>None</code></a> during <a class="reference internal" href="../glossary#term-interpreter-shutdown"><span class="xref std std-term">interpreter shutdown</span></a>. So this code should work without any issues on CPython.</p> <p>However, handling of <a class="reference internal" href="../reference/datamodel#object.__del__" title="object.__del__"><code>__del__()</code></a> methods is notoriously implementation specific, since it depends on internal details of the interpreter’s garbage collector implementation.</p> <p>A more robust alternative can be to define a finalizer which only references the specific functions and objects that it needs, rather than having access to the full state of the object:</p> <pre data-language="python">class TempDir:
+ def __init__(self):
+ self.name = tempfile.mkdtemp()
+ self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
+
+ def remove(self):
+ self._finalizer()
+
+ @property
+ def removed(self):
+ return not self._finalizer.alive
+</pre> <p>Defined like this, our finalizer only receives a reference to the details it needs to clean up the directory appropriately. If the object never gets garbage collected the finalizer will still be called at exit.</p> <p>The other advantage of weakref based finalizers is that they can be used to register finalizers for classes where the definition is controlled by a third party, such as running code when a module is unloaded:</p> <pre data-language="python">import weakref, sys
+def unloading_module():
+ # implicit reference to the module globals from the function body
+weakref.finalize(sys.modules[__name__], unloading_module)
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If you create a finalizer object in a daemonic thread just as the program exits then there is the possibility that the finalizer does not get called at exit. However, in a daemonic thread <a class="reference internal" href="atexit#atexit.register" title="atexit.register"><code>atexit.register()</code></a>, <code>try: ... finally: ...</code> and <code>with: ...</code> do not guarantee that cleanup occurs either.</p> </div> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/weakref.html" class="_attribution-link">https://docs.python.org/3.12/library/weakref.html</a>
+ </p>
+</div>