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?2022.1" />
    
    <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.11.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="What’s New in Python 2.5" href="2.5.html" />
    <link rel="prev" title="What’s New in Python 2.7" href="2.7.html" />
    <link rel="canonical" href="https://docs.python.org/3/whatsnew/2.6.html" />
    
      
    

    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
<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> 

  </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" />
    <label for="menuToggler" class="toggler__label">
        <span></span>
    </label>
    <nav class="nav-content" role="navigation">
         <a href="https://www.python.org/" class="nav-logo">
             <img src="../_static/py.svg" alt="Logo"/>
         </a>
        <div class="version_switcher_placeholder"></div>
        <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"
                        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" fill="#444"></path>
            </svg>
            <input type="text" name="q" aria-label="Quick search"/>
            <input type="submit" value="Go"/>
        </form>
    </nav>
    <div class="menu-wrapper">
        <nav class="menu" role="navigation" aria-label="main navigation">
            <div class="language_switcher_placeholder"></div>
  <div>
    <h3><a href="../contents.html">Table of Contents</a></h3>
    <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.6</a><ul>
<li><a class="reference internal" href="#python-3-0">Python 3.0</a></li>
<li><a class="reference internal" href="#changes-to-the-development-process">Changes to the Development Process</a><ul>
<li><a class="reference internal" href="#new-issue-tracker-roundup">New Issue Tracker: Roundup</a></li>
<li><a class="reference internal" href="#new-documentation-format-restructuredtext-using-sphinx">New Documentation Format: reStructuredText Using Sphinx</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
<li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
<li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: Explicit Relative Imports From a Main Module</a></li>
<li><a class="reference internal" href="#pep-370-per-user-site-packages-directory">PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</a></li>
<li><a class="reference internal" href="#pep-371-the-multiprocessing-package">PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package</a></li>
<li><a class="reference internal" href="#pep-3101-advanced-string-formatting">PEP 3101: Advanced String Formatting</a></li>
<li><a class="reference internal" href="#pep-3105-print-as-a-function">PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function</a></li>
<li><a class="reference internal" href="#pep-3110-exception-handling-changes">PEP 3110: Exception-Handling Changes</a></li>
<li><a class="reference internal" href="#pep-3112-byte-literals">PEP 3112: Byte Literals</a></li>
<li><a class="reference internal" href="#pep-3116-new-i-o-library">PEP 3116: New I/O Library</a></li>
<li><a class="reference internal" href="#pep-3118-revised-buffer-protocol">PEP 3118: Revised Buffer Protocol</a></li>
<li><a class="reference internal" href="#pep-3119-abstract-base-classes">PEP 3119: Abstract Base Classes</a></li>
<li><a class="reference internal" href="#pep-3127-integer-literal-support-and-syntax">PEP 3127: Integer Literal Support and Syntax</a></li>
<li><a class="reference internal" href="#pep-3129-class-decorators">PEP 3129: Class Decorators</a></li>
<li><a class="reference internal" href="#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: A Type Hierarchy for Numbers</a><ul>
<li><a class="reference internal" href="#the-fractions-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code> Module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
<li><a class="reference internal" href="#interpreter-changes">Interpreter Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-and-improved-modules">New and Improved Modules</a><ul>
<li><a class="reference internal" href="#the-ast-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code> module</a></li>
<li><a class="reference internal" href="#the-future-builtins-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module</a></li>
<li><a class="reference internal" href="#the-json-module-javascript-object-notation">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code> module: JavaScript Object Notation</a></li>
<li><a class="reference internal" href="#the-plistlib-module-a-property-list-parser">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code> module: A Property-List Parser</a></li>
<li><a class="reference internal" href="#ctypes-enhancements">ctypes Enhancements</a></li>
<li><a class="reference internal" href="#improved-ssl-support">Improved SSL Support</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deprecations-and-removals">Deprecations and Removals</a></li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#port-specific-changes-windows">Port-Specific Changes: Windows</a></li>
<li><a class="reference internal" href="#port-specific-changes-mac-os-x">Port-Specific Changes: Mac OS X</a></li>
<li><a class="reference internal" href="#port-specific-changes-irix">Port-Specific Changes: IRIX</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-6">Porting to Python 2.6</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  </div>
  <div>
    <h4>Previous topic</h4>
    <p class="topless"><a href="2.7.html"
                          title="previous chapter">What’s New in Python 2.7</a></p>
  </div>
  <div>
    <h4>Next topic</h4>
    <p class="topless"><a href="2.5.html"
                          title="next chapter">What’s New in Python 2.5</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/whatsnew/2.6.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="2.5.html" title="What’s New in Python 2.5"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.7.html" title="What’s New in Python 2.7"
             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> &#187;</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.11.0 Documentation</a> &#187;
    </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li>
        <li class="nav-item nav-item-this"><a href="">What’s New in Python 2.6</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="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>
                     |
                </li>
            
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <section id="what-s-new-in-python-2-6">
<span id="whats-new-in-2-6"></span><h1>What’s New in Python 2.6<a class="headerlink" href="#what-s-new-in-python-2-6" title="Permalink to this headline">¶</a></h1>
<dl class="field-list simple">
<dt class="field-odd">Author</dt>
<dd class="field-odd"><p>A.M. Kuchling (amk at amk.ca)</p>
</dd>
</dl>
<p>This article explains the new features in Python 2.6, released on October 1,
2008.  The release schedule is described in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0361/"><strong>PEP 361</strong></a>.</p>
<p>The major theme of Python 2.6 is preparing the migration path to
Python 3.0, a major redesign of the language.  Whenever possible,
Python 2.6 incorporates new features and syntax from 3.0 while
remaining compatible with existing code by not removing older features
or syntax.  When it’s not possible to do that, Python 2.6 tries to do
what it can, adding compatibility functions in a
<code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module and a <code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code> switch to warn about
usages that will become unsupported in 3.0.</p>
<p>Some significant new packages have been added to the standard library,
such as the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> and <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> modules, but
there aren’t many new features that aren’t related to Python 3.0 in
some way.</p>
<p>Python 2.6 also sees a number of improvements and bugfixes throughout
the source.  A search through the change logs finds there were 259
patches applied and 612 bugs fixed between Python 2.5 and 2.6.  Both
figures are likely to be underestimates.</p>
<p>This article doesn’t attempt to provide a complete specification of
the new features, but instead provides a convenient overview.  For
full details, you should refer to the documentation for Python 2.6. If
you want to understand the rationale for the design and
implementation, refer to the PEP for a particular new feature.
Whenever possible, “What’s New in Python” links to the bug/patch item
for each change.</p>
<section id="python-3-0">
<h2>Python 3.0<a class="headerlink" href="#python-3-0" title="Permalink to this headline">¶</a></h2>
<p>The development cycle for Python versions 2.6 and 3.0 was
synchronized, with the alpha and beta releases for both versions being
made on the same days.  The development of 3.0 has influenced many
features in 2.6.</p>
<p>Python 3.0 is a far-ranging redesign of Python that breaks
compatibility with the 2.x series.  This means that existing Python
code will need some conversion in order to run on
Python 3.0.  However, not all the changes in 3.0 necessarily break
compatibility.  In cases where new features won’t cause existing code
to break, they’ve been backported to 2.6 and are described in this
document in the appropriate place.  Some of the 3.0-derived features
are:</p>
<ul class="simple">
<li><p>A <code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code> method for converting objects to a complex number.</p></li>
<li><p>Alternate syntax for catching exceptions: <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">TypeError</span> <span class="pre">as</span> <span class="pre">exc</span></code>.</p></li>
<li><p>The addition of <a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a> as a synonym for the built-in
<code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code> function.</p></li>
</ul>
<p>Python 3.0 adds several new built-in functions and changes the
semantics of some existing builtins.  Functions that are new in 3.0
such as <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a> have simply been added to Python 2.6, but existing
builtins haven’t been changed; instead, the <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code>
module has versions with the new 3.0 semantics.  Code written to be
compatible with 3.0 can do <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">future_builtins</span> <span class="pre">import</span> <span class="pre">hex,</span> <span class="pre">map</span></code> as
necessary.</p>
<p>A new command-line switch, <code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code>, enables warnings
about features that will be removed in Python 3.0.  You can run code
with this switch to see how much work will be necessary to port
code to 3.0.  The value of this switch is available
to Python code as the boolean variable <code class="xref py py-data docutils literal notranslate"><span class="pre">sys.py3kwarning</span></code>,
and to C extension code as <code class="xref c c-data docutils literal notranslate"><span class="pre">Py_Py3kWarningFlag</span></code>.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p>The 3xxx series of PEPs, which contains proposals for Python 3.0.
<span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-3000/"><strong>PEP 3000</strong></a> describes the development process for Python 3.0.
Start with <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-3100/"><strong>PEP 3100</strong></a> that describes the general goals for Python
3.0, and then explore the higher-numbered PEPS that propose
specific features.</p>
</div>
</section>
<section id="changes-to-the-development-process">
<h2>Changes to the Development Process<a class="headerlink" href="#changes-to-the-development-process" title="Permalink to this headline">¶</a></h2>
<p>While 2.6 was being developed, the Python development process
underwent two significant changes: we switched from SourceForge’s
issue tracker to a customized Roundup installation, and the
documentation was converted from LaTeX to reStructuredText.</p>
<section id="new-issue-tracker-roundup">
<h3>New Issue Tracker: Roundup<a class="headerlink" href="#new-issue-tracker-roundup" title="Permalink to this headline">¶</a></h3>
<p>For a long time, the Python developers had been growing increasingly
annoyed by SourceForge’s bug tracker.  SourceForge’s hosted solution
doesn’t permit much customization; for example, it wasn’t possible to
customize the life cycle of issues.</p>
<p>The infrastructure committee of the Python Software Foundation
therefore posted a call for issue trackers, asking volunteers to set
up different products and import some of the bugs and patches from
SourceForge.  Four different trackers were examined: <a class="reference external" href="https://www.atlassian.com/software/jira/">Jira</a>,
<a class="reference external" href="https://launchpad.net/">Launchpad</a>,
<a class="reference external" href="https://roundup.sourceforge.io/">Roundup</a>, and
<a class="reference external" href="https://trac.edgewall.org/">Trac</a>.
The committee eventually settled on Jira
and Roundup as the two candidates.  Jira is a commercial product that
offers no-cost hosted instances to free-software projects; Roundup
is an open-source project that requires volunteers
to administer it and a server to host it.</p>
<p>After posting a call for volunteers, a new Roundup installation was
set up at <a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a>.  One installation of Roundup can
host multiple trackers, and this server now also hosts issue trackers
for Jython and for the Python web site.  It will surely find
other uses in the future.  Where possible,
this edition of “What’s New in Python” links to the bug/patch
item for each change.</p>
<p>Hosting of the Python bug tracker is kindly provided by
<a class="reference external" href="http://www.upfrontsoftware.co.za">Upfront Systems</a>
of Stellenbosch, South Africa.  Martin von Löwis put a
lot of effort into importing existing bugs and patches from
SourceForge; his scripts for this import operation are at
<code class="docutils literal notranslate"><span class="pre">https://svn.python.org/view/tracker/importer/</span></code> and may be useful to
other projects wishing to move from SourceForge to Roundup.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a></dt><dd><p>The Python bug tracker.</p>
</dd>
<dt><a class="reference external" href="https://bugs.jython.org">https://bugs.jython.org</a>:</dt><dd><p>The Jython bug tracker.</p>
</dd>
<dt><a class="reference external" href="https://roundup.sourceforge.io/">https://roundup.sourceforge.io/</a></dt><dd><p>Roundup downloads and documentation.</p>
</dd>
<dt><a class="reference external" href="https://svn.python.org/view/tracker/importer/">https://svn.python.org/view/tracker/importer/</a></dt><dd><p>Martin von Löwis’s conversion scripts.</p>
</dd>
</dl>
</div>
</section>
<section id="new-documentation-format-restructuredtext-using-sphinx">
<h3>New Documentation Format: reStructuredText Using Sphinx<a class="headerlink" href="#new-documentation-format-restructuredtext-using-sphinx" title="Permalink to this headline">¶</a></h3>
<p>The Python documentation was written using LaTeX since the project
started around 1989.  In the 1980s and early 1990s, most documentation
was printed out for later study, not viewed online. LaTeX was widely
used because it provided attractive printed output while remaining
straightforward to write once the basic rules of the markup were
learned.</p>
<p>Today LaTeX is still used for writing publications destined for
printing, but the landscape for programming tools has shifted.  We no
longer print out reams of documentation; instead, we browse through it
online and HTML has become the most important format to support.
Unfortunately, converting LaTeX to HTML is fairly complicated and Fred
L. Drake Jr., the long-time Python documentation editor, spent a lot
of time maintaining the conversion process.  Occasionally people would
suggest converting the documentation into SGML and later XML, but
performing a good conversion is a major task and no one ever committed
the time required to finish the job.</p>
<p>During the 2.6 development cycle, Georg Brandl put a lot of effort
into building a new toolchain for processing the documentation.  The
resulting package is called Sphinx, and is available from
<a class="reference external" href="http://sphinx-doc.org/">http://sphinx-doc.org/</a>.</p>
<p>Sphinx concentrates on HTML output, producing attractively styled and
modern HTML; printed output is still supported through conversion to
LaTeX.  The input format is reStructuredText, a markup syntax
supporting custom extensions and directives that is commonly used in
the Python community.</p>
<p>Sphinx is a standalone package that can be used for writing, and
almost two dozen other projects
(<a class="reference external" href="https://www.sphinx-doc.org/en/master/examples.html">listed on the Sphinx web site</a>)
have adopted Sphinx as their documentation tool.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><a class="reference external" href="https://devguide.python.org/documenting/">Documenting Python</a></dt><dd><p>Describes how to write for Python’s documentation.</p>
</dd>
<dt><a class="reference external" href="http://sphinx-doc.org/">Sphinx</a></dt><dd><p>Documentation and code for the Sphinx toolchain.</p>
</dd>
<dt><a class="reference external" href="https://docutils.sourceforge.io">Docutils</a></dt><dd><p>The underlying reStructuredText parser and toolset.</p>
</dd>
</dl>
</div>
</section>
</section>
<section id="pep-343-the-with-statement">
<span id="pep-0343"></span><h2>PEP 343: The ‘with’ statement<a class="headerlink" href="#pep-343-the-with-statement" title="Permalink to this headline">¶</a></h2>
<p>The previous version, Python 2.5, added the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’
statement as an optional feature, to be enabled by a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span>
<span class="pre">import</span> <span class="pre">with_statement</span></code> directive.  In 2.6 the statement no longer needs to
be specially enabled; this means that <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> is now always a
keyword.  The rest of this section is a copy of the corresponding
section from the “What’s New in Python 2.5” document; if you’re
familiar with the ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’ statement
from Python 2.5, you can skip this section.</p>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement clarifies code that previously would use
<code class="docutils literal notranslate"><span class="pre">try...finally</span></code> blocks to ensure that clean-up code is executed.  In this
section, I’ll discuss the statement as it will commonly be used.  In the next
section, I’ll examine the implementation details and show how to write objects
for use with this statement.</p>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is a control-flow structure whose basic
structure is:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">expression</span> <span class="p">[</span><span class="k">as</span> <span class="n">variable</span><span class="p">]:</span>
    <span class="k">with</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
