Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
graphlib.html568 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="graphlib — Functionality to operate with graph-like structures" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/graphlib.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/graphlib.py Exceptions: The graphlib module defines the following exception classes:" />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_graphlib_ce17f98e.png" />15<meta property="og:image:alt" content="Source code: Lib/graphlib.py Exceptions: The graphlib module defines the following exception classes:" />16<meta name="description" content="Source code: Lib/graphlib.py Exceptions: The graphlib module defines the following exception classes:" />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>graphlib — Functionality to operate with graph-like structures &#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="Numeric and Mathematical Modules" href="numeric.html" />43    <link rel="prev" title="enum — Support for enumerations" href="enum.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/graphlib.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">graphlib</span></code> — Functionality to operate with graph-like structures</a><ul>108<li><a class="reference internal" href="#exceptions">Exceptions</a></li>109</ul>110</li>111</ul>112 113  </div>114  <div>115    <h4>Previous topic</h4>116    <p class="topless"><a href="enum.html"117                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">enum</span></code> — Support for enumerations</a></p>118  </div>119  <div>120    <h4>Next topic</h4>121    <p class="topless"><a href="numeric.html"122                          title="next chapter">Numeric and Mathematical Modules</a></p>123  </div>124  <script>125    document.addEventListener('DOMContentLoaded', () => {126        const title = document.querySelector('meta[property="og:title"]').content;127        const elements = document.querySelectorAll('.improvepage');128        const pageurl = window.location.href.split('?')[0];129        elements.forEach(element => {130            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));131            url.searchParams.set('pagetitle', title);132            url.searchParams.set('pageurl', pageurl);133            url.searchParams.set('pagesource', "library/graphlib.rst");134            element.href = url.toString();135        });136    });137  </script>138  <div role="note" aria-label="source link">139    <h3>This page</h3>140    <ul class="this-page-menu">141      <li><a href="../bugs.html">Report a bug</a></li>142      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>143      <li>144        <a href="https://github.com/python/cpython/blob/main/Doc/library/graphlib.rst?plain=1"145            rel="nofollow">Show source146        </a>147      </li>148      149    </ul>150  </div>151        </nav>152    </div>153</div>154 155  156    <div class="related" role="navigation" aria-label="Related">157      <h3>Navigation</h3>158      <ul>159        <li class="right" style="margin-right: 10px">160          <a href="../genindex.html" title="General Index"161             accesskey="I">index</a></li>162        <li class="right" >163          <a href="../py-modindex.html" title="Python Module Index"164             >modules</a> |</li>165        <li class="right" >166          <a href="numeric.html" title="Numeric and Mathematical Modules"167             accesskey="N">next</a> |</li>168        <li class="right" >169          <a href="enum.html" title="enum — Support for enumerations"170             accesskey="P">previous</a> |</li>171 172          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>173          <li><a href="https://www.python.org/">Python</a> &#187;</li>174          <li class="switchers">175            <div class="language_switcher_placeholder"></div>176            <div class="version_switcher_placeholder"></div>177          </li>178          <li>179              180          </li>181    <li id="cpython-language-and-version">182      <a href="../index.html">3.15.0a6 Documentation</a> &#187;183    </li>184 185          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>186          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">Data Types</a> &#187;</li>187        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">graphlib</span></code> — Functionality to operate with graph-like structures</a></li>188                <li class="right">189                    190 191    <div class="inline-search" role="search">192        <form class="inline-search" action="../search.html" method="get">193          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">194          <input type="submit" value="Go">195        </form>196    </div>197                     |198                </li>199            <li class="right">200<label class="theme-selector-label">201    Theme202    <select class="theme-selector" oninput="activateTheme(this.value)">203        <option value="auto" selected>Auto</option>204        <option value="light">Light</option>205        <option value="dark">Dark</option>206    </select>207</label> |</li>208            209      </ul>210    </div>    211 212    <div class="document">213      <div class="documentwrapper">214        <div class="bodywrapper">215          <div class="body" role="main">216            217  <section id="module-graphlib">218<span id="graphlib-functionality-to-operate-with-graph-like-structures"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">graphlib</span></code> — Functionality to operate with graph-like structures<a class="headerlink" href="#module-graphlib" title="Link to this heading">¶</a></h1>219<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/graphlib.py">Lib/graphlib.py</a></p>220<hr class="docutils" />221<dl class="py class">222<dt class="sig sig-object py" id="graphlib.TopologicalSorter">223<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">graphlib.</span></span><span class="sig-name descname"><span class="pre">TopologicalSorter</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">graph</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#graphlib.TopologicalSorter" title="Link to this definition">¶</a></dt>224<dd><p>Provides functionality to topologically sort a graph of <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> nodes.</p>225<p>A topological order is a linear ordering of the vertices in a graph such that226for every directed edge u -&gt; v from vertex u to vertex v, vertex u comes227before vertex v in the ordering. For instance, the vertices of the graph may228represent tasks to be performed, and the edges may represent constraints that229one task must be performed before another; in this example, a topological230ordering is just a valid sequence for the tasks. A complete topological231ordering is possible if and only if the graph has no directed cycles, that232is, if it is a directed acyclic graph.</p>233<p>If the optional <em>graph</em> argument is provided it must be a dictionary234representing a directed acyclic graph where the keys are nodes and the values235are iterables of all predecessors of that node in the graph (the nodes that236have edges that point to the value in the key). Additional nodes can be added237to the graph using the <a class="reference internal" href="#graphlib.TopologicalSorter.add" title="graphlib.TopologicalSorter.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> method.</p>238<p>In the general case, the steps required to perform the sorting of a given239graph are as follows:</p>240<ul class="simple">241<li><p>Create an instance of the <code class="xref py py-class docutils literal notranslate"><span class="pre">TopologicalSorter</span></code> with an optional242initial graph.</p></li>243<li><p>Add additional nodes to the graph.</p></li>244<li><p>Call <a class="reference internal" href="#graphlib.TopologicalSorter.prepare" title="graphlib.TopologicalSorter.prepare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prepare()</span></code></a> on the graph.</p></li>245<li><p>While <a class="reference internal" href="#graphlib.TopologicalSorter.is_active" title="graphlib.TopologicalSorter.is_active"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_active()</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, iterate over246the nodes returned by <a class="reference internal" href="#graphlib.TopologicalSorter.get_ready" title="graphlib.TopologicalSorter.get_ready"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_ready()</span></code></a> and247process them. Call <a class="reference internal" href="#graphlib.TopologicalSorter.done" title="graphlib.TopologicalSorter.done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">done()</span></code></a> on each node as it248finishes processing.</p></li>249</ul>250<p>In case just an immediate sorting of the nodes in the graph is required and251no parallelism is involved, the convenience method252<a class="reference internal" href="#graphlib.TopologicalSorter.static_order" title="graphlib.TopologicalSorter.static_order"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.static_order()</span></code></a> can be used directly:</p>253<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">graph</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;D&quot;</span><span class="p">:</span> <span class="p">{</span><span class="s2">&quot;B&quot;</span><span class="p">,</span> <span class="s2">&quot;C&quot;</span><span class="p">},</span> <span class="s2">&quot;C&quot;</span><span class="p">:</span> <span class="p">{</span><span class="s2">&quot;A&quot;</span><span class="p">},</span> <span class="s2">&quot;B&quot;</span><span class="p">:</span> <span class="p">{</span><span class="s2">&quot;A&quot;</span><span class="p">}}</span>254<span class="gp">&gt;&gt;&gt; </span><span class="n">ts</span> <span class="o">=</span> <span class="n">TopologicalSorter</span><span class="p">(</span><span class="n">graph</span><span class="p">)</span>255<span class="gp">&gt;&gt;&gt; </span><span class="nb">tuple</span><span class="p">(</span><span class="n">ts</span><span class="o">.</span><span class="n">static_order</span><span class="p">())</span>256<span class="go">(&#39;A&#39;, &#39;C&#39;, &#39;B&#39;, &#39;D&#39;)</span>257</pre></div>258</div>259<p>The class is designed to easily support parallel processing of the nodes as260they become ready. For instance:</p>261<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">topological_sorter</span> <span class="o">=</span> <span class="n">TopologicalSorter</span><span class="p">()</span>262 263<span class="c1"># Add nodes to &#39;topological_sorter&#39;...</span>264 265<span class="n">topological_sorter</span><span class="o">.</span><span class="n">prepare</span><span class="p">()</span>266<span class="k">while</span> <span class="n">topological_sorter</span><span class="o">.</span><span class="n">is_active</span><span class="p">():</span>267    <span class="k">for</span> <span class="n">node</span> <span class="ow">in</span> <span class="n">topological_sorter</span><span class="o">.</span><span class="n">get_ready</span><span class="p">():</span>268        <span class="c1"># Worker threads or processes take nodes to work on off the</span>269        <span class="c1"># &#39;task_queue&#39; queue.</span>270        <span class="n">task_queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>271 272    <span class="c1"># When the work for a node is done, workers put the node in</span>273    <span class="c1"># &#39;finalized_tasks_queue&#39; so we can get more nodes to work on.</span>274    <span class="c1"># The definition of &#39;is_active()&#39; guarantees that, at this point, at</span>275    <span class="c1"># least one node has been placed on &#39;task_queue&#39; that hasn&#39;t yet</span>276    <span class="c1"># been passed to &#39;done()&#39;, so this blocking &#39;get()&#39; must (eventually)</span>277    <span class="c1"># succeed.  After calling &#39;done()&#39;, we loop back to call &#39;get_ready()&#39;</span>278    <span class="c1"># again, so put newly freed nodes on &#39;task_queue&#39; as soon as</span>279    <span class="c1"># logically possible.</span>280    <span class="n">node</span> <span class="o">=</span> <span class="n">finalized_tasks_queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>281    <span class="n">topological_sorter</span><span class="o">.</span><span class="n">done</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>282</pre></div>283</div>284<dl class="py method">285<dt class="sig sig-object py" id="graphlib.TopologicalSorter.add">286<span class="sig-name descname"><span class="pre">add</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">node</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">predecessors</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#graphlib.TopologicalSorter.add" title="Link to this definition">¶</a></dt>287<dd><p>Add a new node and its predecessors to the graph. Both the <em>node</em> and all288elements in <em>predecessors</em> must be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>.</p>289<p>If called multiple times with the same node argument, the set of290dependencies will be the union of all dependencies passed in.</p>291<p>It is possible to add a node with no dependencies (<em>predecessors</em> is not292provided) or to provide a dependency twice. If a node that has not been293provided before is included among <em>predecessors</em> it will be automatically294added to the graph with no predecessors of its own.</p>295<p>Raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if called after <a class="reference internal" href="#graphlib.TopologicalSorter.prepare" title="graphlib.TopologicalSorter.prepare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prepare()</span></code></a>.</p>296</dd></dl>297 298<dl class="py method">299<dt class="sig sig-object py" id="graphlib.TopologicalSorter.prepare">300<span class="sig-name descname"><span class="pre">prepare</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#graphlib.TopologicalSorter.prepare" title="Link to this definition">¶</a></dt>301<dd><p>Mark the graph as finished and check for cycles in the graph. If any cycle302is detected, <a class="reference internal" href="#graphlib.CycleError" title="graphlib.CycleError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CycleError</span></code></a> will be raised, but303<a class="reference internal" href="#graphlib.TopologicalSorter.get_ready" title="graphlib.TopologicalSorter.get_ready"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_ready()</span></code></a> can still be used to obtain as many304nodes as possible until cycles block more progress. After a call to this305function, the graph cannot be modified, and therefore no more nodes can be306added using <a class="reference internal" href="#graphlib.TopologicalSorter.add" title="graphlib.TopologicalSorter.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a>.</p>307<p>A <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised if the sort has been started by308<a class="reference internal" href="#graphlib.TopologicalSorter.static_order" title="graphlib.TopologicalSorter.static_order"><code class="xref py py-meth docutils literal notranslate"><span class="pre">static_order()</span></code></a> or <a class="reference internal" href="#graphlib.TopologicalSorter.get_ready" title="graphlib.TopologicalSorter.get_ready"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_ready()</span></code></a>.</p>309<div class="versionchanged">310<p><span class="versionmodified changed">Changed in version 3.14: </span><code class="docutils literal notranslate"><span class="pre">prepare()</span></code> can now be called more than once as long as the sort has311not started. Previously this raised <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>312</div>313</dd></dl>314 315<dl class="py method">316<dt class="sig sig-object py" id="graphlib.TopologicalSorter.is_active">317<span class="sig-name descname"><span class="pre">is_active</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#graphlib.TopologicalSorter.is_active" title="Link to this definition">¶</a></dt>318<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if more progress can be made and <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.319Progress can be made if cycles do not block the resolution and either320there are still nodes ready that haven’t yet been returned by321<a class="reference internal" href="#graphlib.TopologicalSorter.get_ready" title="graphlib.TopologicalSorter.get_ready"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.get_ready()</span></code></a> or the number of nodes marked322<a class="reference internal" href="#graphlib.TopologicalSorter.done" title="graphlib.TopologicalSorter.done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.done()</span></code></a> is less than the number that have been323returned by <code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.get_ready()</span></code>.</p>324<p>The <a class="reference internal" href="../reference/datamodel.html#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> method of this class defers to325this function, so instead of:</p>326<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">ts</span><span class="o">.</span><span class="n">is_active</span><span class="p">():</span>327    <span class="o">...</span>328</pre></div>329</div>330<p>it is possible to simply do:</p>331<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">ts</span><span class="p">:</span>332    <span class="o">...</span>333</pre></div>334</div>335<p>Raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if called without calling336<a class="reference internal" href="#graphlib.TopologicalSorter.prepare" title="graphlib.TopologicalSorter.prepare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prepare()</span></code></a> previously.</p>337</dd></dl>338 339<dl class="py method">340<dt class="sig sig-object py" id="graphlib.TopologicalSorter.done">341<span class="sig-name descname"><span class="pre">done</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">nodes</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#graphlib.TopologicalSorter.done" title="Link to this definition">¶</a></dt>342<dd><p>Marks a set of nodes returned by <a class="reference internal" href="#graphlib.TopologicalSorter.get_ready" title="graphlib.TopologicalSorter.get_ready"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.get_ready()</span></code></a> as343processed, unblocking any successor of each node in <em>nodes</em> for being344returned in the future by a call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.get_ready()</span></code>.</p>345<p>Raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if any node in <em>nodes</em> has already been marked as346processed by a previous call to this method or if a node was not added to347the graph by using <a class="reference internal" href="#graphlib.TopologicalSorter.add" title="graphlib.TopologicalSorter.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.add()</span></code></a>, if called without348calling <a class="reference internal" href="#graphlib.TopologicalSorter.prepare" title="graphlib.TopologicalSorter.prepare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prepare()</span></code></a> or if node has not yet been349returned by <a class="reference internal" href="#graphlib.TopologicalSorter.get_ready" title="graphlib.TopologicalSorter.get_ready"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_ready()</span></code></a>.</p>350</dd></dl>351 352<dl class="py method">353<dt class="sig sig-object py" id="graphlib.TopologicalSorter.get_ready">354<span class="sig-name descname"><span class="pre">get_ready</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#graphlib.TopologicalSorter.get_ready" title="Link to this definition">¶</a></dt>355<dd><p>Returns a <code class="docutils literal notranslate"><span class="pre">tuple</span></code> with all the nodes that are ready. Initially it356returns all nodes with no predecessors, and once those are marked as357processed by calling <a class="reference internal" href="#graphlib.TopologicalSorter.done" title="graphlib.TopologicalSorter.done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.done()</span></code></a>, further calls will358return all new nodes that have all their predecessors already processed.359Once no more progress can be made, empty tuples are returned.</p>360<p>Raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if called without calling361<a class="reference internal" href="#graphlib.TopologicalSorter.prepare" title="graphlib.TopologicalSorter.prepare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prepare()</span></code></a> previously.</p>362</dd></dl>363 364<dl class="py method">365<dt class="sig sig-object py" id="graphlib.TopologicalSorter.static_order">366<span class="sig-name descname"><span class="pre">static_order</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#graphlib.TopologicalSorter.static_order" title="Link to this definition">¶</a></dt>367<dd><p>Returns an iterator object which will iterate over nodes in a topological368order. When using this method, <a class="reference internal" href="#graphlib.TopologicalSorter.prepare" title="graphlib.TopologicalSorter.prepare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prepare()</span></code></a> and369<a class="reference internal" href="#graphlib.TopologicalSorter.done" title="graphlib.TopologicalSorter.done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">done()</span></code></a> should not be called. This method is370equivalent to:</p>371<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">static_order</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>372    <span class="bp">self</span><span class="o">.</span><span class="n">prepare</span><span class="p">()</span>373    <span class="k">while</span> <span class="bp">self</span><span class="o">.</span><span class="n">is_active</span><span class="p">():</span>374        <span class="n">node_group</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_ready</span><span class="p">()</span>375        <span class="k">yield from</span> <span class="n">node_group</span>376        <span class="bp">self</span><span class="o">.</span><span class="n">done</span><span class="p">(</span><span class="o">*</span><span class="n">node_group</span><span class="p">)</span>377</pre></div>378</div>379<p>The particular order that is returned may depend on the specific order in380which the items were inserted in the graph. For example:</p>381<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ts</span> <span class="o">=</span> <span class="n">TopologicalSorter</span><span class="p">()</span>382<span class="gp">&gt;&gt;&gt; </span><span class="n">ts</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>383<span class="gp">&gt;&gt;&gt; </span><span class="n">ts</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>384<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">([</span><span class="o">*</span><span class="n">ts</span><span class="o">.</span><span class="n">static_order</span><span class="p">()])</span>385<span class="go">[2, 0, 1, 3]</span>386 387<span class="gp">&gt;&gt;&gt; </span><span class="n">ts2</span> <span class="o">=</span> <span class="n">TopologicalSorter</span><span class="p">()</span>388<span class="gp">&gt;&gt;&gt; </span><span class="n">ts2</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>389<span class="gp">&gt;&gt;&gt; </span><span class="n">ts2</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>390<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">([</span><span class="o">*</span><span class="n">ts2</span><span class="o">.</span><span class="n">static_order</span><span class="p">()])</span>391<span class="go">[0, 2, 1, 3]</span>392</pre></div>393</div>394<p>This is due to the fact that “0” and “2” are in the same level in the395graph (they would have been returned in the same call to396<a class="reference internal" href="#graphlib.TopologicalSorter.get_ready" title="graphlib.TopologicalSorter.get_ready"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_ready()</span></code></a>) and the order between them is397determined by the order of insertion.</p>398<p>If any cycle is detected, <a class="reference internal" href="#graphlib.CycleError" title="graphlib.CycleError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CycleError</span></code></a> will be raised.</p>399</dd></dl>400 401<div class="versionadded">402<p><span class="versionmodified added">Added in version 3.9.</span></p>403</div>404</dd></dl>405 406<section id="exceptions">407<h2>Exceptions<a class="headerlink" href="#exceptions" title="Link to this heading">¶</a></h2>408<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">graphlib</span></code> module defines the following exception classes:</p>409<dl class="py exception">410<dt class="sig sig-object py" id="graphlib.CycleError">411<em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">graphlib.</span></span><span class="sig-name descname"><span class="pre">CycleError</span></span><a class="headerlink" href="#graphlib.CycleError" title="Link to this definition">¶</a></dt>412<dd><p>Subclass of <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> raised by <a class="reference internal" href="#graphlib.TopologicalSorter.prepare" title="graphlib.TopologicalSorter.prepare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TopologicalSorter.prepare()</span></code></a> if cycles exist413in the working graph. If multiple cycles exist, only one undefined choice among them will414be reported and included in the exception.</p>415<p>The detected cycle can be accessed via the second element in the <a class="reference internal" href="exceptions.html#BaseException.args" title="BaseException.args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code></a>416attribute of the exception instance and consists in a list of nodes, such that each node is,417in the graph, an immediate predecessor of the next node in the list. In the reported list,418the first and the last node will be the same, to make it clear that it is cyclic.</p>419</dd></dl>420 421</section>422</section>423 424 425            <div class="clearer"></div>426          </div>427        </div>428      </div>429      <div class="sphinxsidebar" role="navigation" aria-label="Main">430        <div class="sphinxsidebarwrapper">431  <div>432    <h3><a href="../contents.html">Table of Contents</a></h3>433    <ul>434<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">graphlib</span></code> — Functionality to operate with graph-like structures</a><ul>435<li><a class="reference internal" href="#exceptions">Exceptions</a></li>436</ul>437</li>438</ul>439 440  </div>441  <div>442    <h4>Previous topic</h4>443    <p class="topless"><a href="enum.html"444                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">enum</span></code> — Support for enumerations</a></p>445  </div>446  <div>447    <h4>Next topic</h4>448    <p class="topless"><a href="numeric.html"449                          title="next chapter">Numeric and Mathematical Modules</a></p>450  </div>451  <script>452    document.addEventListener('DOMContentLoaded', () => {453        const title = document.querySelector('meta[property="og:title"]').content;454        const elements = document.querySelectorAll('.improvepage');455        const pageurl = window.location.href.split('?')[0];456        elements.forEach(element => {457            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));458            url.searchParams.set('pagetitle', title);459            url.searchParams.set('pageurl', pageurl);460            url.searchParams.set('pagesource', "library/graphlib.rst");461            element.href = url.toString();462        });463    });464  </script>465  <div role="note" aria-label="source link">466    <h3>This page</h3>467    <ul class="this-page-menu">468      <li><a href="../bugs.html">Report a bug</a></li>469      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>470      <li>471        <a href="https://github.com/python/cpython/blob/main/Doc/library/graphlib.rst?plain=1"472            rel="nofollow">Show source473        </a>474      </li>475      476    </ul>477  </div>478        </div>479<div id="sidebarbutton" title="Collapse sidebar">480<span>«</span>481</div>482 483      </div>484      <div class="clearer"></div>485    </div>  486    <div class="related" role="navigation" aria-label="Related">487      <h3>Navigation</h3>488      <ul>489        <li class="right" style="margin-right: 10px">490          <a href="../genindex.html" title="General Index"491             >index</a></li>492        <li class="right" >493          <a href="../py-modindex.html" title="Python Module Index"494             >modules</a> |</li>495        <li class="right" >496          <a href="numeric.html" title="Numeric and Mathematical Modules"497             >next</a> |</li>498        <li class="right" >499          <a href="enum.html" title="enum — Support for enumerations"500             >previous</a> |</li>501 502          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>503          <li><a href="https://www.python.org/">Python</a> &#187;</li>504          <li class="switchers">505            <div class="language_switcher_placeholder"></div>506            <div class="version_switcher_placeholder"></div>507          </li>508          <li>509              510          </li>511    <li id="cpython-language-and-version">512      <a href="../index.html">3.15.0a6 Documentation</a> &#187;513    </li>514 515          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>516          <li class="nav-item nav-item-2"><a href="datatypes.html" >Data Types</a> &#187;</li>517        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">graphlib</span></code> — Functionality to operate with graph-like structures</a></li>518                <li class="right">519                    520 521    <div class="inline-search" role="search">522        <form class="inline-search" action="../search.html" method="get">523          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">524          <input type="submit" value="Go">525        </form>526    </div>527                     |528                </li>529            <li class="right">530<label class="theme-selector-label">531    Theme532    <select class="theme-selector" oninput="activateTheme(this.value)">533        <option value="auto" selected>Auto</option>534        <option value="light">Light</option>535        <option value="dark">Dark</option>536    </select>537</label> |</li>538            539      </ul>540    </div>  541    <div class="footer">542    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.543    <br>544    This page is licensed under the Python Software Foundation License Version 2.545    <br>546    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.547    <br>548    549      See <a href="/license.html">History and License</a> for more information.<br>550    551    552    <br>553 554    The Python Software Foundation is a non-profit corporation.555<a href="https://www.python.org/psf/donations/">Please donate.</a>556<br>557    <br>558      Last updated on Mar 10, 2026 (08:58 UTC).559    560      <a href="/bugs.html">Found a bug</a>?561    562    <br>563 564    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.565    </div>566 567  </body>568</html>