parthtamu/rag-code-assistant
0
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4 <head>5 <meta charset="utf-8" />6 <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="weakref — Weak references" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/weakref.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/weakref.py The weakref module allows the Python programmer to create weak references to objects. In the following, the term referent means the object which is referred to by a weak..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_weakref_88301ee3.png" />15<meta property="og:image:alt" content="Source code: Lib/weakref.py The weakref module allows the Python programmer to create weak references to objects. In the following, the term referent means the object which is referred to by a weak..." />16<meta name="description" content="Source code: Lib/weakref.py The weakref module allows the Python programmer to create weak references to objects. In the following, the term referent means the object which is referred to by a weak..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20 <title>weakref — Weak references — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21 22 <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23 <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24 <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25 <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26 <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27 28 <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29 <script src="../_static/doctools.js?v=9bcbadda"></script>30 <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31 <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32 33 <script src="../_static/sidebar.js"></script>34 35 <link rel="search" type="application/opensearchdescription+xml"36 title="Search within Python 3.15.0a6 documentation"37 href="../_static/opensearch.xml"/>38 <link rel="author" title="About these documents" href="../about.html" />39 <link rel="index" title="Index" href="../genindex.html" />40 <link rel="search" title="Search" href="../search.html" />41 <link rel="copyright" title="Copyright" href="../copyright.html" />42 <link rel="next" title="types — Dynamic type creation and names for built-in types" href="types.html" />43 <link rel="prev" title="array — Efficient arrays of numeric values" href="array.html" />44 45 46 <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47 48 <link rel="canonical" href="https://docs.python.org/3/library/weakref.html">49 50 51 52 53 <style>54 @media only screen {55 table.full-width-table {56 width: 100%;57 }58 }59 </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61 <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62 <script type="text/javascript" src="../_static/copybutton.js"></script>63 <script type="text/javascript" src="../_static/menu.js"></script>64 <script type="text/javascript" src="../_static/search-focus.js"></script>65 <script type="text/javascript" src="../_static/themetoggle.js"></script> 66 <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67 <meta name="readthedocs-addons-api-version" content="1">68 69 </head>70<body>71<div class="mobile-nav">72 <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73 aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74 <nav class="nav-content" role="navigation">75 <label for="menuToggler" class="toggler__label">76 <span></span>77 </label>78 <span class="nav-items-wrapper">79 <a href="https://www.python.org/" class="nav-logo">80 <img src="../_static/py.svg" alt="Python logo">81 </a>82 <span class="version_switcher_placeholder"></span>83 <form role="search" class="search" action="../search.html" method="get">84 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85 <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86 </svg>87 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88 <input type="submit" value="Go">89 </form>90 </span>91 </nav>92 <div class="menu-wrapper">93 <nav class="menu" role="navigation" aria-label="main navigation">94 <div class="language_switcher_placeholder"></div>95 96<label class="theme-selector-label">97 Theme98 <select class="theme-selector" oninput="activateTheme(this.value)">99 <option value="auto" selected>Auto</option>100 <option value="light">Light</option>101 <option value="dark">Dark</option>102 </select>103</label>104 <div>105 <h3><a href="../contents.html">Table of Contents</a></h3>106 <ul>107<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a><ul>108<li><a class="reference internal" href="#weak-reference-objects">Weak Reference Objects</a></li>109<li><a class="reference internal" href="#example">Example</a></li>110<li><a class="reference internal" href="#finalizer-objects">Finalizer Objects</a></li>111<li><a class="reference internal" href="#comparing-finalizers-with-del-methods">Comparing finalizers with <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> methods</a></li>112</ul>113</li>114</ul>115 116 </div>117 <div>118 <h4>Previous topic</h4>119 <p class="topless"><a href="array.html"120 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></p>121 </div>122 <div>123 <h4>Next topic</h4>124 <p class="topless"><a href="types.html"125 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code> — Dynamic type creation and names for built-in types</a></p>126 </div>127 <script>128 document.addEventListener('DOMContentLoaded', () => {129 const title = document.querySelector('meta[property="og:title"]').content;130 const elements = document.querySelectorAll('.improvepage');131 const pageurl = window.location.href.split('?')[0];132 elements.forEach(element => {133 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));134 url.searchParams.set('pagetitle', title);135 url.searchParams.set('pageurl', pageurl);136 url.searchParams.set('pagesource', "library/weakref.rst");137 element.href = url.toString();138 });139 });140 </script>141 <div role="note" aria-label="source link">142 <h3>This page</h3>143 <ul class="this-page-menu">144 <li><a href="../bugs.html">Report a bug</a></li>145 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>146 <li>147 <a href="https://github.com/python/cpython/blob/main/Doc/library/weakref.rst?plain=1"148 rel="nofollow">Show source149 </a>150 </li>151 152 </ul>153 </div>154 </nav>155 </div>156</div>157 158 159 <div class="related" role="navigation" aria-label="Related">160 <h3>Navigation</h3>161 <ul>162 <li class="right" style="margin-right: 10px">163 <a href="../genindex.html" title="General Index"164 accesskey="I">index</a></li>165 <li class="right" >166 <a href="../py-modindex.html" title="Python Module Index"167 >modules</a> |</li>168 <li class="right" >169 <a href="types.html" title="types — Dynamic type creation and names for built-in types"170 accesskey="N">next</a> |</li>171 <li class="right" >172 <a href="array.html" title="array — Efficient arrays of numeric values"173 accesskey="P">previous</a> |</li>174 175 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>176 <li><a href="https://www.python.org/">Python</a> »</li>177 <li class="switchers">178 <div class="language_switcher_placeholder"></div>179 <div class="version_switcher_placeholder"></div>180 </li>181 <li>182 183 </li>184 <li id="cpython-language-and-version">185 <a href="../index.html">3.15.0a6 Documentation</a> »186 </li>187 188 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>189 <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">Data Types</a> »</li>190 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a></li>191 <li class="right">192 193 194 <div class="inline-search" role="search">195 <form class="inline-search" action="../search.html" method="get">196 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">197 <input type="submit" value="Go">198 </form>199 </div>200 |201 </li>202 <li class="right">203<label class="theme-selector-label">204 Theme205 <select class="theme-selector" oninput="activateTheme(this.value)">206 <option value="auto" selected>Auto</option>207 <option value="light">Light</option>208 <option value="dark">Dark</option>209 </select>210</label> |</li>211 212 </ul>213 </div> 214 215 <div class="document">216 <div class="documentwrapper">217 <div class="bodywrapper">218 <div class="body" role="main">219 220 <section id="module-weakref">221<span id="weakref-weak-references"></span><span id="mod-weakref"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references<a class="headerlink" href="#module-weakref" title="Link to this heading">¶</a></h1>222<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/weakref.py">Lib/weakref.py</a></p>223<hr class="docutils" />224<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> module allows the Python programmer to create <em class="dfn">weak225references</em> to objects.</p>226<p>In the following, the term <em class="dfn">referent</em> means the object which is referred to227by a weak reference.</p>228<p>A weak reference to an object is not enough to keep the object alive: when the229only remaining references to a referent are weak references,230<a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> is free to destroy the referent and reuse its memory231for something else. However, until the object is actually destroyed the weak232reference may return the object even if there are no strong references to it.</p>233<p>A primary use for weak references is to implement caches or234mappings holding large objects, where it’s desired that a large object not be235kept alive solely because it appears in a cache or mapping.</p>236<p>For example, if you have a number of large binary image objects, you may wish to237associate a name with each. If you used a Python dictionary to map names to238images, or images to names, the image objects would remain alive just because239they appeared as values or keys in the dictionaries. The240<a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> classes supplied by241the <code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> module are an alternative, using weak references to construct242mappings that don’t keep objects alive solely because they appear in the mapping243objects. If, for example, an image object is a value in a244<code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code>, then when the last remaining references to that245image object are the weak references held by weak mappings, garbage collection246can reclaim the object, and its corresponding entries in weak mappings are247simply deleted.</p>248<p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> use weak references249in their implementation, setting up callback functions on the weak references250that notify the weak dictionaries when a key or value has been reclaimed by251garbage collection. <a class="reference internal" href="#weakref.WeakSet" title="weakref.WeakSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakSet</span></code></a> implements the <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> interface,252but keeps weak references to its elements, just like a253<code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code> does.</p>254<p><a class="reference internal" href="#weakref.finalize" title="weakref.finalize"><code class="xref py py-class docutils literal notranslate"><span class="pre">finalize</span></code></a> provides a straight forward way to register a255cleanup function to be called when an object is garbage collected.256This is simpler to use than setting up a callback function on a raw257weak reference, since the module automatically ensures that the finalizer258remains alive until the object is collected.</p>259<p>Most programs should find that using one of these weak container types260or <a class="reference internal" href="#weakref.finalize" title="weakref.finalize"><code class="xref py py-class docutils literal notranslate"><span class="pre">finalize</span></code></a> is all they need – it’s not usually necessary to261create your own weak references directly. The low-level machinery is262exposed by the <code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> module for the benefit of advanced uses.</p>263<p>Not all objects can be weakly referenced. Objects which support weak references264include class instances, functions written in Python (but not in C), instance methods,265sets, frozensets, some <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file objects</span></a>, <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generators</span></a>,266type objects, sockets, arrays, deques, regular expression pattern objects, and code267objects.</p>268<div class="versionchanged">269<p><span class="versionmodified changed">Changed in version 3.2: </span>Added support for thread.lock, threading.Lock, and code objects.</p>270</div>271<p>Several built-in types such as <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> and <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> do not directly272support weak references but can add support through subclassing:</p>273<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Dict</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>274 <span class="k">pass</span>275 276<span class="n">obj</span> <span class="o">=</span> <span class="n">Dict</span><span class="p">(</span><span class="n">red</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">green</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">blue</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="c1"># this object is weak referenceable</span>277</pre></div>278</div>279<div class="impl-detail compound">280<p><strong>CPython implementation detail:</strong> Other built-in types such as <a class="reference internal" href="stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> and <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> do not support weak281references even when subclassed.</p>282</div>283<p>Extension types can easily be made to support weak references; see284<a class="reference internal" href="../extending/newtypes.html#weakref-support"><span class="std std-ref">Weak Reference Support</span></a>.</p>285<p>When <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> are defined for a given type, weak reference support is286disabled unless a <code class="docutils literal notranslate"><span class="pre">'__weakref__'</span></code> string is also present in the sequence of287strings in the <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> declaration.288See <a class="reference internal" href="../reference/datamodel.html#slots"><span class="std std-ref">__slots__ documentation</span></a> for details.</p>289<dl class="py class">290<dt class="sig sig-object py" id="weakref.ref">291<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">ref</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">object</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">callback</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.ref" title="Link to this definition">¶</a></dt>292<dd><p>Return a weak reference to <em>object</em>. The original object can be retrieved by293calling the reference object if the referent is still alive; if the referent is294no longer alive, calling the reference object will cause <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> to be295returned. If <em>callback</em> is provided and not <code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code>, and the returned296weakref object is still alive, the callback will be called when the object is297about to be finalized; the weak reference object will be passed as the only298parameter to the callback; the referent will no longer be available.</p>299<p>It is allowable for many weak references to be constructed for the same object.300Callbacks registered for each weak reference will be called from the most301recently registered callback to the oldest registered callback.</p>302<p>Exceptions raised by the callback will be noted on the standard error output,303but cannot be propagated; they are handled in exactly the same way as exceptions304raised from an object’s <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method.</p>305<p>Weak references are <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> if the <em>object</em> is hashable. They will306maintain their hash value even after the <em>object</em> was deleted. If307<a class="reference internal" href="functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> is called the first time only after the <em>object</em> was deleted,308the call will raise <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>309<p>Weak references support tests for equality, but not ordering. If the referents310are still alive, two references have the same equality relationship as their311referents (regardless of the <em>callback</em>). If either referent has been deleted,312the references are equal only if the reference objects are the same object.</p>313<p>This is a subclassable type rather than a factory function.</p>314<dl class="py attribute">315<dt class="sig sig-object py" id="weakref.ref.__callback__">316<span class="sig-name descname"><span class="pre">__callback__</span></span><a class="headerlink" href="#weakref.ref.__callback__" title="Link to this definition">¶</a></dt>317<dd><p>This read-only attribute returns the callback currently associated to the318weakref. If there is no callback or if the referent of the weakref is319no longer alive then this attribute will have value <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>320</dd></dl>321 322<div class="versionchanged">323<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 class="xref py py-attr docutils literal notranslate"><span class="pre">__callback__</span></code></a> attribute.</p>324</div>325</dd></dl>326 327<dl class="py function">328<dt class="sig sig-object py" id="weakref.proxy">329<span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">proxy</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">object</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">callback</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.proxy" title="Link to this definition">¶</a></dt>330<dd><p>Return a proxy to <em>object</em> which uses a weak reference. This supports use of331the proxy in most contexts instead of requiring the explicit dereferencing used332with weak reference objects. The returned object will have a type of either333<code class="docutils literal notranslate"><span class="pre">ProxyType</span></code> or <code class="docutils literal notranslate"><span class="pre">CallableProxyType</span></code>, depending on whether <em>object</em> is334callable. Proxy objects are not <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> regardless of the referent; this335avoids a number of problems related to their fundamentally mutable nature, and336prevents their use as dictionary keys. <em>callback</em> is the same as the parameter337of the same name to the <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code class="xref py py-func docutils literal notranslate"><span class="pre">ref()</span></code></a> function.</p>338<p>Accessing an attribute of the proxy object after the referent is339garbage collected raises <a class="reference internal" href="exceptions.html#ReferenceError" title="ReferenceError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ReferenceError</span></code></a>.</p>340<div class="versionchanged">341<p><span class="versionmodified changed">Changed in version 3.8: </span>Extended the operator support on proxy objects to include the matrix342multiplication operators <code class="docutils literal notranslate"><span class="pre">@</span></code> and <code class="docutils literal notranslate"><span class="pre">@=</span></code>.</p>343</div>344</dd></dl>345 346<dl class="py function">347<dt class="sig sig-object py" id="weakref.getweakrefcount">348<span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">getweakrefcount</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">object</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#weakref.getweakrefcount" title="Link to this definition">¶</a></dt>349<dd><p>Return the number of weak references and proxies which refer to <em>object</em>.</p>350</dd></dl>351 352<dl class="py function">353<dt class="sig sig-object py" id="weakref.getweakrefs">354<span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">getweakrefs</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">object</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#weakref.getweakrefs" title="Link to this definition">¶</a></dt>355<dd><p>Return a list of all weak reference and proxy objects which refer to <em>object</em>.</p>356</dd></dl>357 358<dl class="py class">359<dt class="sig sig-object py" id="weakref.WeakKeyDictionary">360<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">WeakKeyDictionary</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">dict</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakKeyDictionary" title="Link to this definition">¶</a></dt>361<dd><p>Mapping class that references keys weakly. Entries in the dictionary will be362discarded when there is no longer a strong reference to the key. This can be363used to associate additional data with an object owned by other parts of an364application without adding attributes to those objects. This can be especially365useful with objects that override attribute accesses.</p>366<p>Note that when a key with equal value to an existing key (but not equal identity)367is inserted into the dictionary, it replaces the value but does not replace the368existing key. Due to this, when the reference to the original key is deleted, it369also deletes the entry in the dictionary:</p>370<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">T</span><span class="p">(</span><span class="nb">str</span><span class="p">):</span> <span class="k">pass</span>371<span class="gp">...</span>372<span class="gp">>>> </span><span class="n">k1</span><span class="p">,</span> <span class="n">k2</span> <span class="o">=</span> <span class="n">T</span><span class="p">(),</span> <span class="n">T</span><span class="p">()</span>373<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakKeyDictionary</span><span class="p">()</span>374<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="n">k1</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># d = {k1: 1}</span>375<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="n">k2</span><span class="p">]</span> <span class="o">=</span> <span class="mi">2</span> <span class="c1"># d = {k1: 2}</span>376<span class="gp">>>> </span><span class="k">del</span> <span class="n">k1</span> <span class="c1"># d = {}</span>377</pre></div>378</div>379<p>A workaround would be to remove the key prior to reassignment:</p>380<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">T</span><span class="p">(</span><span class="nb">str</span><span class="p">):</span> <span class="k">pass</span>381<span class="gp">...</span>382<span class="gp">>>> </span><span class="n">k1</span><span class="p">,</span> <span class="n">k2</span> <span class="o">=</span> <span class="n">T</span><span class="p">(),</span> <span class="n">T</span><span class="p">()</span>383<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakKeyDictionary</span><span class="p">()</span>384<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="n">k1</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># d = {k1: 1}</span>385<span class="gp">>>> </span><span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="n">k1</span><span class="p">]</span>386<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="n">k2</span><span class="p">]</span> <span class="o">=</span> <span class="mi">2</span> <span class="c1"># d = {k2: 2}</span>387<span class="gp">>>> </span><span class="k">del</span> <span class="n">k1</span> <span class="c1"># d = {k2: 2}</span>388</pre></div>389</div>390<div class="versionchanged">391<p><span class="versionmodified changed">Changed in version 3.9: </span>Added support for <code class="docutils literal notranslate"><span class="pre">|</span></code> and <code class="docutils literal notranslate"><span class="pre">|=</span></code> operators, as 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>392</div>393</dd></dl>394 395<p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> objects have an additional method that396exposes the internal references directly. The references are not guaranteed to397be “live” at the time they are used, so the result of calling the references398needs to be checked before being used. This can be used to avoid creating399references that will cause the garbage collector to keep the keys around longer400than needed.</p>401<dl class="py method">402<dt class="sig sig-object py" id="weakref.WeakKeyDictionary.keyrefs">403<span class="sig-prename descclassname"><span class="pre">WeakKeyDictionary.</span></span><span class="sig-name descname"><span class="pre">keyrefs</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakKeyDictionary.keyrefs" title="Link to this definition">¶</a></dt>404<dd><p>Return an iterable of the weak references to the keys.</p>405</dd></dl>406 407<dl class="py class">408<dt class="sig sig-object py" id="weakref.WeakValueDictionary">409<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">WeakValueDictionary</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">dict</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakValueDictionary" title="Link to this definition">¶</a></dt>410<dd><p>Mapping class that references values weakly. Entries in the dictionary will be411discarded when no strong reference to the value exists any more.</p>412<div class="versionchanged">413<p><span class="versionmodified changed">Changed in version 3.9: </span>Added support for <code class="docutils literal notranslate"><span class="pre">|</span></code> and <code class="docutils literal notranslate"><span class="pre">|=</span></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>414</div>415</dd></dl>416 417<p><a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> objects have an additional method that has the418same issues as the <a class="reference internal" href="#weakref.WeakKeyDictionary.keyrefs" title="weakref.WeakKeyDictionary.keyrefs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">WeakKeyDictionary.keyrefs()</span></code></a> method.</p>419<dl class="py method">420<dt class="sig sig-object py" id="weakref.WeakValueDictionary.valuerefs">421<span class="sig-prename descclassname"><span class="pre">WeakValueDictionary.</span></span><span class="sig-name descname"><span class="pre">valuerefs</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakValueDictionary.valuerefs" title="Link to this definition">¶</a></dt>422<dd><p>Return an iterable of the weak references to the values.</p>423</dd></dl>424 425<dl class="py class">426<dt class="sig sig-object py" id="weakref.WeakSet">427<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">WeakSet</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">elements</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakSet" title="Link to this definition">¶</a></dt>428<dd><p>Set class that keeps weak references to its elements. An element will be429discarded when no strong reference to it exists any more.</p>430</dd></dl>431 432<dl class="py class">433<dt class="sig sig-object py" id="weakref.WeakMethod">434<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">WeakMethod</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">method</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">callback</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakMethod" title="Link to this definition">¶</a></dt>435<dd><p>A custom <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code class="xref py py-class docutils literal notranslate"><span class="pre">ref</span></code></a> subclass which simulates a weak reference to a bound436method (i.e., a method defined on a class and looked up on an instance).437Since a bound method is ephemeral, a standard weak reference cannot keep438hold of it. <code class="xref py py-class docutils literal notranslate"><span class="pre">WeakMethod</span></code> has special code to recreate the bound439method until either the object or the original function dies:</p>440<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">:</span>441<span class="gp">... </span> <span class="k">def</span><span class="w"> </span><span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>442<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"method called!"</span><span class="p">)</span>443<span class="gp">...</span>444<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>445<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="p">)</span>446<span class="gp">>>> </span><span class="n">r</span><span class="p">()</span>447<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakMethod</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="p">)</span>448<span class="gp">>>> </span><span class="n">r</span><span class="p">()</span>449<span class="go"><bound method C.method of <__main__.C object at 0x7fc859830220>></span>450<span class="gp">>>> </span><span class="n">r</span><span class="p">()()</span>451<span class="go">method called!</span>452<span class="gp">>>> </span><span class="k">del</span> <span class="n">c</span>453<span class="gp">>>> </span><span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span>454<span class="go">0</span>455<span class="gp">>>> </span><span class="n">r</span><span class="p">()</span>456<span class="gp">>>></span>457</pre></div>458</div>459<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 class="xref py py-func docutils literal notranslate"><span class="pre">ref()</span></code></a> function.</p>460<div class="versionadded">461<p><span class="versionmodified added">Added in version 3.4.</span></p>462</div>463</dd></dl>464 465<dl class="py class">466<dt class="sig sig-object py" id="weakref.finalize">467<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">finalize</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">func</span></span></em>, <em class="sig-param"><span class="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#weakref.finalize" title="Link to this definition">¶</a></dt>468<dd><p>Return a callable finalizer object which will be called when <em>obj</em>469is garbage collected. Unlike an ordinary weak reference, a finalizer470will always survive until the reference object is collected, greatly471simplifying lifecycle management.</p>472<p>A finalizer is considered <em>alive</em> until it is called (either explicitly473or at garbage collection), and after that it is <em>dead</em>. Calling a live474finalizer returns the result of evaluating <code class="docutils literal notranslate"><span class="pre">func(*arg,</span> <span class="pre">**kwargs)</span></code>,475whereas calling a dead finalizer returns <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>476<p>Exceptions raised by finalizer callbacks during garbage collection477will be shown on the standard error output, but cannot be478propagated. They are handled in the same way as exceptions raised479from an object’s <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method or a weak reference’s480callback.</p>481<p>When the program exits, each remaining live finalizer is called482unless its <a class="reference internal" href="atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-attr docutils literal notranslate"><span class="pre">atexit</span></code></a> attribute has been set to false. They483are called in reverse order of creation.</p>484<p>A finalizer will never invoke its callback during the later part of485the <a class="reference internal" href="../glossary.html#term-interpreter-shutdown"><span class="xref std std-term">interpreter shutdown</span></a> when module globals are liable to have486been replaced by <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>487<dl class="py method">488<dt class="sig sig-object py" id="weakref.finalize.__call__">489<span class="sig-name descname"><span class="pre">__call__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.finalize.__call__" title="Link to this definition">¶</a></dt>490<dd><p>If <em>self</em> is alive then mark it as dead and return the result of491calling <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwargs)</span></code>. If <em>self</em> is dead then return492<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>493</dd></dl>494 495<dl class="py method">496<dt class="sig sig-object py" id="weakref.finalize.detach">497<span class="sig-name descname"><span class="pre">detach</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.finalize.detach" title="Link to this definition">¶</a></dt>498<dd><p>If <em>self</em> is alive then mark it as dead and return the tuple499<code class="docutils literal notranslate"><span class="pre">(obj,</span> <span class="pre">func,</span> <span class="pre">args,</span> <span class="pre">kwargs)</span></code>. If <em>self</em> is dead then return500<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>501</dd></dl>502 503<dl class="py method">504<dt class="sig sig-object py" id="weakref.finalize.peek">505<span class="sig-name descname"><span class="pre">peek</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.finalize.peek" title="Link to this definition">¶</a></dt>506<dd><p>If <em>self</em> is alive then return the tuple <code class="docutils literal notranslate"><span class="pre">(obj,</span> <span class="pre">func,</span> <span class="pre">args,</span>507<span class="pre">kwargs)</span></code>. If <em>self</em> is dead then return <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>508</dd></dl>509 510<dl class="py attribute">511<dt class="sig sig-object py" id="weakref.finalize.alive">512<span class="sig-name descname"><span class="pre">alive</span></span><a class="headerlink" href="#weakref.finalize.alive" title="Link to this definition">¶</a></dt>513<dd><p>Property which is true if the finalizer is alive, false otherwise.</p>514</dd></dl>515 516<dl class="py attribute">517<dt class="sig sig-object py" id="weakref.finalize.atexit">518<span class="sig-name descname"><span class="pre">atexit</span></span><a class="headerlink" href="#weakref.finalize.atexit" title="Link to this definition">¶</a></dt>519<dd><p>A writable boolean property which by default is true. When the520program exits, it calls all remaining live finalizers for which521<a class="reference internal" href="#weakref.finalize.atexit" title="weakref.finalize.atexit"><code class="xref py py-attr docutils literal notranslate"><span class="pre">atexit</span></code></a> is true. They are called in reverse order of522creation.</p>523</dd></dl>524 525<div class="admonition note">526<p class="admonition-title">Note</p>527<p>It is important to ensure that <em>func</em>, <em>args</em> and <em>kwargs</em> do528not own any references to <em>obj</em>, either directly or indirectly,529since otherwise <em>obj</em> will never be garbage collected. In530particular, <em>func</em> should not be a bound method of <em>obj</em>.</p>531</div>532<div class="versionadded">533<p><span class="versionmodified added">Added in version 3.4.</span></p>534</div>535</dd></dl>536 537<dl class="py data">538<dt class="sig sig-object py" id="weakref.ReferenceType">539<span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">ReferenceType</span></span><a class="headerlink" href="#weakref.ReferenceType" title="Link to this definition">¶</a></dt>540<dd><p>The type object for weak references objects.</p>541</dd></dl>542 543<dl class="py data">544<dt class="sig sig-object py" id="weakref.ProxyType">545<span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">ProxyType</span></span><a class="headerlink" href="#weakref.ProxyType" title="Link to this definition">¶</a></dt>546<dd><p>The type object for proxies of objects which are not callable.</p>547</dd></dl>548 549<dl class="py data">550<dt class="sig sig-object py" id="weakref.CallableProxyType">551<span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">CallableProxyType</span></span><a class="headerlink" href="#weakref.CallableProxyType" title="Link to this definition">¶</a></dt>552<dd><p>The type object for proxies of callable objects.</p>553</dd></dl>554 555<dl class="py data">556<dt class="sig sig-object py" id="weakref.ProxyTypes">557<span class="sig-prename descclassname"><span class="pre">weakref.</span></span><span class="sig-name descname"><span class="pre">ProxyTypes</span></span><a class="headerlink" href="#weakref.ProxyTypes" title="Link to this definition">¶</a></dt>558<dd><p>Sequence containing all the type objects for proxies. This can make it simpler559to test if an object is a proxy without being dependent on naming both proxy560types.</p>561</dd></dl>562 563<div class="admonition seealso">564<p class="admonition-title">See also</p>565<dl class="simple">566<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 earlier567implementations and information about similar features in other languages.</p>568</dd>569</dl>570</div>571<section id="weak-reference-objects">572<span id="weakref-objects"></span><h2>Weak Reference Objects<a class="headerlink" href="#weak-reference-objects" title="Link to this heading">¶</a></h2>573<p>Weak reference objects have no methods and no attributes besides574<a class="reference internal" href="#weakref.ref.__callback__" title="weakref.ref.__callback__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ref.__callback__</span></code></a>. A weak reference object allows the referent to be575obtained, if it still exists, by calling it:</p>576<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">weakref</span>577<span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">Object</span><span class="p">:</span>578<span class="gp">... </span> <span class="k">pass</span>579<span class="gp">...</span>580<span class="gp">>>> </span><span class="n">o</span> <span class="o">=</span> <span class="n">Object</span><span class="p">()</span>581<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>582<span class="gp">>>> </span><span class="n">o2</span> <span class="o">=</span> <span class="n">r</span><span class="p">()</span>583<span class="gp">>>> </span><span class="n">o</span> <span class="ow">is</span> <span class="n">o2</span>584<span class="go">True</span>585</pre></div>586</div>587<p>If the referent no longer exists, calling the reference object returns588<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>:</p>589<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">del</span> <span class="n">o</span><span class="p">,</span> <span class="n">o2</span>590<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">r</span><span class="p">())</span>591<span class="go">None</span>592</pre></div>593</div>594<p>Testing that a weak reference object is still live should be done using the595expression <code class="docutils literal notranslate"><span class="pre">ref()</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">None</span></code>. Normally, application code that needs to use596a reference object should follow this pattern:</p>597<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># r is a weak reference object</span>598<span class="n">o</span> <span class="o">=</span> <span class="n">r</span><span class="p">()</span>599<span class="k">if</span> <span class="n">o</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>600 <span class="c1"># referent has been garbage collected</span>601 <span class="nb">print</span><span class="p">(</span><span class="s2">"Object has been deallocated; can't frobnicate."</span><span class="p">)</span>602<span class="k">else</span><span class="p">:</span>603 <span class="nb">print</span><span class="p">(</span><span class="s2">"Object is still live!"</span><span class="p">)</span>604 <span class="n">o</span><span class="o">.</span><span class="n">do_something_useful</span><span class="p">()</span>605</pre></div>606</div>607<p>Using a separate test for “liveness” creates race conditions in threaded608applications; another thread can cause a weak reference to become invalidated609before the weak reference is called; the idiom shown above is safe in threaded610applications as well as single-threaded applications.</p>611<p>Specialized versions of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code class="xref py py-class docutils literal notranslate"><span class="pre">ref</span></code></a> objects can be created through subclassing.612This is used in the implementation of the <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> to reduce613the memory overhead for each entry in the mapping. This may be most useful to614associate additional information with a reference, but could also be used to615insert additional processing on calls to retrieve the referent.</p>616<p>This example shows how a subclass of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code class="xref py py-class docutils literal notranslate"><span class="pre">ref</span></code></a> can be used to store617additional information about an object and affect the value that’s returned when618the referent is accessed:</p>619<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">weakref</span>620 621<span class="k">class</span><span class="w"> </span><span class="nc">ExtendedRef</span><span class="p">(</span><span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">):</span>622 <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ob</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">/</span><span class="p">,</span> <span class="o">**</span><span class="n">annotations</span><span class="p">):</span>623 <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">ob</span><span class="p">,</span> <span class="n">callback</span><span class="p">)</span>624 <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span> <span class="o">=</span> <span class="mi">0</span>625 <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">annotations</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>626 <span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span>627 628 <span class="k">def</span><span class="w"> </span><span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>629<span class="w"> </span><span class="sd">"""Return a pair containing the referent and the number of</span>630<span class="sd"> times the reference has been called.</span>631<span class="sd"> """</span>632 <span class="n">ob</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__call__</span><span class="p">()</span>633 <span class="k">if</span> <span class="n">ob</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>634 <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span> <span class="o">+=</span> <span class="mi">1</span>635 <span class="n">ob</span> <span class="o">=</span> <span class="p">(</span><span class="n">ob</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span><span class="p">)</span>636 <span class="k">return</span> <span class="n">ob</span>637</pre></div>638</div>639</section>640<section id="example">641<span id="weakref-example"></span><h2>Example<a class="headerlink" href="#example" title="Link to this heading">¶</a></h2>642<p>This simple example shows how an application can use object IDs to retrieve643objects that it has seen before. The IDs of the objects can then be used in644other data structures without forcing the objects to remain alive, but the645objects can still be retrieved by ID if they do.</p>646<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">weakref</span>647 648<span class="n">_id2obj_dict</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakValueDictionary</span><span class="p">()</span>649 650<span class="k">def</span><span class="w"> </span><span class="nf">remember</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>651 <span class="n">oid</span> <span class="o">=</span> <span class="nb">id</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>652 <span class="n">_id2obj_dict</span><span class="p">[</span><span class="n">oid</span><span class="p">]</span> <span class="o">=</span> <span class="n">obj</span>653 <span class="k">return</span> <span class="n">oid</span>654 655<span class="k">def</span><span class="w"> </span><span class="nf">id2obj</span><span class="p">(</span><span class="n">oid</span><span class="p">):</span>656 <span class="k">return</span> <span class="n">_id2obj_dict</span><span class="p">[</span><span class="n">oid</span><span class="p">]</span>657</pre></div>658</div>659</section>660<section id="finalizer-objects">661<span id="finalize-examples"></span><h2>Finalizer Objects<a class="headerlink" href="#finalizer-objects" title="Link to this heading">¶</a></h2>662<p>The main benefit of using <a class="reference internal" href="#weakref.finalize" title="weakref.finalize"><code class="xref py py-class docutils literal notranslate"><span class="pre">finalize</span></code></a> is that it makes it simple663to register a callback without needing to preserve the returned finalizer664object. For instance</p>665<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">weakref</span>666<span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">Object</span><span class="p">:</span>667<span class="gp">... </span> <span class="k">pass</span>668<span class="gp">...</span>669<span class="gp">>>> </span><span class="n">kenny</span> <span class="o">=</span> <span class="n">Object</span><span class="p">()</span>670<span class="gp">>>> </span><span class="n">weakref</span><span class="o">.</span><span class="n">finalize</span><span class="p">(</span><span class="n">kenny</span><span class="p">,</span> <span class="nb">print</span><span class="p">,</span> <span class="s2">"You killed Kenny!"</span><span class="p">)</span>671<span class="go"><finalize object at ...; for 'Object' at ...></span>672<span class="gp">>>> </span><span class="k">del</span> <span class="n">kenny</span>673<span class="go">You killed Kenny!</span>674</pre></div>675</div>676<p>The finalizer can be called directly as well. However the finalizer677will invoke the callback at most once.</p>678<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">callback</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span><span class="p">):</span>679<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"CALLBACK"</span><span class="p">)</span>680<span class="gp">... </span> <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="o">+</span> <span class="n">z</span>681<span class="gp">...</span>682<span class="gp">>>> </span><span class="n">obj</span> <span class="o">=</span> <span class="n">Object</span><span class="p">()</span>683<span class="gp">>>> </span><span class="n">f</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">finalize</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">z</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>684<span class="gp">>>> </span><span class="k">assert</span> <span class="n">f</span><span class="o">.</span><span class="n">alive</span>685<span class="gp">>>> </span><span class="k">assert</span> <span class="n">f</span><span class="p">()</span> <span class="o">==</span> <span class="mi">6</span>686<span class="go">CALLBACK</span>687<span class="gp">>>> </span><span class="k">assert</span> <span class="ow">not</span> <span class="n">f</span><span class="o">.</span><span class="n">alive</span>688<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span> <span class="c1"># callback not called because finalizer dead</span>689<span class="gp">>>> </span><span class="k">del</span> <span class="n">obj</span> <span class="c1"># callback not called because finalizer dead</span>690</pre></div>691</div>692<p>You can unregister a finalizer using its <a class="reference internal" href="#weakref.finalize.detach" title="weakref.finalize.detach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">detach()</span></code></a>693method. This kills the finalizer and returns the arguments passed to694the constructor when it was created.</p>695<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">obj</span> <span class="o">=</span> <span class="n">Object</span><span class="p">()</span>696<span class="gp">>>> </span><span class="n">f</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">finalize</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">z</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>697<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span>698<span class="go">(<...Object object ...>, <function callback ...>, (1, 2), {'z': 3})</span>699<span class="gp">>>> </span><span class="n">newobj</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">_</span>700<span class="gp">>>> </span><span class="k">assert</span> <span class="ow">not</span> <span class="n">f</span><span class="o">.</span><span class="n">alive</span>701<span class="gp">>>> </span><span class="k">assert</span> <span class="n">newobj</span> <span class="ow">is</span> <span class="n">obj</span>702<span class="gp">>>> </span><span class="k">assert</span> <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span>703<span class="go">CALLBACK</span>704</pre></div>705</div>706<p>Unless you set the <a class="reference internal" href="#weakref.finalize.atexit" title="weakref.finalize.atexit"><code class="xref py py-attr docutils literal notranslate"><span class="pre">atexit</span></code></a> attribute to707<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, a finalizer will be called when the program exits if it708is still alive. For instance</p>709<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">obj</span> <span class="o">=</span> <span class="n">Object</span><span class="p">()</span>710<span class="gp">>>> </span><span class="n">weakref</span><span class="o">.</span><span class="n">finalize</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">print</span><span class="p">,</span> <span class="s2">"obj dead or exiting"</span><span class="p">)</span>711<span class="go"><finalize object at ...; for 'Object' at ...></span>712<span class="gp">>>> </span><span class="n">exit</span><span class="p">()</span>713<span class="go">obj dead or exiting</span>714</pre></div>715</div>716</section>717<section id="comparing-finalizers-with-del-methods">718<h2>Comparing finalizers with <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods<a class="headerlink" href="#comparing-finalizers-with-del-methods" title="Link to this heading">¶</a></h2>719<p>Suppose we want to create a class whose instances represent temporary720directories. The directories should be deleted with their contents721when the first of the following events occurs:</p>722<ul class="simple">723<li><p>the object is garbage collected,</p></li>724<li><p>the object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code> method is called, or</p></li>725<li><p>the program exits.</p></li>726</ul>727<p>We might try to implement the class using a <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method as728follows:</p>729<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">TempDir</span><span class="p">:</span>730 <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>731 <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">mkdtemp</span><span class="p">()</span>732 733 <span class="k">def</span><span class="w"> </span><span class="nf">remove</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>734 <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>735 <span class="n">shutil</span><span class="o">.</span><span class="n">rmtree</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>736 <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="kc">None</span>737 738 <span class="nd">@property</span>739 <span class="k">def</span><span class="w"> </span><span class="nf">removed</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>740 <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="ow">is</span> <span class="kc">None</span>741 742 <span class="k">def</span><span class="w"> </span><span class="fm">__del__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>743 <span class="bp">self</span><span class="o">.</span><span class="n">remove</span><span class="p">()</span>744</pre></div>745</div>746<p>Starting with Python 3.4, <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods no longer prevent747reference cycles from being garbage collected, and module globals are748no longer forced to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> during <a class="reference internal" href="../glossary.html#term-interpreter-shutdown"><span class="xref std std-term">interpreter shutdown</span></a>.749So this code should work without any issues on CPython.</p>750<p>However, handling of <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods is notoriously implementation751specific, since it depends on internal details of the interpreter’s garbage752collector implementation.</p>753<p>A more robust alternative can be to define a finalizer which only references754the specific functions and objects that it needs, rather than having access755to the full state of the object:</p>756<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">TempDir</span><span class="p">:</span>757 <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>758 <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">mkdtemp</span><span class="p">()</span>759 <span class="bp">self</span><span class="o">.</span><span class="n">_finalizer</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">finalize</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">shutil</span><span class="o">.</span><span class="n">rmtree</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>760 761 <span class="k">def</span><span class="w"> </span><span class="nf">remove</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>762 <span class="bp">self</span><span class="o">.</span><span class="n">_finalizer</span><span class="p">()</span>763 764 <span class="nd">@property</span>765 <span class="k">def</span><span class="w"> </span><span class="nf">removed</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>766 <span class="k">return</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_finalizer</span><span class="o">.</span><span class="n">alive</span>767</pre></div>768</div>769<p>Defined like this, our finalizer only receives a reference to the details770it needs to clean up the directory appropriately. If the object never gets771garbage collected the finalizer will still be called at exit.</p>772<p>The other advantage of weakref based finalizers is that they can be used to773register finalizers for classes where the definition is controlled by a774third party, such as running code when a module is unloaded:</p>775<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">weakref</span><span class="o">,</span><span class="w"> </span><span class="nn">sys</span>776<span class="k">def</span><span class="w"> </span><span class="nf">unloading_module</span><span class="p">():</span>777 <span class="c1"># implicit reference to the module globals from the function body</span>778<span class="n">weakref</span><span class="o">.</span><span class="n">finalize</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="vm">__name__</span><span class="p">],</span> <span class="n">unloading_module</span><span class="p">)</span>779</pre></div>780</div>781<div class="admonition note">782<p class="admonition-title">Note</p>783<p>If you create a finalizer object in a daemonic thread just as the program784exits then there is the possibility that the finalizer785does not get called at exit. However, in a daemonic thread786<a class="reference internal" href="atexit.html#atexit.register" title="atexit.register"><code class="xref py py-func docutils literal notranslate"><span class="pre">atexit.register()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span> <span class="pre">...</span></code> and <code class="docutils literal notranslate"><span class="pre">with:</span> <span class="pre">...</span></code>787do not guarantee that cleanup occurs either.</p>788</div>789</section>790</section>791 792 793 <div class="clearer"></div>794 </div>795 </div>796 </div>797 <div class="sphinxsidebar" role="navigation" aria-label="Main">798 <div class="sphinxsidebarwrapper">799 <div>800 <h3><a href="../contents.html">Table of Contents</a></h3>801 <ul>802<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a><ul>803<li><a class="reference internal" href="#weak-reference-objects">Weak Reference Objects</a></li>804<li><a class="reference internal" href="#example">Example</a></li>805<li><a class="reference internal" href="#finalizer-objects">Finalizer Objects</a></li>806<li><a class="reference internal" href="#comparing-finalizers-with-del-methods">Comparing finalizers with <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> methods</a></li>807</ul>808</li>809</ul>810 811 </div>812 <div>813 <h4>Previous topic</h4>814 <p class="topless"><a href="array.html"815 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></p>816 </div>817 <div>818 <h4>Next topic</h4>819 <p class="topless"><a href="types.html"820 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code> — Dynamic type creation and names for built-in types</a></p>821 </div>822 <script>823 document.addEventListener('DOMContentLoaded', () => {824 const title = document.querySelector('meta[property="og:title"]').content;825 const elements = document.querySelectorAll('.improvepage');826 const pageurl = window.location.href.split('?')[0];827 elements.forEach(element => {828 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));829 url.searchParams.set('pagetitle', title);830 url.searchParams.set('pageurl', pageurl);831 url.searchParams.set('pagesource', "library/weakref.rst");832 element.href = url.toString();833 });834 });835 </script>836 <div role="note" aria-label="source link">837 <h3>This page</h3>838 <ul class="this-page-menu">839 <li><a href="../bugs.html">Report a bug</a></li>840 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>841 <li>842 <a href="https://github.com/python/cpython/blob/main/Doc/library/weakref.rst?plain=1"843 rel="nofollow">Show source844 </a>845 </li>846 847 </ul>848 </div>849 </div>850<div id="sidebarbutton" title="Collapse sidebar">851<span>«</span>852</div>853 854 </div>855 <div class="clearer"></div>856 </div> 857 <div class="related" role="navigation" aria-label="Related">858 <h3>Navigation</h3>859 <ul>860 <li class="right" style="margin-right: 10px">861 <a href="../genindex.html" title="General Index"862 >index</a></li>863 <li class="right" >864 <a href="../py-modindex.html" title="Python Module Index"865 >modules</a> |</li>866 <li class="right" >867 <a href="types.html" title="types — Dynamic type creation and names for built-in types"868 >next</a> |</li>869 <li class="right" >870 <a href="array.html" title="array — Efficient arrays of numeric values"871 >previous</a> |</li>872 873 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>874 <li><a href="https://www.python.org/">Python</a> »</li>875 <li class="switchers">876 <div class="language_switcher_placeholder"></div>877 <div class="version_switcher_placeholder"></div>878 </li>879 <li>880 881 </li>882 <li id="cpython-language-and-version">883 <a href="../index.html">3.15.0a6 Documentation</a> »884 </li>885 886 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>887 <li class="nav-item nav-item-2"><a href="datatypes.html" >Data Types</a> »</li>888 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a></li>889 <li class="right">890 891 892 <div class="inline-search" role="search">893 <form class="inline-search" action="../search.html" method="get">894 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">895 <input type="submit" value="Go">896 </form>897 </div>898 |899 </li>900 <li class="right">901<label class="theme-selector-label">902 Theme903 <select class="theme-selector" oninput="activateTheme(this.value)">904 <option value="auto" selected>Auto</option>905 <option value="light">Light</option>906 <option value="dark">Dark</option>907 </select>908</label> |</li>909 910 </ul>911 </div> 912 <div class="footer">913 © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.914 <br>915 This page is licensed under the Python Software Foundation License Version 2.916 <br>917 Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.918 <br>919 920 See <a href="/license.html">History and License</a> for more information.<br>921 922 923 <br>924 925 The Python Software Foundation is a non-profit corporation.926<a href="https://www.python.org/psf/donations/">Please donate.</a>927<br>928 <br>929 Last updated on Mar 10, 2026 (08:58 UTC).930 931 <a href="/bugs.html">Found a bug</a>?932 933 <br>934 935 Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.936 </div>937 938 </body>939</html>