methods).</p>
<p>The object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> is called before <em>with-block</em> is executed and
therefore can run set-up code. It also may return a value that is bound to the
name <em>variable</em>, if given.  (Note carefully that <em>variable</em> is <em>not</em> assigned
the result of <em>expression</em>.)</p>
<p>After execution of the <em>with-block</em> is finished, the object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
method is called, even if the block raised an exception, and can therefore run
clean-up code.</p>
<p>Some standard Python objects now support the context management protocol and can
be used with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement. File objects are one example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/etc/passwd&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span>
        <span class="o">...</span> <span class="n">more</span> <span class="n">processing</span> <span class="n">code</span> <span class="o">...</span>
</pre></div>
</div>
<p>After this statement has executed, the file object in <em>f</em> will have been
automatically closed, even if the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop raised an exception
part-way through the block.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>In this case, <em>f</em> is the same object created by <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, because
<code class="xref py py-meth docutils literal notranslate"><span class="pre">file.__enter__()</span></code> returns <em>self</em>.</p>
</div>
<p>The <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’s locks and condition variables  also support the
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">lock</span><span class="p">:</span>
    <span class="c1"># Critical section of code</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The lock is acquired before the block is executed and always released once  the
block is complete.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">localcontext()</span></code> function in 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 makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">decimal</span> <span class="kn">import</span> <span class="n">Decimal</span><span class="p">,</span> <span class="n">Context</span><span class="p">,</span> <span class="n">localcontext</span>

