556 lines
57 KiB
HTML
556 lines
57 KiB
HTML
|
||
<!DOCTYPE html>
|
||
|
||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<title>11. Brief Tour of the Standard Library — Part II — Python 3.7.4 documentation</title>
|
||
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
|
||
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
|
||
|
||
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
|
||
<script type="text/javascript" src="../_static/jquery.js"></script>
|
||
<script type="text/javascript" src="../_static/underscore.js"></script>
|
||
<script type="text/javascript" src="../_static/doctools.js"></script>
|
||
<script type="text/javascript" src="../_static/language_data.js"></script>
|
||
|
||
<script type="text/javascript" src="../_static/sidebar.js"></script>
|
||
|
||
<link rel="search" type="application/opensearchdescription+xml"
|
||
title="Search within Python 3.7.4 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="shortcut icon" type="image/png" href="../_static/py.png" />
|
||
<link rel="canonical" href="https://docs.python.org/3/tutorial/stdlib2.html" />
|
||
|
||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||
<script type="text/javascript" src="../_static/switchers.js"></script>
|
||
|
||
|
||
|
||
<style>
|
||
@media only screen {
|
||
table.full-width-table {
|
||
width: 100%;
|
||
}
|
||
}
|
||
</style>
|
||
|
||
|
||
</head><body>
|
||
|
||
<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.png" alt=""
|
||
style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li>
|
||
<span class="language_switcher_placeholder">en</span>
|
||
<span class="version_switcher_placeholder">3.7.4</span>
|
||
<a href="../index.html">Documentation </a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" style="display: none" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" type="text" name="q" />
|
||
<input type="submit" value="Go" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
<script type="text/javascript">$('.inline-search').show(0);</script>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
|
||
<div class="document">
|
||
<div class="documentwrapper">
|
||
<div class="bodywrapper">
|
||
<div class="body" role="main">
|
||
|
||
<div class="section" id="brief-tour-of-the-standard-library-part-ii">
|
||
<span id="tut-brieftourtwo"></span><h1>11. 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>
|
||
<div class="section" id="output-formatting">
|
||
<span id="tut-output-formatting"></span><h2>11.1. 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</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>
|
||
</div>
|
||
<div class="section" id="templating">
|
||
<span id="tut-templating"></span><h2>11.2. 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="k">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="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="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>
|
||
</div>
|
||
<div class="section" id="working-with-binary-data-record-layouts">
|
||
<span id="tut-binary-formats"></span><h2>11.3. 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>
|
||
</div>
|
||
<div class="section" id="multi-threading">
|
||
<span id="tut-multi-threading"></span><h2>11.4. 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="nf">__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>
|
||
</div>
|
||
<div class="section" id="logging">
|
||
<span id="tut-logging"></span><h2>11.5. 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: <code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code>,
|
||
<code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code>,
|
||
and <code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code>.</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>
|
||
</div>
|
||
<div class="section" id="weak-references">
|
||
<span id="tut-weak-references"></span><h2>11.6. 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="nf">__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="nf">__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="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:/python37/lib/weakref.py"</span>, line <span class="m">46</span>, in <span class="n">__getitem__</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>
|
||
</div>
|
||
<div class="section" id="tools-for-working-with-lists">
|
||
<span id="tut-list-tools"></span><h2>11.7. 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="k">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="k">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="k">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>
|
||
</div>
|
||
<div class="section" id="decimal-floating-point-arithmetic">
|
||
<span id="tut-decimal-fp"></span><h2>11.8. 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="k">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="o">.</span><span class="mi">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="nb">sum</span><span class="p">([</span><span class="mf">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="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>
|
||
</div>
|
||
</div>
|
||
|
||
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
|
||
<div class="sphinxsidebarwrapper">
|
||
<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>
|
||
|
||
<h4>Previous topic</h4>
|
||
<p class="topless"><a href="stdlib.html"
|
||
title="previous chapter">10. Brief Tour of the Standard Library</a></p>
|
||
<h4>Next topic</h4>
|
||
<p class="topless"><a href="venv.html"
|
||
title="next chapter">12. Virtual Environments and Packages</a></p>
|
||
<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/3.7/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.png" alt=""
|
||
style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li>
|
||
<span class="language_switcher_placeholder">en</span>
|
||
<span class="version_switcher_placeholder">3.7.4</span>
|
||
<a href="../index.html">Documentation </a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" style="display: none" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" type="text" name="q" />
|
||
<input type="submit" value="Go" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
<script type="text/javascript">$('.inline-search').show(0);</script>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
<div class="footer">
|
||
© <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
|
||
<br />
|
||
The Python Software Foundation is a non-profit corporation.
|
||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||
<br />
|
||
Last updated on Jul 13, 2019.
|
||
<a href="../bugs.html">Found a bug</a>?
|
||
<br />
|
||
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
|
||
</div>
|
||
|
||
</body>
|
||
</html> |