123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
- <meta property="og:title" content="11. Brief Tour of the Standard Library — Part II" />
- <meta property="og:type" content="website" />
- <meta property="og:url" content="https://docs.python.org/3/tutorial/stdlib2.html" />
- <meta property="og:site_name" content="Python documentation" />
- <meta property="og:description" content="This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts. Output Formatting: The reprlib module provides a version of r..." />
- <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
- <meta property="og:image:alt" content="Python documentation" />
- <meta name="description" content="This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts. Output Formatting: The reprlib module provides a version of r..." />
- <meta property="og:image:width" content="200" />
- <meta property="og:image:height" content="200" />
- <meta name="theme-color" content="#3776ab" />
- <title>11. Brief Tour of the Standard Library — Part II — Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
-
- <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
- <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
- <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
-
- <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
- <script src="../_static/jquery.js"></script>
- <script src="../_static/underscore.js"></script>
- <script src="../_static/doctools.js"></script>
-
- <script src="../_static/sidebar.js"></script>
-
- <link rel="search" type="application/opensearchdescription+xml"
- title="Search within Python 3.12.0 documentation"
- href="../_static/opensearch.xml"/>
- <link rel="author" title="About these documents" href="../about.html" />
- <link rel="index" title="Index" href="../genindex.html" />
- <link rel="search" title="Search" href="../search.html" />
- <link rel="copyright" title="Copyright" href="../copyright.html" />
- <link rel="next" title="12. Virtual Environments and Packages" href="venv.html" />
- <link rel="prev" title="10. Brief Tour of the Standard Library" href="stdlib.html" />
- <link rel="canonical" href="https://docs.python.org/3/tutorial/stdlib2.html" />
-
-
-
-
- <style>
- @media only screen {
- table.full-width-table {
- width: 100%;
- }
- }
- </style>
- <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
- <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
- <script type="text/javascript" src="../_static/copybutton.js"></script>
- <script type="text/javascript" src="../_static/menu.js"></script>
- <script type="text/javascript" src="../_static/themetoggle.js"></script>
- </head>
- <body>
- <div class="mobile-nav">
- <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
- aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
- <nav class="nav-content" role="navigation">
- <label for="menuToggler" class="toggler__label">
- <span></span>
- </label>
- <span class="nav-items-wrapper">
- <a href="https://www.python.org/" class="nav-logo">
- <img src="../_static/py.svg" alt="Logo"/>
- </a>
- <span class="version_switcher_placeholder"></span>
- <form role="search" class="search" action="../search.html" method="get">
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
- <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>
- </svg>
- <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
- <input type="submit" value="Go"/>
- </form>
- </span>
- </nav>
- <div class="menu-wrapper">
- <nav class="menu" role="navigation" aria-label="main navigation">
- <div class="language_switcher_placeholder"></div>
-
- <label class="theme-selector-label">
- Theme
- <select class="theme-selector" oninput="activateTheme(this.value)">
- <option value="auto" selected>Auto</option>
- <option value="light">Light</option>
- <option value="dark">Dark</option>
- </select>
- </label>
- <div>
- <h3><a href="../contents.html">Table of Contents</a></h3>
- <ul>
- <li><a class="reference internal" href="#">11. Brief Tour of the Standard Library — Part II</a><ul>
- <li><a class="reference internal" href="#output-formatting">11.1. Output Formatting</a></li>
- <li><a class="reference internal" href="#templating">11.2. Templating</a></li>
- <li><a class="reference internal" href="#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
- <li><a class="reference internal" href="#multi-threading">11.4. Multi-threading</a></li>
- <li><a class="reference internal" href="#logging">11.5. Logging</a></li>
- <li><a class="reference internal" href="#weak-references">11.6. Weak References</a></li>
- <li><a class="reference internal" href="#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
- <li><a class="reference internal" href="#decimal-floating-point-arithmetic">11.8. Decimal Floating Point Arithmetic</a></li>
- </ul>
- </li>
- </ul>
- </div>
- <div>
- <h4>Previous topic</h4>
- <p class="topless"><a href="stdlib.html"
- title="previous chapter"><span class="section-number">10. </span>Brief Tour of the Standard Library</a></p>
- </div>
- <div>
- <h4>Next topic</h4>
- <p class="topless"><a href="venv.html"
- title="next chapter"><span class="section-number">12. </span>Virtual Environments and Packages</a></p>
- </div>
- <div role="note" aria-label="source link">
- <h3>This Page</h3>
- <ul class="this-page-menu">
- <li><a href="../bugs.html">Report a Bug</a></li>
- <li>
- <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/stdlib2.rst"
- rel="nofollow">Show Source
- </a>
- </li>
- </ul>
- </div>
- </nav>
- </div>
- </div>
-
- <div class="related" role="navigation" aria-label="related navigation">
- <h3>Navigation</h3>
- <ul>
- <li class="right" style="margin-right: 10px">
- <a href="../genindex.html" title="General Index"
- accesskey="I">index</a></li>
- <li class="right" >
- <a href="../py-modindex.html" title="Python Module Index"
- >modules</a> |</li>
- <li class="right" >
- <a href="venv.html" title="12. Virtual Environments and Packages"
- accesskey="N">next</a> |</li>
- <li class="right" >
- <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
- accesskey="P">previous</a> |</li>
- <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
- <li><a href="https://www.python.org/">Python</a> »</li>
- <li class="switchers">
- <div class="language_switcher_placeholder"></div>
- <div class="version_switcher_placeholder"></div>
- </li>
- <li>
-
- </li>
- <li id="cpython-language-and-version">
- <a href="../index.html">3.12.0 Documentation</a> »
- </li>
- <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
- <li class="nav-item nav-item-this"><a href=""><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></li>
- <li class="right">
-
- <div class="inline-search" role="search">
- <form class="inline-search" action="../search.html" method="get">
- <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
- <input type="submit" value="Go" />
- </form>
- </div>
- |
- </li>
- <li class="right">
- <label class="theme-selector-label">
- Theme
- <select class="theme-selector" oninput="activateTheme(this.value)">
- <option value="auto" selected>Auto</option>
- <option value="light">Light</option>
- <option value="dark">Dark</option>
- </select>
- </label> |</li>
-
- </ul>
- </div>
- <div class="document">
- <div class="documentwrapper">
- <div class="bodywrapper">
- <div class="body" role="main">
-
- <section id="brief-tour-of-the-standard-library-part-ii">
- <span id="tut-brieftourtwo"></span><h1><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II<a class="headerlink" href="#brief-tour-of-the-standard-library-part-ii" title="Permalink to this headline">¶</a></h1>
- <p>This second tour covers more advanced modules that support professional
- programming needs. These modules rarely occur in small scripts.</p>
- <section id="output-formatting">
- <span id="tut-output-formatting"></span><h2><span class="section-number">11.1. </span>Output Formatting<a class="headerlink" href="#output-formatting" title="Permalink to this headline">¶</a></h2>
- <p>The <a class="reference internal" href="../library/reprlib.html#module-reprlib" title="reprlib: Alternate repr() implementation with size limits."><code class="xref py py-mod docutils literal notranslate"><span class="pre">reprlib</span></code></a> module provides a version of <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> customized for
- abbreviated displays of large or deeply nested containers:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">reprlib</span>
- <span class="gp">>>> </span><span class="n">reprlib</span><span class="o">.</span><span class="n">repr</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="s1">'supercalifragilisticexpialidocious'</span><span class="p">))</span>
- <span class="go">"{'a', 'c', 'd', 'e', 'f', 'g', ...}"</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/pprint.html#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> module offers more sophisticated control over printing both
- built-in and user defined objects in a way that is readable by the interpreter.
- When the result is longer than one line, the “pretty printer” adds line breaks
- and indentation to more clearly reveal data structure:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">pprint</span>
- <span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="p">[[[[</span><span class="s1">'black'</span><span class="p">,</span> <span class="s1">'cyan'</span><span class="p">],</span> <span class="s1">'white'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'green'</span><span class="p">,</span> <span class="s1">'red'</span><span class="p">]],</span> <span class="p">[[</span><span class="s1">'magenta'</span><span class="p">,</span>
- <span class="gp">... </span> <span class="s1">'yellow'</span><span class="p">],</span> <span class="s1">'blue'</span><span class="p">]]]</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
- <span class="go">[[[['black', 'cyan'],</span>
- <span class="go"> 'white',</span>
- <span class="go"> ['green', 'red']],</span>
- <span class="go"> [['magenta', 'yellow'],</span>
- <span class="go"> 'blue']]]</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module formats paragraphs of text to fit a given screen
- width:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">textwrap</span>
- <span class="gp">>>> </span><span class="n">doc</span> <span class="o">=</span> <span class="s2">"""The wrap() method is just like fill() except that it returns</span>
- <span class="gp">... </span><span class="s2">a list of strings instead of one big string with newlines to separate</span>
- <span class="gp">... </span><span class="s2">the wrapped lines."""</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">doc</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">40</span><span class="p">))</span>
- <span class="go">The wrap() method is just like fill()</span>
- <span class="go">except that it returns a list of strings</span>
- <span class="go">instead of one big string with newlines</span>
- <span class="go">to separate the wrapped lines.</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module accesses a database of culture specific data formats.
- The grouping attribute of locale’s format function provides a direct way of
- formatting numbers with group separators:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">locale</span>
- <span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">'English_United States.1252'</span><span class="p">)</span>
- <span class="go">'English_United States.1252'</span>
- <span class="gp">>>> </span><span class="n">conv</span> <span class="o">=</span> <span class="n">locale</span><span class="o">.</span><span class="n">localeconv</span><span class="p">()</span> <span class="c1"># get a mapping of conventions</span>
- <span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mf">1234567.8</span>
- <span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">format_string</span><span class="p">(</span><span class="s2">"</span><span class="si">%d</span><span class="s2">"</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
- <span class="go">'1,234,567'</span>
- <span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">format_string</span><span class="p">(</span><span class="s2">"</span><span class="si">%s%.*f</span><span class="s2">"</span><span class="p">,</span> <span class="p">(</span><span class="n">conv</span><span class="p">[</span><span class="s1">'currency_symbol'</span><span class="p">],</span>
- <span class="gp">... </span> <span class="n">conv</span><span class="p">[</span><span class="s1">'frac_digits'</span><span class="p">],</span> <span class="n">x</span><span class="p">),</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
- <span class="go">'$1,234,567.80'</span>
- </pre></div>
- </div>
- </section>
- <section id="templating">
- <span id="tut-templating"></span><h2><span class="section-number">11.2. </span>Templating<a class="headerlink" href="#templating" title="Permalink to this headline">¶</a></h2>
- <p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module includes a versatile <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class
- with a simplified syntax suitable for editing by end-users. This allows users
- to customize their applications without having to alter the application.</p>
- <p>The format uses placeholder names formed by <code class="docutils literal notranslate"><span class="pre">$</span></code> with valid Python identifiers
- (alphanumeric characters and underscores). Surrounding the placeholder with
- braces allows it to be followed by more alphanumeric letters with no intervening
- spaces. Writing <code class="docutils literal notranslate"><span class="pre">$$</span></code> creates a single escaped <code class="docutils literal notranslate"><span class="pre">$</span></code>:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">string</span> <span class="kn">import</span> <span class="n">Template</span>
- <span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">'$</span><span class="si">{village}</span><span class="s1">folk send $$10 to $cause.'</span><span class="p">)</span>
- <span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">village</span><span class="o">=</span><span class="s1">'Nottingham'</span><span class="p">,</span> <span class="n">cause</span><span class="o">=</span><span class="s1">'the ditch fund'</span><span class="p">)</span>
- <span class="go">'Nottinghamfolk send $10 to the ditch fund.'</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/string.html#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">substitute()</span></code></a> method raises a <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> when a
- placeholder is not supplied in a dictionary or a keyword argument. For
- mail-merge style applications, user supplied data may be incomplete and the
- <a class="reference internal" href="../library/string.html#string.Template.safe_substitute" title="string.Template.safe_substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">safe_substitute()</span></code></a> method may be more appropriate —
- it will leave placeholders unchanged if data is missing:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">'Return the $item to $owner.'</span><span class="p">)</span>
- <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">item</span><span class="o">=</span><span class="s1">'unladen swallow'</span><span class="p">)</span>
- <span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
- <span class="gt">Traceback (most recent call last):</span>
- <span class="w"> </span><span class="c">...</span>
- <span class="gr">KeyError</span>: <span class="n">'owner'</span>
- <span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">safe_substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
- <span class="go">'Return the unladen swallow to $owner.'</span>
- </pre></div>
- </div>
- <p>Template subclasses can specify a custom delimiter. For example, a batch
- renaming utility for a photo browser may elect to use percent signs for
- placeholders such as the current date, image sequence number, or file format:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">time</span><span class="o">,</span> <span class="nn">os.path</span>
- <span class="gp">>>> </span><span class="n">photofiles</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'img_1074.jpg'</span><span class="p">,</span> <span class="s1">'img_1076.jpg'</span><span class="p">,</span> <span class="s1">'img_1077.jpg'</span><span class="p">]</span>
- <span class="gp">>>> </span><span class="k">class</span> <span class="nc">BatchRename</span><span class="p">(</span><span class="n">Template</span><span class="p">):</span>
- <span class="gp">... </span> <span class="n">delimiter</span> <span class="o">=</span> <span class="s1">'%'</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="n">fmt</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s1">'Enter rename style (</span><span class="si">%d</span><span class="s1">-date %n-seqnum </span><span class="si">%f</span><span class="s1">-format): '</span><span class="p">)</span>
- <span class="go">Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f</span>
- <span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">BatchRename</span><span class="p">(</span><span class="n">fmt</span><span class="p">)</span>
- <span class="gp">>>> </span><span class="n">date</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">'</span><span class="si">%d</span><span class="s1">%b%y'</span><span class="p">)</span>
- <span class="gp">>>> </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">filename</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">photofiles</span><span class="p">):</span>
- <span class="gp">... </span> <span class="n">base</span><span class="p">,</span> <span class="n">ext</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">splitext</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
- <span class="gp">... </span> <span class="n">newname</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="o">=</span><span class="n">date</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="n">i</span><span class="p">,</span> <span class="n">f</span><span class="o">=</span><span class="n">ext</span><span class="p">)</span>
- <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{0}</span><span class="s1"> --> </span><span class="si">{1}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">newname</span><span class="p">))</span>
- <span class="go">img_1074.jpg --> Ashley_0.jpg</span>
- <span class="go">img_1076.jpg --> Ashley_1.jpg</span>
- <span class="go">img_1077.jpg --> Ashley_2.jpg</span>
- </pre></div>
- </div>
- <p>Another application for templating is separating program logic from the details
- of multiple output formats. This makes it possible to substitute custom
- templates for XML files, plain text reports, and HTML web reports.</p>
- </section>
- <section id="working-with-binary-data-record-layouts">
- <span id="tut-binary-formats"></span><h2><span class="section-number">11.3. </span>Working with Binary Data Record Layouts<a class="headerlink" href="#working-with-binary-data-record-layouts" title="Permalink to this headline">¶</a></h2>
- <p>The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module provides <a class="reference internal" href="../library/struct.html#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> and
- <a class="reference internal" href="../library/struct.html#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a> functions for working with variable length binary
- record formats. The following example shows
- how to loop through header information in a ZIP file without using the
- <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module. Pack codes <code class="docutils literal notranslate"><span class="pre">"H"</span></code> and <code class="docutils literal notranslate"><span class="pre">"I"</span></code> represent two and four
- byte unsigned numbers respectively. The <code class="docutils literal notranslate"><span class="pre">"<"</span></code> indicates that they are
- standard size and in little-endian byte order:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">struct</span>
- <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'myfile.zip'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
- <span class="n">data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
- <span class="n">start</span> <span class="o">=</span> <span class="mi">0</span>
- <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span> <span class="c1"># show the first 3 file headers</span>
- <span class="n">start</span> <span class="o">+=</span> <span class="mi">14</span>
- <span class="n">fields</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s1">'<IIIHH'</span><span class="p">,</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="mi">16</span><span class="p">])</span>
- <span class="n">crc32</span><span class="p">,</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span><span class="p">,</span> <span class="n">filenamesize</span><span class="p">,</span> <span class="n">extra_size</span> <span class="o">=</span> <span class="n">fields</span>
- <span class="n">start</span> <span class="o">+=</span> <span class="mi">16</span>
- <span class="n">filename</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">filenamesize</span><span class="p">]</span>
- <span class="n">start</span> <span class="o">+=</span> <span class="n">filenamesize</span>
- <span class="n">extra</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">extra_size</span><span class="p">]</span>
- <span class="nb">print</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="nb">hex</span><span class="p">(</span><span class="n">crc32</span><span class="p">),</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span><span class="p">)</span>
- <span class="n">start</span> <span class="o">+=</span> <span class="n">extra_size</span> <span class="o">+</span> <span class="n">comp_size</span> <span class="c1"># skip to the next header</span>
- </pre></div>
- </div>
- </section>
- <section id="multi-threading">
- <span id="tut-multi-threading"></span><h2><span class="section-number">11.4. </span>Multi-threading<a class="headerlink" href="#multi-threading" title="Permalink to this headline">¶</a></h2>
- <p>Threading is a technique for decoupling tasks which are not sequentially
- dependent. Threads can be used to improve the responsiveness of applications
- that accept user input while other tasks run in the background. A related use
- case is running I/O in parallel with computations in another thread.</p>
- <p>The following code shows how the high level <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module can run
- tasks in background while the main program continues to run:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">zipfile</span>
- <span class="k">class</span> <span class="nc">AsyncZip</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">):</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">infile</span><span class="p">,</span> <span class="n">outfile</span><span class="p">):</span>
- <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
- <span class="bp">self</span><span class="o">.</span><span class="n">infile</span> <span class="o">=</span> <span class="n">infile</span>
- <span class="bp">self</span><span class="o">.</span><span class="n">outfile</span> <span class="o">=</span> <span class="n">outfile</span>
- <span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
- <span class="n">f</span> <span class="o">=</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZipFile</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">outfile</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">,</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZIP_DEFLATED</span><span class="p">)</span>
- <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">infile</span><span class="p">)</span>
- <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
- <span class="nb">print</span><span class="p">(</span><span class="s1">'Finished background zip of:'</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">infile</span><span class="p">)</span>
- <span class="n">background</span> <span class="o">=</span> <span class="n">AsyncZip</span><span class="p">(</span><span class="s1">'mydata.txt'</span><span class="p">,</span> <span class="s1">'myarchive.zip'</span><span class="p">)</span>
- <span class="n">background</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
- <span class="nb">print</span><span class="p">(</span><span class="s1">'The main program continues to run in foreground.'</span><span class="p">)</span>
- <span class="n">background</span><span class="o">.</span><span class="n">join</span><span class="p">()</span> <span class="c1"># Wait for the background task to finish</span>
- <span class="nb">print</span><span class="p">(</span><span class="s1">'Main program waited until background was done.'</span><span class="p">)</span>
- </pre></div>
- </div>
- <p>The principal challenge of multi-threaded applications is coordinating threads
- that share data or other resources. To that end, the threading module provides
- a number of synchronization primitives including locks, events, condition
- variables, and semaphores.</p>
- <p>While those tools are powerful, minor design errors can result in problems that
- are difficult to reproduce. So, the preferred approach to task coordination is
- to concentrate all access to a resource in a single thread and then use the
- <a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a> module to feed that thread with requests from other threads.
- Applications using <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> objects for inter-thread communication and
- coordination are easier to design, more readable, and more reliable.</p>
- </section>
- <section id="logging">
- <span id="tut-logging"></span><h2><span class="section-number">11.5. </span>Logging<a class="headerlink" href="#logging" title="Permalink to this headline">¶</a></h2>
- <p>The <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module offers a full featured and flexible logging system.
- At its simplest, log messages are sent to a file or to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
- <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">'Debugging information'</span><span class="p">)</span>
- <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'Informational message'</span><span class="p">)</span>
- <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'Warning:config file </span><span class="si">%s</span><span class="s1"> not found'</span><span class="p">,</span> <span class="s1">'server.conf'</span><span class="p">)</span>
- <span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">'Error occurred'</span><span class="p">)</span>
- <span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">'Critical error -- shutting down'</span><span class="p">)</span>
- </pre></div>
- </div>
- <p>This produces the following output:</p>
- <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Warning:config file server.conf not found
- ERROR:root:Error occurred
- CRITICAL:root:Critical error -- shutting down
- </pre></div>
- </div>
- <p>By default, informational and debugging messages are suppressed and the output
- is sent to standard error. Other output options include routing messages
- through email, datagrams, sockets, or to an HTTP Server. New filters can select
- different routing based on message priority: <a class="reference internal" href="../library/logging.html#logging.DEBUG" title="logging.DEBUG"><code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code></a>,
- <a class="reference internal" href="../library/logging.html#logging.INFO" title="logging.INFO"><code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.WARNING" title="logging.WARNING"><code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.ERROR" title="logging.ERROR"><code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code></a>,
- and <a class="reference internal" href="../library/logging.html#logging.CRITICAL" title="logging.CRITICAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code></a>.</p>
- <p>The logging system can be configured directly from Python or can be loaded from
- a user editable configuration file for customized logging without altering the
- application.</p>
- </section>
- <section id="weak-references">
- <span id="tut-weak-references"></span><h2><span class="section-number">11.6. </span>Weak References<a class="headerlink" href="#weak-references" title="Permalink to this headline">¶</a></h2>
- <p>Python does automatic memory management (reference counting for most objects and
- <a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> to eliminate cycles). The memory is freed shortly
- after the last reference to it has been eliminated.</p>
- <p>This approach works fine for most applications but occasionally there is a need
- to track objects only as long as they are being used by something else.
- Unfortunately, just tracking them creates a reference that makes them permanent.
- The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module provides tools for tracking objects without creating a
- reference. When the object is no longer needed, it is automatically removed
- from a weakref table and a callback is triggered for weakref objects. Typical
- applications include caching objects that are expensive to create:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">weakref</span><span class="o">,</span> <span class="nn">gc</span>
- <span class="gp">>>> </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
- <span class="gp">... </span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
- <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
- <span class="gp">... </span> <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
- <span class="gp">... </span> <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
- <span class="gp">...</span>
- <span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># create a reference</span>
- <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakValueDictionary</span><span class="p">()</span>
- <span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span> <span class="c1"># does not create a reference</span>
- <span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="c1"># fetch the object if it is still alive</span>
- <span class="go">10</span>
- <span class="gp">>>> </span><span class="k">del</span> <span class="n">a</span> <span class="c1"># remove the one reference</span>
- <span class="gp">>>> </span><span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span> <span class="c1"># run garbage collection right away</span>
- <span class="go">0</span>
- <span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="c1"># entry was automatically removed</span>
- <span class="gt">Traceback (most recent call last):</span>
- File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
- <span class="w"> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="c1"># entry was automatically removed</span>
- File <span class="nb">"C:/python312/lib/weakref.py"</span>, line <span class="m">46</span>, in <span class="n">__getitem__</span>
- <span class="w"> </span><span class="n">o</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="n">key</span><span class="p">]()</span>
- <span class="gr">KeyError</span>: <span class="n">'primary'</span>
- </pre></div>
- </div>
- </section>
- <section id="tools-for-working-with-lists">
- <span id="tut-list-tools"></span><h2><span class="section-number">11.7. </span>Tools for Working with Lists<a class="headerlink" href="#tools-for-working-with-lists" title="Permalink to this headline">¶</a></h2>
- <p>Many data structure needs can be met with the built-in list type. However,
- sometimes there is a need for alternative implementations with different
- performance trade-offs.</p>
- <p>The <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module provides an <a class="reference internal" href="../library/array.html#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array()</span></code></a> object that is like
- a list that stores only homogeneous data and stores it more compactly. The
- following example shows an array of numbers stored as two byte unsigned binary
- numbers (typecode <code class="docutils literal notranslate"><span class="pre">"H"</span></code>) rather than the usual 16 bytes per entry for regular
- lists of Python int objects:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">array</span> <span class="kn">import</span> <span class="n">array</span>
- <span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="p">(</span><span class="s1">'H'</span><span class="p">,</span> <span class="p">[</span><span class="mi">4000</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">700</span><span class="p">,</span> <span class="mi">22222</span><span class="p">])</span>
- <span class="gp">>>> </span><span class="nb">sum</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
- <span class="go">26932</span>
- <span class="gp">>>> </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span>
- <span class="go">array('H', [10, 700])</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/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 provides a <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque()</span></code></a> object
- that is like a list with faster appends and pops from the left side but slower
- lookups in the middle. These objects are well suited for implementing queues
- and breadth first tree searches:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
- <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="s2">"task1"</span><span class="p">,</span> <span class="s2">"task2"</span><span class="p">,</span> <span class="s2">"task3"</span><span class="p">])</span>
- <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"task4"</span><span class="p">)</span>
- <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s2">"Handling"</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">())</span>
- <span class="go">Handling task1</span>
- </pre></div>
- </div>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">unsearched</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="n">starting_node</span><span class="p">])</span>
- <span class="k">def</span> <span class="nf">breadth_first_search</span><span class="p">(</span><span class="n">unsearched</span><span class="p">):</span>
- <span class="n">node</span> <span class="o">=</span> <span class="n">unsearched</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
- <span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">gen_moves</span><span class="p">(</span><span class="n">node</span><span class="p">):</span>
- <span class="k">if</span> <span class="n">is_goal</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
- <span class="k">return</span> <span class="n">m</span>
- <span class="n">unsearched</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
- </pre></div>
- </div>
- <p>In addition to alternative list implementations, the library also offers other
- tools such as the <a class="reference internal" href="../library/bisect.html#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code></a> module with functions for manipulating sorted
- lists:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">bisect</span>
- <span class="gp">>>> </span><span class="n">scores</span> <span class="o">=</span> <span class="p">[(</span><span class="mi">100</span><span class="p">,</span> <span class="s1">'perl'</span><span class="p">),</span> <span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="s1">'tcl'</span><span class="p">),</span> <span class="p">(</span><span class="mi">400</span><span class="p">,</span> <span class="s1">'lua'</span><span class="p">),</span> <span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="s1">'python'</span><span class="p">)]</span>
- <span class="gp">>>> </span><span class="n">bisect</span><span class="o">.</span><span class="n">insort</span><span class="p">(</span><span class="n">scores</span><span class="p">,</span> <span class="p">(</span><span class="mi">300</span><span class="p">,</span> <span class="s1">'ruby'</span><span class="p">))</span>
- <span class="gp">>>> </span><span class="n">scores</span>
- <span class="go">[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module provides functions for implementing heaps based on
- regular lists. The lowest valued entry is always kept at position zero. This
- is useful for applications which repeatedly access the smallest element but do
- not want to run a full list sort:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">heapq</span> <span class="kn">import</span> <span class="n">heapify</span><span class="p">,</span> <span class="n">heappop</span><span class="p">,</span> <span class="n">heappush</span>
- <span class="gp">>>> </span><span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">]</span>
- <span class="gp">>>> </span><span class="n">heapify</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="c1"># rearrange the list into heap order</span>
- <span class="gp">>>> </span><span class="n">heappush</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">)</span> <span class="c1"># add a new entry</span>
- <span class="gp">>>> </span><span class="p">[</span><span class="n">heappop</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span> <span class="c1"># fetch the three smallest entries</span>
- <span class="go">[-5, 0, 1]</span>
- </pre></div>
- </div>
- </section>
- <section id="decimal-floating-point-arithmetic">
- <span id="tut-decimal-fp"></span><h2><span class="section-number">11.8. </span>Decimal Floating Point Arithmetic<a class="headerlink" href="#decimal-floating-point-arithmetic" title="Permalink to this headline">¶</a></h2>
- <p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module offers a <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> datatype for
- decimal floating point arithmetic. Compared to the built-in <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>
- implementation of binary floating point, the class is especially helpful for</p>
- <ul class="simple">
- <li><p>financial applications and other uses which require exact decimal
- representation,</p></li>
- <li><p>control over precision,</p></li>
- <li><p>control over rounding to meet legal or regulatory requirements,</p></li>
- <li><p>tracking of significant decimal places, or</p></li>
- <li><p>applications where the user expects the results to match calculations done by
- hand.</p></li>
- </ul>
- <p>For example, calculating a 5% tax on a 70 cent phone charge gives different
- results in decimal floating point and binary floating point. The difference
- becomes significant if the results are rounded to the nearest cent:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="kn">import</span> <span class="o">*</span>
- <span class="gp">>>> </span><span class="nb">round</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">'0.70'</span><span class="p">)</span> <span class="o">*</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">'1.05'</span><span class="p">),</span> <span class="mi">2</span><span class="p">)</span>
- <span class="go">Decimal('0.74')</span>
- <span class="gp">>>> </span><span class="nb">round</span><span class="p">(</span><span class="mf">.70</span> <span class="o">*</span> <span class="mf">1.05</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
- <span class="go">0.73</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> result keeps a trailing zero, automatically
- inferring four place significance from multiplicands with two place
- significance. Decimal reproduces mathematics as done by hand and avoids
- issues that can arise when binary floating point cannot exactly represent
- decimal quantities.</p>
- <p>Exact representation enables the <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class to perform
- modulo calculations and equality tests that are unsuitable for binary floating
- point:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">'1.00'</span><span class="p">)</span> <span class="o">%</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">'.10'</span><span class="p">)</span>
- <span class="go">Decimal('0.00')</span>
- <span class="gp">>>> </span><span class="mf">1.00</span> <span class="o">%</span> <span class="mf">0.10</span>
- <span class="go">0.09999999999999995</span>
- <span class="gp">>>> </span><span class="nb">sum</span><span class="p">([</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">'0.1'</span><span class="p">)]</span><span class="o">*</span><span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">'1.0'</span><span class="p">)</span>
- <span class="go">True</span>
- <span class="gp">>>> </span><span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">==</span> <span class="mf">1.0</span>
- <span class="go">False</span>
- </pre></div>
- </div>
- <p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module provides arithmetic with as much precision as needed:</p>
- <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">36</span>
- <span class="gp">>>> </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
- <span class="go">Decimal('0.142857142857142857142857142857142857')</span>
- </pre></div>
- </div>
- </section>
- </section>
- <div class="clearer"></div>
- </div>
- </div>
- </div>
- <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
- <div class="sphinxsidebarwrapper">
- <div>
- <h3><a href="../contents.html">Table of Contents</a></h3>
- <ul>
- <li><a class="reference internal" href="#">11. Brief Tour of the Standard Library — Part II</a><ul>
- <li><a class="reference internal" href="#output-formatting">11.1. Output Formatting</a></li>
- <li><a class="reference internal" href="#templating">11.2. Templating</a></li>
- <li><a class="reference internal" href="#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
- <li><a class="reference internal" href="#multi-threading">11.4. Multi-threading</a></li>
- <li><a class="reference internal" href="#logging">11.5. Logging</a></li>
- <li><a class="reference internal" href="#weak-references">11.6. Weak References</a></li>
- <li><a class="reference internal" href="#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
- <li><a class="reference internal" href="#decimal-floating-point-arithmetic">11.8. Decimal Floating Point Arithmetic</a></li>
- </ul>
- </li>
- </ul>
- </div>
- <div>
- <h4>Previous topic</h4>
- <p class="topless"><a href="stdlib.html"
- title="previous chapter"><span class="section-number">10. </span>Brief Tour of the Standard Library</a></p>
- </div>
- <div>
- <h4>Next topic</h4>
- <p class="topless"><a href="venv.html"
- title="next chapter"><span class="section-number">12. </span>Virtual Environments and Packages</a></p>
- </div>
- <div role="note" aria-label="source link">
- <h3>This Page</h3>
- <ul class="this-page-menu">
- <li><a href="../bugs.html">Report a Bug</a></li>
- <li>
- <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/stdlib2.rst"
- rel="nofollow">Show Source
- </a>
- </li>
- </ul>
- </div>
- </div>
- </div>
- <div class="clearer"></div>
- </div>
- <div class="related" role="navigation" aria-label="related navigation">
- <h3>Navigation</h3>
- <ul>
- <li class="right" style="margin-right: 10px">
- <a href="../genindex.html" title="General Index"
- >index</a></li>
- <li class="right" >
- <a href="../py-modindex.html" title="Python Module Index"
- >modules</a> |</li>
- <li class="right" >
- <a href="venv.html" title="12. Virtual Environments and Packages"
- >next</a> |</li>
- <li class="right" >
- <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
- >previous</a> |</li>
- <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
- <li><a href="https://www.python.org/">Python</a> »</li>
- <li class="switchers">
- <div class="language_switcher_placeholder"></div>
- <div class="version_switcher_placeholder"></div>
- </li>
- <li>
-
- </li>
- <li id="cpython-language-and-version">
- <a href="../index.html">3.12.0 Documentation</a> »
- </li>
- <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
- <li class="nav-item nav-item-this"><a href=""><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></li>
- <li class="right">
-
- <div class="inline-search" role="search">
- <form class="inline-search" action="../search.html" method="get">
- <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
- <input type="submit" value="Go" />
- </form>
- </div>
- |
- </li>
- <li class="right">
- <label class="theme-selector-label">
- Theme
- <select class="theme-selector" oninput="activateTheme(this.value)">
- <option value="auto" selected>Auto</option>
- <option value="light">Light</option>
- <option value="dark">Dark</option>
- </select>
- </label> |</li>
-
- </ul>
- </div>
- <div class="footer">
- © <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
- <br />
- This page is licensed under the Python Software Foundation License Version 2.
- <br />
- Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
- <br />
- See <a href="/license.html">History and License</a> for more information.<br />
- <br />
- The Python Software Foundation is a non-profit corporation.
- <a href="https://www.python.org/psf/donations/">Please donate.</a>
- <br />
- <br />
- Last updated on Oct 02, 2023.
- <a href="/bugs.html">Found a bug</a>?
- <br />
- Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
- </div>
- </body>
- </html>
|