<span class="c1"># Displays with default precision of 28 digits</span>
<span class="n">v</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;578&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>

<span class="k">with</span> <span class="n">localcontext</span><span class="p">(</span><span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">16</span><span class="p">)):</span>
    <span class="c1"># All code in this block uses a precision of 16 digits.</span>
    <span class="c1"># The original context is restored on exiting the block.</span>
    <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
</pre></div>
</div>
<section id="writing-context-managers">
<span id="new-26-context-managers"></span><h3>Writing Context Managers<a class="headerlink" href="#writing-context-managers" title="Permalink to this headline">¶</a></h3>
<p>Under the hood, the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is fairly complicated. Most
people will only use ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’ in company with existing objects and
don’t need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.</p>
<p>A high-level explanation of the context management protocol is:</p>
<ul class="simple">
<li><p>The expression is evaluated and should result in an object called a “context
manager”.  The context manager must have <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
methods.</p></li>
<li><p>The context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method is called.  The value returned
is assigned to <em>VAR</em>.  If no <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">VAR</span></code> clause is present, the value is simply
discarded.</p></li>
<li><p>The code in <em>BLOCK</em> is executed.</p></li>
<li><p>If <em>BLOCK</em> raises an exception, the context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method
is called with three arguments, the exception details (<code class="docutils literal notranslate"><span class="pre">type,</span> <span class="pre">value,</span> <span class="pre">traceback</span></code>,
the same values returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>, which can also be <code class="docutils literal notranslate"><span class="pre">None</span></code>
if no exception occurred).  The method’s return value controls whether an exception
is re-raised: any false value re-raises the exception, and <code class="docutils literal notranslate"><span class="pre">True</span></code> will result
in suppressing it.  You’ll only rarely want to suppress the exception, because
if you do the author of the code containing the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement will
never realize anything went wrong.</p></li>
<li><p>If <em>BLOCK</em> didn’t raise an exception,  the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method is still
called, but <em>type</em>, <em>value</em>, and <em>traceback</em> are all <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
</ul>
<p>Let’s think through an example.  I won’t present detailed code but will only
sketch the methods necessary for a database that supports transactions.</p>
<p>(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)</p>
<p>Let’s assume there’s an object representing a database connection. Our goal will
be to let the user write code like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">db_connection</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_connection</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;insert into ...&#39;</span><span class="p">)</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;delete from ...&#39;</span><span class="p">)</span>
    <span class="c1"># ... more operations ...</span>
</pre></div>
</div>
<p>The transaction should be committed if the code in the block runs flawlessly or
rolled back if there’s an exception. Here’s the basic interface for
<code class="xref py py-class docutils literal notranslate"><span class="pre">DatabaseConnection</span></code> that I’ll assume:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="c1"># Database interface</span>
    <span class="k">def</span> <span class="nf">cursor</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Returns a cursor object and starts a new transaction&quot;</span>
    <span class="k">def</span> <span class="nf">commit</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Commits current transaction&quot;</span>
    <span class="k">def</span> <span class="nf">rollback</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Rolls back current transaction&quot;</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">cursor</span></code> to
their ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement to bind the cursor to a variable name.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Code to start a new transaction</span>
        <span class="n">cursor</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">cursor</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method is the most complicated because it’s where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.</p>
<p>In the code below, execution will just fall off the end of the function,
returning the default value of <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement at the marked location.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">type</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">tb</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="c1"># No exception, so commit</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c1"># Exception occurred, so rollback.</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
            <span class="c1"># return False</span>
</pre></div>
</div>
</section>
<section id="the-contextlib-module">
<span id="new-module-contextlib"></span><h3>The contextlib module<a class="headerlink" href="#the-contextlib-module" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module provides some functions and a decorator that
are useful when writing objects for use with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement.</p>
<p>The decorator is called <code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code>, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will be executed as the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method, and the value yielded will be the method’s return
value that will get bound to the variable in the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement’s
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause, if any.  The code after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> will be
executed in the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method.  Any exception raised in the block will
be raised by the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement.</p>
<p>Using this decorator, our database example from the previous section
could be written as:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span>

<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">db_transaction</span><span class="p">(</span><span class="n">connection</span><span class="p">):</span>
    <span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">cursor</span>
    <span class="k">except</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
        <span class="k">raise</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">db</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">)</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module also has a <code class="docutils literal notranslate"><span class="pre">nested(mgr1,</span> <span class="pre">mgr2,</span> <span class="pre">...)</span></code> function
