Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
abc.html695 linesDownload Raw Back to docs
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="abc — Abstract Base Classes" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/abc.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/abc.py This module provides the infrastructure for defining abstract base classes(ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also ..." />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_abc_5b42805a.png" />15<meta property="og:image:alt" content="Source code: Lib/abc.py This module provides the infrastructure for defining abstract base classes(ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also ..." />16<meta name="description" content="Source code: Lib/abc.py This module provides the infrastructure for defining abstract base classes(ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also ..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>abc — Abstract Base Classes &#8212; 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="atexit — Exit handlers" href="atexit.html" />43    <link rel="prev" title="contextlib — Utilities for with-statement contexts" href="contextlib.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/abc.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    <h4>Previous topic</h4>106    <p class="topless"><a href="contextlib.html"107                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></p>108  </div>109  <div>110    <h4>Next topic</h4>111    <p class="topless"><a href="atexit.html"112                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a></p>113  </div>114  <script>115    document.addEventListener('DOMContentLoaded', () => {116        const title = document.querySelector('meta[property="og:title"]').content;117        const elements = document.querySelectorAll('.improvepage');118        const pageurl = window.location.href.split('?')[0];119        elements.forEach(element => {120            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));121            url.searchParams.set('pagetitle', title);122            url.searchParams.set('pageurl', pageurl);123            url.searchParams.set('pagesource', "library/abc.rst");124            element.href = url.toString();125        });126    });127  </script>128  <div role="note" aria-label="source link">129    <h3>This page</h3>130    <ul class="this-page-menu">131      <li><a href="../bugs.html">Report a bug</a></li>132      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>133      <li>134        <a href="https://github.com/python/cpython/blob/main/Doc/library/abc.rst?plain=1"135            rel="nofollow">Show source136        </a>137      </li>138      139    </ul>140  </div>141        </nav>142    </div>143</div>144 145  146    <div class="related" role="navigation" aria-label="Related">147      <h3>Navigation</h3>148      <ul>149        <li class="right" style="margin-right: 10px">150          <a href="../genindex.html" title="General Index"151             accesskey="I">index</a></li>152        <li class="right" >153          <a href="../py-modindex.html" title="Python Module Index"154             >modules</a> |</li>155        <li class="right" >156          <a href="atexit.html" title="atexit — Exit handlers"157             accesskey="N">next</a> |</li>158        <li class="right" >159          <a href="contextlib.html" title="contextlib — Utilities for with-statement contexts"160             accesskey="P">previous</a> |</li>161 162          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>163          <li><a href="https://www.python.org/">Python</a> &#187;</li>164          <li class="switchers">165            <div class="language_switcher_placeholder"></div>166            <div class="version_switcher_placeholder"></div>167          </li>168          <li>169              170          </li>171    <li id="cpython-language-and-version">172      <a href="../index.html">3.15.0a6 Documentation</a> &#187;173    </li>174 175          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>176          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">Python Runtime Services</a> &#187;</li>177        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></li>178                <li class="right">179                    180 181    <div class="inline-search" role="search">182        <form class="inline-search" action="../search.html" method="get">183          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">184          <input type="submit" value="Go">185        </form>186    </div>187                     |188                </li>189            <li class="right">190<label class="theme-selector-label">191    Theme192    <select class="theme-selector" oninput="activateTheme(this.value)">193        <option value="auto" selected>Auto</option>194        <option value="light">Light</option>195        <option value="dark">Dark</option>196    </select>197</label> |</li>198            199      </ul>200    </div>    201 202    <div class="document">203      <div class="documentwrapper">204        <div class="bodywrapper">205          <div class="body" role="main">206            207  <section id="module-abc">208<span id="abc-abstract-base-classes"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes<a class="headerlink" href="#module-abc" title="Link to this heading">¶</a></h1>209<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/abc.py">Lib/abc.py</a></p>210<hr class="docutils" />211<p>This module provides the infrastructure for defining <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base212classes</span></a> (ABCs) in Python, as outlined in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-3119/"><strong>PEP 3119</strong></a>;213see the PEP for why this was added to Python. (See also <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-3141/"><strong>PEP 3141</strong></a> and the214<a class="reference internal" href="numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module regarding a type hierarchy for numbers based on ABCs.)</p>215<p>The <a class="reference internal" href="collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module has some concrete classes that derive from216ABCs; these can, of course, be further derived. In addition, the217<a class="reference internal" href="collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code></a> submodule has some ABCs that can be used to test whether218a class or instance provides a particular interface, for example, if it is219<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> or if it is a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>.</p>220<p>This module provides the metaclass <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> for defining ABCs and221a helper class <a class="reference internal" href="#abc.ABC" title="abc.ABC"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code></a> to alternatively define ABCs through inheritance:</p>222<dl class="py class">223<dt class="sig sig-object py" id="abc.ABC">224<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">abc.</span></span><span class="sig-name descname"><span class="pre">ABC</span></span><a class="headerlink" href="#abc.ABC" title="Link to this definition">¶</a></dt>225<dd><p>A helper class that has <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> as its metaclass.  With this class,226an abstract base class can be created by simply deriving from <code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code>227avoiding sometimes confusing metaclass usage, for example:</p>228<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">abc</span><span class="w"> </span><span class="kn">import</span> <span class="n">ABC</span>229 230<span class="k">class</span><span class="w"> </span><span class="nc">MyABC</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>231    <span class="k">pass</span>232</pre></div>233</div>234<p>Note that the type of <code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code> is still <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a>, therefore235inheriting from <code class="xref py py-class docutils literal notranslate"><span class="pre">ABC</span></code> requires the usual precautions regarding236metaclass usage, as multiple inheritance may lead to metaclass conflicts.237One may also define an abstract base class by passing the metaclass238keyword and using <code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code> directly, for example:</p>239<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">abc</span><span class="w"> </span><span class="kn">import</span> <span class="n">ABCMeta</span>240 241<span class="k">class</span><span class="w"> </span><span class="nc">MyABC</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">ABCMeta</span><span class="p">):</span>242    <span class="k">pass</span>243</pre></div>244</div>245<div class="versionadded">246<p><span class="versionmodified added">Added in version 3.4.</span></p>247</div>248</dd></dl>249 250<dl class="py class">251<dt class="sig sig-object py" id="abc.ABCMeta">252<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">abc.</span></span><span class="sig-name descname"><span class="pre">ABCMeta</span></span><a class="headerlink" href="#abc.ABCMeta" title="Link to this definition">¶</a></dt>253<dd><p>Metaclass for defining Abstract Base Classes (ABCs).</p>254<p>Use this metaclass to create an ABC.  An ABC can be subclassed directly, and255then acts as a mix-in class.  You can also register unrelated concrete256classes (even built-in classes) and unrelated ABCs as “virtual subclasses” –257these and their descendants will be considered subclasses of the registering258ABC by the built-in <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> function, but the registering ABC259won’t show up in their MRO (Method Resolution Order) nor will method260implementations defined by the registering ABC be callable (not even via261<a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>). <a class="footnote-reference brackets" href="#id2" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a></p>262<p>Classes created with a metaclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code> have the following method:</p>263<dl class="py method">264<dt class="sig sig-object py" id="abc.ABCMeta.register">265<span class="sig-name descname"><span class="pre">register</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">subclass</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.register" title="Link to this definition">¶</a></dt>266<dd><p>Register <em>subclass</em> as a “virtual subclass” of this ABC. For267example:</p>268<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">abc</span><span class="w"> </span><span class="kn">import</span> <span class="n">ABC</span>269 270<span class="k">class</span><span class="w"> </span><span class="nc">MyABC</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>271    <span class="k">pass</span>272 273<span class="n">MyABC</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">tuple</span><span class="p">)</span>274 275<span class="k">assert</span> <span class="nb">issubclass</span><span class="p">(</span><span class="nb">tuple</span><span class="p">,</span> <span class="n">MyABC</span><span class="p">)</span>276<span class="k">assert</span> <span class="nb">isinstance</span><span class="p">((),</span> <span class="n">MyABC</span><span class="p">)</span>277</pre></div>278</div>279<div class="versionchanged">280<p><span class="versionmodified changed">Changed in version 3.3: </span>Returns the registered subclass, to allow usage as a class decorator.</p>281</div>282<div class="versionchanged">283<p><span class="versionmodified changed">Changed in version 3.4: </span>To detect calls to <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code>, you can use the284<a class="reference internal" href="#abc.get_cache_token" title="abc.get_cache_token"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_cache_token()</span></code></a> function.</p>285</div>286</dd></dl>287 288<p>You can also override this method in an abstract base class:</p>289<dl class="py method">290<dt class="sig sig-object py" id="abc.ABCMeta.__subclasshook__">291<span class="sig-name descname"><span class="pre">__subclasshook__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">subclass</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.__subclasshook__" title="Link to this definition">¶</a></dt>292<dd><p>(Must be defined as a class method.)</p>293<p>Check whether <em>subclass</em> is considered a subclass of this ABC.  This means294that you can customize the behavior of <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> further without the295need to call <a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code></a> on every class you want to consider a296subclass of the ABC.  (This class method is called from the297<a class="reference internal" href="../reference/datamodel.html#type.__subclasscheck__" title="type.__subclasscheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a> method of the ABC.)</p>298<p>This method should return <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="docutils literal notranslate"><span class="pre">False</span></code> or <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>.  If299it returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, the <em>subclass</em> is considered a subclass of this ABC.300If it returns <code class="docutils literal notranslate"><span class="pre">False</span></code>, the <em>subclass</em> is not considered a subclass of301this ABC, even if it would normally be one.  If it returns302<code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code>, the subclass check is continued with the usual303mechanism.</p>304</dd></dl>305 306<p>For a demonstration of these concepts, look at this example ABC definition:</p>307<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Foo</span><span class="p">:</span>308    <span class="k">def</span><span class="w"> </span><span class="fm">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span>309        <span class="o">...</span>310    <span class="k">def</span><span class="w"> </span><span class="fm">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>311        <span class="o">...</span>312    <span class="k">def</span><span class="w"> </span><span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>313        <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>314 315<span class="k">class</span><span class="w"> </span><span class="nc">MyIterable</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>316 317    <span class="nd">@abstractmethod</span>318    <span class="k">def</span><span class="w"> </span><span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>319        <span class="k">while</span> <span class="kc">False</span><span class="p">:</span>320            <span class="k">yield</span> <span class="kc">None</span>321 322    <span class="k">def</span><span class="w"> </span><span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>323        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="fm">__iter__</span><span class="p">()</span>324 325    <span class="nd">@classmethod</span>326    <span class="k">def</span><span class="w"> </span><span class="nf">__subclasshook__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">C</span><span class="p">):</span>327        <span class="k">if</span> <span class="bp">cls</span> <span class="ow">is</span> <span class="n">MyIterable</span><span class="p">:</span>328            <span class="k">if</span> <span class="nb">any</span><span class="p">(</span><span class="s2">&quot;__iter__&quot;</span> <span class="ow">in</span> <span class="n">B</span><span class="o">.</span><span class="vm">__dict__</span> <span class="k">for</span> <span class="n">B</span> <span class="ow">in</span> <span class="n">C</span><span class="o">.</span><span class="vm">__mro__</span><span class="p">):</span>329                <span class="k">return</span> <span class="kc">True</span>330        <span class="k">return</span> <span class="bp">NotImplemented</span>331 332<span class="n">MyIterable</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Foo</span><span class="p">)</span>333</pre></div>334</div>335<p>The ABC <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> defines the standard iterable method,336<a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, as an abstract method.  The implementation given337here can still be called from subclasses.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_iterator()</span></code> method338is also part of the <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> abstract base class, but it does not have339to be overridden in non-abstract derived classes.</p>340<p>The <a class="reference internal" href="#abc.ABCMeta.__subclasshook__" title="abc.ABCMeta.__subclasshook__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasshook__()</span></code></a> class method defined here says that any class341that has an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method in its342<a class="reference internal" href="../reference/datamodel.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> (or in that of one of its base classes, accessed343via the <a class="reference internal" href="../reference/datamodel.html#type.__mro__" title="type.__mro__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__mro__</span></code></a> list) is considered a <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> too.</p>344<p>Finally, the last line makes <code class="docutils literal notranslate"><span class="pre">Foo</span></code> a virtual subclass of <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code>,345even though it does not define an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method (it uses346the old-style iterable protocol, defined in terms of <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> and347<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>).  Note that this will not make <code class="docutils literal notranslate"><span class="pre">get_iterator</span></code>348available as a method of <code class="docutils literal notranslate"><span class="pre">Foo</span></code>, so it is provided separately.</p>349</dd></dl>350 351<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> module also provides the following decorator:</p>352<dl class="py function">353<dt class="sig sig-object py" id="abc.abstractmethod">354<span class="sig-prename descclassname"><span class="pre">&#64;</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractmethod</span></span><a class="headerlink" href="#abc.abstractmethod" title="Link to this definition">¶</a></dt>355<dd><p>A decorator indicating abstract methods.</p>356<p>Using this decorator requires that the class’s metaclass is <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a>357or is derived from it.  A class that has a metaclass derived from358<code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code> cannot be instantiated unless all of its abstract methods359and properties are overridden.  The abstract methods can be called using any360of the normal ‘super’ call mechanisms.  <code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code> may be used361to declare abstract methods for properties and descriptors.</p>362<p>Dynamically adding abstract methods to a class, or attempting to modify the363abstraction status of a method or class once it is created, are only364supported using the <a class="reference internal" href="#abc.update_abstractmethods" title="abc.update_abstractmethods"><code class="xref py py-func docutils literal notranslate"><span class="pre">update_abstractmethods()</span></code></a> function.  The365<code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code> only affects subclasses derived using regular366inheritance; “virtual subclasses” registered with the ABC’s367<a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code></a> method are not affected.</p>368<p>When <code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code> is applied in combination with other method369descriptors, it should be applied as the innermost decorator, as shown in370the following usage examples:</p>371<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>372    <span class="nd">@abstractmethod</span>373    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_method</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg1</span><span class="p">):</span>374        <span class="o">...</span>375    <span class="nd">@classmethod</span>376    <span class="nd">@abstractmethod</span>377    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_classmethod</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">arg2</span><span class="p">):</span>378        <span class="o">...</span>379    <span class="nd">@staticmethod</span>380    <span class="nd">@abstractmethod</span>381    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_staticmethod</span><span class="p">(</span><span class="n">arg3</span><span class="p">):</span>382        <span class="o">...</span>383 384    <span class="nd">@property</span>385    <span class="nd">@abstractmethod</span>386    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>387        <span class="o">...</span>388    <span class="nd">@my_abstract_property</span><span class="o">.</span><span class="n">setter</span>389    <span class="nd">@abstractmethod</span>390    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span>391        <span class="o">...</span>392 393    <span class="nd">@abstractmethod</span>394    <span class="k">def</span><span class="w"> </span><span class="nf">_get_x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>395        <span class="o">...</span>396    <span class="nd">@abstractmethod</span>397    <span class="k">def</span><span class="w"> </span><span class="nf">_set_x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span>398        <span class="o">...</span>399    <span class="n">x</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">_get_x</span><span class="p">,</span> <span class="n">_set_x</span><span class="p">)</span>400</pre></div>401</div>402<p>In order to correctly interoperate with the abstract base class machinery,403the descriptor must identify itself as abstract using404<code class="xref py py-attr docutils literal notranslate"><span class="pre">__isabstractmethod__</span></code>. In general, this attribute should be <code class="docutils literal notranslate"><span class="pre">True</span></code>405if any of the methods used to compose the descriptor are abstract. For406example, Python’s built-in <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-class docutils literal notranslate"><span class="pre">property</span></code></a> does the equivalent of:</p>407<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Descriptor</span><span class="p">:</span>408    <span class="o">...</span>409    <span class="nd">@property</span>410    <span class="k">def</span><span class="w"> </span><span class="nf">__isabstractmethod__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>411        <span class="k">return</span> <span class="nb">any</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s1">&#39;__isabstractmethod__&#39;</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span> <span class="k">for</span>412                   <span class="n">f</span> <span class="ow">in</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_fget</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fset</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fdel</span><span class="p">))</span>413</pre></div>414</div>415<div class="admonition note">416<p class="admonition-title">Note</p>417<p>Unlike Java abstract methods, these abstract418methods may have an implementation. This implementation can be419called via the <a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> mechanism from the class that420overrides it.  This could be useful as an end-point for a421super-call in a framework that uses cooperative422multiple-inheritance.</p>423</div>424</dd></dl>425 426<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> module also supports the following legacy decorators:</p>427<dl class="py function">428<dt class="sig sig-object py" id="abc.abstractclassmethod">429<span class="sig-prename descclassname"><span class="pre">&#64;</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractclassmethod</span></span><a class="headerlink" href="#abc.abstractclassmethod" title="Link to this definition">¶</a></dt>430<dd><div class="versionadded">431<p><span class="versionmodified added">Added in version 3.2.</span></p>432</div>433<div class="deprecated">434<p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>It is now possible to use <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">classmethod</span></code></a> with435<a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>, making this decorator redundant.</p>436</div>437<p>A subclass of the built-in <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a>, indicating an abstract438classmethod. Otherwise it is similar to <a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>.</p>439<p>This special case is deprecated, as the <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> decorator440is now correctly identified as abstract when applied to an abstract441method:</p>442<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>443    <span class="nd">@classmethod</span>444    <span class="nd">@abstractmethod</span>445    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_classmethod</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>446        <span class="o">...</span>447</pre></div>448</div>449</dd></dl>450 451<dl class="py function">452<dt class="sig sig-object py" id="abc.abstractstaticmethod">453<span class="sig-prename descclassname"><span class="pre">&#64;</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractstaticmethod</span></span><a class="headerlink" href="#abc.abstractstaticmethod" title="Link to this definition">¶</a></dt>454<dd><div class="versionadded">455<p><span class="versionmodified added">Added in version 3.2.</span></p>456</div>457<div class="deprecated">458<p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>It is now possible to use <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">staticmethod</span></code></a> with459<a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>, making this decorator redundant.</p>460</div>461<p>A subclass of the built-in <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a>, indicating an abstract462staticmethod. Otherwise it is similar to <a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>.</p>463<p>This special case is deprecated, as the <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> decorator464is now correctly identified as abstract when applied to an abstract465method:</p>466<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>467    <span class="nd">@staticmethod</span>468    <span class="nd">@abstractmethod</span>469    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_staticmethod</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span>470        <span class="o">...</span>471</pre></div>472</div>473</dd></dl>474 475<dl class="py function">476<dt class="sig sig-object py" id="abc.abstractproperty">477<span class="sig-prename descclassname"><span class="pre">&#64;</span></span><span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">abstractproperty</span></span><a class="headerlink" href="#abc.abstractproperty" title="Link to this definition">¶</a></dt>478<dd><div class="deprecated">479<p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>It is now possible to use <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-class docutils literal notranslate"><span class="pre">property</span></code></a>, <a class="reference internal" href="functions.html#property.getter" title="property.getter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">property.getter()</span></code></a>,480<a class="reference internal" href="functions.html#property.setter" title="property.setter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">property.setter()</span></code></a> and <a class="reference internal" href="functions.html#property.deleter" title="property.deleter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">property.deleter()</span></code></a> with481<a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a>, making this decorator redundant.</p>482</div>483<p>A subclass of the built-in <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a>, indicating an abstract484property.</p>485<p>This special case is deprecated, as the <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> decorator486is now correctly identified as abstract when applied to an abstract487method:</p>488<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>489    <span class="nd">@property</span>490    <span class="nd">@abstractmethod</span>491    <span class="k">def</span><span class="w"> </span><span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>492        <span class="o">...</span>493</pre></div>494</div>495<p>The above example defines a read-only property; you can also define a496read-write abstract property by appropriately marking one or more of the497underlying methods as abstract:</p>498<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>499    <span class="nd">@property</span>500    <span class="k">def</span><span class="w"> </span><span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>501        <span class="o">...</span>502 503    <span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>504    <span class="nd">@abstractmethod</span>505    <span class="k">def</span><span class="w"> </span><span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span>506        <span class="o">...</span>507</pre></div>508</div>509<p>If only some components are abstract, only those components need to be510updated to create a concrete property in a subclass:</p>511<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>512    <span class="nd">@C</span><span class="o">.</span><span class="n">x</span><span class="o">.</span><span class="n">setter</span>513    <span class="k">def</span><span class="w"> </span><span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span>514        <span class="o">...</span>515</pre></div>516</div>517</dd></dl>518 519<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> module also provides the following functions:</p>520<dl class="py function">521<dt class="sig sig-object py" id="abc.get_cache_token">522<span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">get_cache_token</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#abc.get_cache_token" title="Link to this definition">¶</a></dt>523<dd><p>Returns the current abstract base class cache token.</p>524<p>The token is an opaque object (that supports equality testing) identifying525the current version of the abstract base class cache for virtual subclasses.526The token changes with every call to <a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ABCMeta.register()</span></code></a> on any ABC.</p>527<div class="versionadded">528<p><span class="versionmodified added">Added in version 3.4.</span></p>529</div>530</dd></dl>531 532<dl class="py function">533<dt class="sig sig-object py" id="abc.update_abstractmethods">534<span class="sig-prename descclassname"><span class="pre">abc.</span></span><span class="sig-name descname"><span class="pre">update_abstractmethods</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cls</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#abc.update_abstractmethods" title="Link to this definition">¶</a></dt>535<dd><p>A function to recalculate an abstract class’s abstraction status. This536function should be called if a class’s abstract methods have been537implemented or changed after it was created. Usually, this function should538be called from within a class decorator.</p>539<p>Returns <em>cls</em>, to allow usage as a class decorator.</p>540<p>If <em>cls</em> is not an instance of <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a>, does nothing.</p>541<div class="admonition note">542<p class="admonition-title">Note</p>543<p>This function assumes that <em>cls</em>’s superclasses are already updated.544It does not update any subclasses.</p>545</div>546<div class="versionadded">547<p><span class="versionmodified added">Added in version 3.10.</span></p>548</div>549</dd></dl>550 551<p class="rubric">Footnotes</p>552<aside class="footnote-list brackets">553<aside class="footnote brackets" id="id2" role="doc-footnote">554<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>555<p>C++ programmers should note that Python’s virtual base class556concept is not the same as C++’s.</p>557</aside>558</aside>559</section>560 561 562            <div class="clearer"></div>563          </div>564        </div>565      </div>566      <div class="sphinxsidebar" role="navigation" aria-label="Main">567        <div class="sphinxsidebarwrapper">568  <div>569    <h4>Previous topic</h4>570    <p class="topless"><a href="contextlib.html"571                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></p>572  </div>573  <div>574    <h4>Next topic</h4>575    <p class="topless"><a href="atexit.html"576                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a></p>577  </div>578  <script>579    document.addEventListener('DOMContentLoaded', () => {580        const title = document.querySelector('meta[property="og:title"]').content;581        const elements = document.querySelectorAll('.improvepage');582        const pageurl = window.location.href.split('?')[0];583        elements.forEach(element => {584            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));585            url.searchParams.set('pagetitle', title);586            url.searchParams.set('pageurl', pageurl);587            url.searchParams.set('pagesource', "library/abc.rst");588            element.href = url.toString();589        });590    });591  </script>592  <div role="note" aria-label="source link">593    <h3>This page</h3>594    <ul class="this-page-menu">595      <li><a href="../bugs.html">Report a bug</a></li>596      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>597      <li>598        <a href="https://github.com/python/cpython/blob/main/Doc/library/abc.rst?plain=1"599            rel="nofollow">Show source600        </a>601      </li>602      603    </ul>604  </div>605        </div>606<div id="sidebarbutton" title="Collapse sidebar">607<span>«</span>608</div>609 610      </div>611      <div class="clearer"></div>612    </div>  613    <div class="related" role="navigation" aria-label="Related">614      <h3>Navigation</h3>615      <ul>616        <li class="right" style="margin-right: 10px">617          <a href="../genindex.html" title="General Index"618             >index</a></li>619        <li class="right" >620          <a href="../py-modindex.html" title="Python Module Index"621             >modules</a> |</li>622        <li class="right" >623          <a href="atexit.html" title="atexit — Exit handlers"624             >next</a> |</li>625        <li class="right" >626          <a href="contextlib.html" title="contextlib — Utilities for with-statement contexts"627             >previous</a> |</li>628 629          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>630          <li><a href="https://www.python.org/">Python</a> &#187;</li>631          <li class="switchers">632            <div class="language_switcher_placeholder"></div>633            <div class="version_switcher_placeholder"></div>634          </li>635          <li>636              637          </li>638    <li id="cpython-language-and-version">639      <a href="../index.html">3.15.0a6 Documentation</a> &#187;640    </li>641 642          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>643          <li class="nav-item nav-item-2"><a href="python.html" >Python Runtime Services</a> &#187;</li>644        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></li>645                <li class="right">646                    647 648    <div class="inline-search" role="search">649        <form class="inline-search" action="../search.html" method="get">650          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">651          <input type="submit" value="Go">652        </form>653    </div>654                     |655                </li>656            <li class="right">657<label class="theme-selector-label">658    Theme659    <select class="theme-selector" oninput="activateTheme(this.value)">660        <option value="auto" selected>Auto</option>661        <option value="light">Light</option>662        <option value="dark">Dark</option>663    </select>664</label> |</li>665            666      </ul>667    </div>  668    <div class="footer">669    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.670    <br>671    This page is licensed under the Python Software Foundation License Version 2.672    <br>673    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.674    <br>675    676      See <a href="/license.html">History and License</a> for more information.<br>677    678    679    <br>680 681    The Python Software Foundation is a non-profit corporation.682<a href="https://www.python.org/psf/donations/">Please donate.</a>683<br>684    <br>685      Last updated on Mar 10, 2026 (08:58 UTC).686    687      <a href="/bugs.html">Found a bug</a>?688    689    <br>690 691    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.692    </div>693 694  </body>695</html>