that combines a number of context managers so you don’t need to write nested
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statements.  In this example, the single ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’
statement both starts a database transaction and acquires a thread lock:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">nested</span> <span class="p">(</span><span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">),</span> <span class="n">lock</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span><span class="n">cursor</span><span class="p">,</span> <span class="n">locked</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Finally, the <code class="xref py py-func docutils literal notranslate"><span class="pre">closing()</span></code> function returns its argument so that it can be
bound to a variable, and calls the argument’s <code class="docutils literal notranslate"><span class="pre">.close()</span></code> method at the end
of the block.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span><span class="o">,</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">closing</span>

<span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.yahoo.com&#39;</span><span class="p">))</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement, which can be helpful in learning how the statement
works.</p>
</dd>
</dl>
<p>The documentation  for the <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module.</p>
</div>
</section>
</section>
<section id="pep-366-explicit-relative-imports-from-a-main-module">
<span id="pep-0366"></span><h2>PEP 366: Explicit Relative Imports From a Main Module<a class="headerlink" href="#pep-366-explicit-relative-imports-from-a-main-module" title="Permalink to this headline">¶</a></h2>
<p>Python’s <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch allows running a module as a script.
When you ran a module that was located inside a package, relative
imports didn’t work correctly.</p>
<p>The fix for Python 2.6 adds a <a class="reference internal" href="../reference/import.html#package__" title="__package__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code></a> attribute to
modules.  When this attribute is present, relative imports will be
relative to the value of this attribute instead of the
<a class="reference internal" href="../reference/import.html#name__" title="__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute.</p>
<p>PEP 302-style importers can then set <a class="reference internal" href="../reference/import.html#package__" title="__package__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code></a> as necessary.
The <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module that implements the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch now
does this, so relative imports will now work correctly in scripts
running from inside a package.</p>
</section>
<section id="pep-370-per-user-site-packages-directory">
<span id="pep-0370"></span><h2>PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory<a class="headerlink" href="#pep-370-per-user-site-packages-directory" title="Permalink to this headline">¶</a></h2>
<p>When you run Python, the module search path <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> usually
includes a directory whose path ends in <code class="docutils literal notranslate"><span class="pre">&quot;site-packages&quot;</span></code>.  This
directory is intended to hold locally installed packages available to
all users using a machine or a particular site installation.</p>
<p>Python 2.6 introduces a convention for user-specific site directories.
The directory varies depending on the platform:</p>
<ul class="simple">
<li><p>Unix and Mac OS X: <code class="file docutils literal notranslate"><span class="pre">~/.local/</span></code></p></li>
<li><p>Windows: <code class="file docutils literal notranslate"><span class="pre">%APPDATA%/Python</span></code></p></li>
</ul>
<p>Within this directory, there will be version-specific subdirectories,
such as <code class="file docutils literal notranslate"><span class="pre">lib/python2.6/site-packages</span></code> on Unix/Mac OS and
<code class="file docutils literal notranslate"><span class="pre">Python26/site-packages</span></code> on Windows.</p>
<p>If you don’t like the default directory, it can be overridden by an
environment variable.  <span class="target" id="index-4"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONUSERBASE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONUSERBASE</span></code></a> sets the root
directory used for all Python versions supporting this feature.  On
Windows, the directory for application-specific data can be changed by
setting the <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">APPDATA</span></code> environment variable.  You can also
modify the <code class="file docutils literal notranslate"><span class="pre">site.py</span></code> file for your Python installation.</p>
<p>The feature can be disabled entirely by running Python with the
<a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> option or setting the <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONNOUSERSITE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONNOUSERSITE</span></code></a>
environment variable.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0370/"><strong>PEP 370</strong></a> - Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</dt><dd><p>PEP written and implemented by Christian Heimes.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-371-the-multiprocessing-package">
<span id="pep-0371"></span><h2>PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package<a class="headerlink" href="#pep-371-the-multiprocessing-package" title="Permalink to this headline">¶</a></h2>
<p>The new <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> package lets Python programs create new
processes that will perform a computation and return a result to the
parent.  The parent and child processes can communicate using queues
and pipes, synchronize their operations using locks and semaphores,
and can share simple arrays of data.</p>
<p>The <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module started out as an exact emulation of
the <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 using processes instead of threads.  That
goal was discarded along the path to Python 2.6, but the general
approach of the module is still similar.  The fundamental class
is the <code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code>, which is passed a callable object and
a collection of arguments.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code> method
sets the callable running in a subprocess, after which you can call
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">is_alive()</span></code> method to check whether the subprocess is still running
and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> method to wait for the process to exit.</p>
<p>Here’s a simple example where the subprocess will calculate a
factorial.  The function doing the calculation is written strangely so
that it takes significantly longer when the input argument is a
multiple of 4.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Queue</span>


<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">queue</span><span class="p">,</span> <span class="n">N</span><span class="p">):</span>
    <span class="s2">&quot;Compute a factorial.&quot;</span>
    <span class="c1"># If N is a multiple of 4, this function will take much longer.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">N</span> <span class="o">%</span> <span class="mi">4</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">.05</span> <span class="o">*</span> <span class="n">N</span><span class="o">/</span><span class="mi">4</span><span class="p">)</span>

    <span class="c1"># Calculate the result</span>
    <span class="n">fact</span> <span class="o">=</span> <span class="mi">1</span><span class="n">L</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">1</span><span class="p">,</span> <span class="n">N</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
        <span class="n">fact</span> <span class="o">=</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">i</span>

    <span class="c1"># Put the result on the queue</span>
    <span class="n">queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">fact</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>

    <span class="n">N</span> <span class="o">=</span> <span class="mi">5</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">factorial</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">queue</span><span class="p">,</span> <span class="n">N</span><span class="p">))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
    <span class="nb">print</span> <span class="s1">&#39;Factorial&#39;</span><span class="p">,</span> <span class="n">N</span><span class="p">,</span> <span class="s1">&#39;=&#39;</span><span class="p">,</span> <span class="n">result</span>
</pre></div>
</div>
<p>A <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> is used to communicate the result of the factorial.
The <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> object is stored in a global variable.
The child process will use the value of the variable when the child
was created; because it’s a <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>, parent and child can use
the object to communicate.  (If the parent were to change the value of
the global variable, the child’s value would be unaffected, and vice
versa.)</p>
<p>Two other classes, <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code>, provide
higher-level interfaces.  <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> will create a fixed number of
worker processes, and requests can then be distributed to the workers
by calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">apply()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">apply_async()</span></code> to add a single request,
and <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-meth docutils literal notranslate"><span class="pre">map()</span></code></a> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">map_async()</span></code> to add a number of
requests.  The following code uses a <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> to spread requests
across 5 worker processes and retrieve a list of results:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Pool</span>

<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">dictionary</span><span class="p">):</span>
    <span class="s2">&quot;Compute a factorial.&quot;</span>
    <span class="o">...</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">factorial</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span>
<span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">result</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">v</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span>
<span class="mi">39916800</span>
<span class="mi">51090942171709440000</span>
<span class="mi">8222838654177922817725562880000000</span>
<span class="mi">33452526613163807108170062053440751665152000000000</span>
<span class="o">...</span>
</pre></div>
</div>
<p>The other high-level interface, the <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code> class, creates a
separate server process that can hold master copies of Python data
structures.  Other processes can then access and modify these data
structures using proxy objects.  The following example creates a
shared dictionary by calling the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict()</span></code></a> method; the worker
processes then insert values into the dictionary.  (Locking is not
done for you automatically, which doesn’t matter in this example.
<code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code>’s methods also include <code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">RLock()</span></code>,
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">Semaphore()</span></code> to create shared locks.)</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Pool</span><span class="p">,</span> <span class="n">Manager</span>

<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">dictionary</span><span class="p">):</span>
    <span class="s2">&quot;Compute a factorial.&quot;</span>
    <span class="c1"># Calculate the result</span>
    <span class="n">fact</span> <span class="o">=</span> <span class="mi">1</span><span class="n">L</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">1</span><span class="p">,</span> <span class="n">N</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
        <span class="n">fact</span> <span class="o">=</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">i</span>

    <span class="c1"># Store result in dictionary</span>
    <span class="n">dictionary</span><span class="p">[</span><span class="n">N</span><span class="p">]</span> <span class="o">=</span> <span class="n">fact</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
    <span class="n">mgr</span> <span class="o">=</span> <span class="n">Manager</span><span class="p">()</span>
    <span class="n">d</span> <span class="o">=</span> <span class="n">mgr</span><span class="o">.</span><span class="n">dict</span><span class="p">()</span>         <span class="c1"># Create shared dictionary</span>

    <span class="c1"># Run tasks using the pool</span>
    <span class="k">for</span> <span class="n">N</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span>
        <span class="n">p</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">factorial</span><span class="p">,</span> <span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">d</span><span class="p">))</span>

    <span class="c1"># Mark pool as closed -- no more tasks can be added.</span>
    <span class="n">p</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

    <span class="c1"># Wait for tasks to exit</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="c1"># Output results</span>
    <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()):</span>
        <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span>
</pre></div>
</div>
<p>This will produce the output:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="mi">1</span>
<span class="mi">11</span> <span class="mi">39916800</span>
<span class="mi">21</span> <span class="mi">51090942171709440000</span>
<span class="mi">31</span> <span class="mi">8222838654177922817725562880000000</span>
<span class="mi">41</span> <span class="mi">33452526613163807108170062053440751665152000000000</span>
<span class="mi">51</span> <span class="mf">15511187532873822802242430164693032110632597200169861120000.</span><span class="o">..</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p>The documentation for the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module.</p>
<dl class="simple">
<dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0371/"><strong>PEP 371</strong></a> - Addition of the multiprocessing package</dt><dd><p>PEP written by Jesse Noller and Richard Oudkerk;
implemented by Richard Oudkerk and Jesse Noller.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3101-advanced-string-formatting">
<span id="pep-3101"></span><h2>PEP 3101: Advanced String Formatting<a class="headerlink" href="#pep-3101-advanced-string-formatting" title="Permalink to this headline">¶</a></h2>
<p>In Python 3.0, the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is supplemented by a more powerful string
formatting method, <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a>.  Support for the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method
has been backported to Python 2.6.</p>
<p>In 2.6, both 8-bit and Unicode strings have a <code class="docutils literal notranslate"><span class="pre">.format()</span></code> method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (<code class="docutils literal notranslate"><span class="pre">{</span></code>, <code class="docutils literal notranslate"><span class="pre">}</span></code>) as special characters:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Substitute positional argument 0 into the string.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;User ID: </span><span class="si">{0}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;root&quot;</span><span class="p">)</span>
<span class="go">&#39;User ID: root&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Use the named keyword arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;User ID: </span><span class="si">{uid}</span><span class="s2">   Last seen: </span><span class="si">{last_login}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
<span class="gp">... </span>   <span class="n">uid</span><span class="o">=</span><span class="s2">&quot;root&quot;</span><span class="p">,</span>
<span class="gp">... </span>   <span class="n">last_login</span> <span class="o">=</span> <span class="s2">&quot;5 Mar 2008 07:20&quot;</span><span class="p">)</span>
<span class=