Files
hustoj/web/python-docs/whatsnew/2.6.html
2025-03-09 17:10:56 +08:00

3099 lines
348 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
<head>
<meta charset="utf-8" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
<title>Python 2.6 有什么新变化 &#8212; Python 3.8.20 文档</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script id="documentation_options" data-url_root="../" 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/language_data.js"></script>
<script src="../_static/translations.js"></script>
<script src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.8.20 文档 中搜索"
href="../_static/opensearch.xml"/>
<link rel="author" title="关于这些文档" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜索" href="../search.html" />
<link rel="copyright" title="版权所有" href="../copyright.html" />
<link rel="next" title="Python 2.5 有什么新变化" href="2.5.html" />
<link rel="prev" title="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="快速搜索"/>
<input type="submit" value="转向"/>
</form>
</nav>
<div class="menu-wrapper">
<nav class="menu" role="navigation" aria-label="main navigation">
<div class="language_switcher_placeholder"></div>
<h3><a href="../contents.html">目录</a></h3>
<ul>
<li><a class="reference internal" href="#">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">开发过程的变化</a><ul>
<li><a class="reference internal" href="#new-issue-tracker-roundup">新问题追踪:简述</a></li>
<li><a class="reference internal" href="#new-documentation-format-restructuredtext-using-sphinx">新的文档格式:使用 Sphinx 的 reStructuredText</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: &quot;with&quot; 语句</a><ul>
<li><a class="reference internal" href="#writing-context-managers">编写上下文管理器</a></li>
<li><a class="reference internal" href="#the-contextlib-module">contextlib 模块</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: 从主模块显式相对导入</a></li>
<li><a class="reference internal" href="#pep-370-per-user-site-packages-directory">PEP 370: 分用户的 site-packages 目录</a></li>
<li><a class="reference internal" href="#pep-371-the-multiprocessing-package">PEP 371: 多任务处理包</a></li>
<li><a class="reference internal" href="#pep-3101-advanced-string-formatting">PEP 3101: 高级字符串格式</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> 改为函数</a></li>
<li><a class="reference internal" href="#pep-3110-exception-handling-changes">PEP 3110: 异常处理的变更</a></li>
<li><a class="reference internal" href="#pep-3112-byte-literals">PEP 3112: 字节字面值</a></li>
<li><a class="reference internal" href="#pep-3116-new-i-o-library">PEP 3116: 新 I/O 库</a></li>
<li><a class="reference internal" href="#pep-3118-revised-buffer-protocol">PEP 3118: 修改缓冲区协议</a></li>
<li><a class="reference internal" href="#pep-3119-abstract-base-classes">PEP 3119: 抽象基类</a></li>
<li><a class="reference internal" href="#pep-3127-integer-literal-support-and-syntax">PEP 3127: 整型文字支持和语法</a></li>
<li><a class="reference internal" href="#pep-3129-class-decorators">PEP 3129: 类装饰器</a></li>
<li><a class="reference internal" href="#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: 数字的类型层级结构</a><ul>
<li><a class="reference internal" href="#the-fractions-module"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code> 模块</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-language-changes">其他语言特性修改</a><ul>
<li><a class="reference internal" href="#optimizations">性能优化</a></li>
<li><a class="reference internal" href="#interpreter-changes">解释器改动</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-and-improved-modules">新增和改进的模块</a><ul>
<li><a class="reference internal" href="#the-ast-module"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code> 模块</a></li>
<li><a class="reference internal" href="#the-future-builtins-module"><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> 模块</a></li>
<li><a class="reference internal" href="#the-json-module-javascript-object-notation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code> 模块: JavaScript Object Notation</a></li>
<li><a class="reference internal" href="#the-plistlib-module-a-property-list-parser"><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code> 模块:属性列表解析器</a></li>
<li><a class="reference internal" href="#ctypes-enhancements">ctypes Enhancements</a></li>
<li><a class="reference internal" href="#improved-ssl-support">改进的 SSL 支持</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deprecations-and-removals">弃用和移除</a></li>
<li><a class="reference internal" href="#build-and-c-api-changes">构建和 C API 的改变</a><ul>
<li><a class="reference internal" href="#port-specific-changes-windows">特定于 Windows 的更改:</a></li>
<li><a class="reference internal" href="#port-specific-changes-mac-os-x">特定于 Mac OS X 的更改:</a></li>
<li><a class="reference internal" href="#port-specific-changes-irix">特定于 IRIX 的更改:</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-6">移植到Python 2.6</a></li>
<li><a class="reference internal" href="#acknowledgements">致谢</a></li>
</ul>
</li>
</ul>
<h4>上一个主题</h4>
<p class="topless"><a href="2.7.html"
title="上一章">Python 2.7 有什么新变化</a></p>
<h4>下一个主题</h4>
<p class="topless"><a href="2.5.html"
title="下一章">Python 2.5 有什么新变化</a></p>
<div role="note" aria-label="source link">
<h3>本页</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">报告 Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.8/Doc/whatsnew/2.6.rst"
rel="nofollow">显示源代码
</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div id="outdated-warning" style="padding: .5em; text-align: center; background-color: #FFBABA; color: #6A0E0E;">
这个文档所针对的是一个已不再受支持的 Python 旧版本。
你应当升级版本,并阅读
<a href="/3/whatsnew/2.6.html"> Python 当前稳定版本的文档</a>.
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>导航</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="总目录"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模块索引"
>模块</a> |</li>
<li class="right" >
<a href="2.5.html" title="Python 2.5 有什么新变化"
accesskey="N">下一页</a> |</li>
<li class="right" >
<a href="2.7.html" title="Python 2.7 有什么新变化"
accesskey="P">上一页</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.8.20 Documentation</a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python的新变化</a> &#187;</li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜索" aria-label="快速搜索" type="text" name="q" />
<input type="submit" value="转向" />
<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>Python 2.6 有什么新变化<a class="headerlink" href="#what-s-new-in-python-2-6" title="永久链接至标题"></a></h1>
<dl class="field-list simple">
<dt class="field-odd">作者</dt>
<dd class="field-odd"><p>A.M. Kuchling (amk at amk.ca)</p>
</dd>
</dl>
<p>本文介绍了 Python 2.6 的新特性,它发布于 2008 年 10 月 1 日。 发布日程说明见 <span class="target" id="index-39"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0361"><strong>PEP 361</strong></a></p>
<p>Python 2.6 的主题是为迁移到 Python 3.0 做准备,这是 Python 语言的一次重大重新设计。 只要有可能Python 2.6 就会纳入 3.0 的新特性和语法,同时通过不删除旧特性或语法来保持与现有代码的兼容。 当无法做到这一点时Python 2.6 会尽力而为,在 <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> 模块中添加兼容性函数,并通过 <code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code> 开关来警告将在 3.0 中变得不支持的用法。</p>
<p>标准库中增加了一些重要的新包,如 <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><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> 模块等,但与 Python 3.0 完全无关联的新特性并不多。</p>
<p>Python 2.6 还对整个源代码进行了大量改进和错误修复。 通过搜索更改日志我们发现在 Python 2.5 和 2.6 之间应用了 259 个补丁并修复了 612 个错误。 这两个数字可能都被低估了。</p>
<p>本文并不试图提供新特性的完整规范说明,而是提供一个方便的概览。 要了解完整的细节,请参阅 Python 2.6 的文档。 如果你想了解有关设计和实现的具体考量,请参阅特定新特性 的 PEP。 在可能的情况下“Python 有什么新变化”为每个更改的错误修正/补丁项提供链接。</p>
<section id="python-3-0">
<h2>Python 3.0<a class="headerlink" href="#python-3-0" title="永久链接至标题"></a></h2>
<p>Python版本2.6和3.0的开发周期是同步的两个版本的alpha和beta版本是在同一天发布的。3.0的发展影响了2.6中的许多功能。</p>
<p>Python 3.0 是对 Python 的大范围重新设计,打破了与 2.x 系列的兼容性。 这意味着现有的 Python 代码需要进行一些转换才能在 Python 3.0 上运行。 不过,并非 3.0 中的所有更改都会破坏兼容性。 在新特性不会导致现有代码崩溃的情况下,它们会被回溯到 2.6,并在本文档的适当位置进行描述。 部分 3.0 衍生功能包括:</p>
<ul class="simple">
<li><p>用于将对象转换为复数的 <a class="reference internal" href="../reference/datamodel.html#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a> 方法。</p></li>
<li><p>用于捕获异常的替代语法: <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>增加 <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> 作为内置 <code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code> 函数的同义词。</p></li>
</ul>
<p>Python 3.0 新增了一些内置函数并对部分现有内置函数的语法进行了修改。 在 3.0 中新增的函数如 <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> 已直接添加到 Python 2.6 中,但现有内置函数则未修改;替代做法是在 <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> 模块中包含具有 3.0 新语法的版本。 要与 3.0 兼容的代码可以在必要时执行 <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></p>
<p>一个新的命令行开关 <code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code> 可以对 Python 3.0 将移除的特性发出警告。 您可以使用该开关运行代码,以了解将代码移植到 3.0 所需的工作量。 Python 代码可以使用 <code class="xref py py-data docutils literal notranslate"><span class="pre">sys.py3kwarning</span></code> 访问该开关的值C 扩展代码可以使用 <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">参见</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://www.python.org/dev/peps/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://www.python.org/dev/peps/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>开发过程的变化<a class="headerlink" href="#changes-to-the-development-process" title="永久链接至标题"></a></h2>
<p>在开发2.6时Python开发过程经历了两个重大变化我们从SourceForge的问题跟踪程序切换到定制的Roundup安装文档从LaTeX转换为reStructuredText。</p>
<section id="new-issue-tracker-roundup">
<h3>新问题追踪:简述<a class="headerlink" href="#new-issue-tracker-roundup" title="永久链接至标题"></a></h3>
<p>很长一段时间以来Python开发人员对SourceForge的bug跟踪器越来越恼火。SourceForge的托管解决方案不允许进行大量定制例如无法定制问题的生命周期。</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="http://roundup.sourceforge.net/">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>在发出志愿者号召后在https://bugs.python.org的一个Roundup的安装可以托管多个跟踪器现在该服务器还托管Jython和Python网站的问题跟踪器。它肯定会在未来找到其他用途。在可能的情况下此版本的“What's New in Python”链接到每个更改的bug/补丁项。</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
<a class="reference external" href="http://svn.python.org/view/tracker/importer/">http://svn.python.org/view/tracker/importer/</a> and may be useful to
other projects wishing to move from SourceForge to Roundup.</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a></dt><dd><p>Python 的错误追踪器</p>
</dd>
<dt><a class="reference external" href="http://bugs.jython.org">http://bugs.jython.org</a>:</dt><dd><p>Jython 的错误追踪器</p>
</dd>
<dt><a class="reference external" href="http://roundup.sourceforge.net/">http://roundup.sourceforge.net/</a></dt><dd><p>Roundup 下载和文档。</p>
</dd>
<dt><a class="reference external" href="http://svn.python.org/view/tracker/importer/">http://svn.python.org/view/tracker/importer/</a></dt><dd><p>Martin von Löwis 的转换脚本。</p>
</dd>
</dl>
</div>
</section>
<section id="new-documentation-format-restructuredtext-using-sphinx">
<h3>新的文档格式:使用 Sphinx 的 reStructuredText<a class="headerlink" href="#new-documentation-format-restructuredtext-using-sphinx" title="永久链接至标题"></a></h3>
<p>自 1989 年左右项目启动以来Python 文档一直使用 LaTeX 编写。在 1980 年代和 1990 年代早期,大多数文档都是打印出来供日后学习的,而不是在网上查看。 LaTeX 被广泛使用,因为它既能提供美观的打印输出,又能在掌握了标记的基本规则后直接进行编写。</p>
<p>如今 LaTeX 仍被用于编写印刷出版物,但编程工具的格局已经发生了变化。 我们不再打印成堆的文档取而代之的是在线浏览HTML 已成为最重要的支持格式。 不幸的是,将 LaTeX 转换为 HTML 相当复杂,长期担任 Python 文档编辑的 Fred L. Drake Jr. 花了许多时间在维护转换过程上。 偶尔有人会建议将文档转换成 SGML之后再转换成 XML但进行良好的转换是一项艰巨的任务从来没有人投入所需的时间来完成这项工作。</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 专注于 HTML 输出,可生成吸引人风格的现代 HTML通过转换为 LaTeX仍可支持打印输出。输入格式是 reStructuredText这是一种支持自定义扩展和指令的标记语法在 Python 社区很常用。</p>
<p>Sphinx 是一个可用于写文档的独立软件包,将近二十多个其他项目 (<a class="reference external" href="https://www.sphinx-doc.org/en/master/examples.html">列在 Sphinx 网站</a> 上) 已采用 Sphinx 作为其文档工具。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><a class="reference external" href="https://devguide.python.org/documenting/">Documenting Python</a></dt><dd><p>描述如何编写Python文档。</p>
</dd>
<dt><a class="reference external" href="http://sphinx-doc.org/">Sphinx</a></dt><dd><p>Sphinx工具链的文档和代码。</p>
</dd>
<dt><a class="reference external" href="http://docutils.sourceforge.net">Docutils</a></dt><dd><p>reStructuredText 的基础解析器和工具集。</p>
</dd>
</dl>
</div>
</section>
</section>
<section id="pep-343-the-with-statement">
<span id="pep-0343"></span><h2>PEP 343: &quot;with&quot; 语句<a class="headerlink" href="#pep-343-the-with-statement" title="永久链接至标题"></a></h2>
<p>在 Python 2.5 之前的版本中,&quot;<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>&quot; 语句是一个可选功能,可以通过 <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> 指令启用。 在 2.6 中,该语句不再需要特别启用;这意味着 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> 现在总是一个关键字。 本节的其余部分是“Python 2.5 新特性”文档中相应部分的复制;如果您熟悉 Python 2.5 中的 '<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>' 语句,可以跳过本节。</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>' 语是一种基本结构如下所示的流程控制结构:</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 <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
methods).</p>
<p>The object's <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> 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 <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
method is called, even if the block raised an exception, and can therefore run
clean-up code.</p>
<p>一些标准 Python 对象现在已支持上下文管理协议并可被用于 '<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>' 语句。 文件对象就是一个例子:</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>在此语句被执行之后,文件对象 <em>f</em> 将被自动关闭,即使是当 <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> 循环在代码块中间引发了异常的时候也是如此。</p>
<div class="admonition note">
<p class="admonition-title">注解</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><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> 模块的加锁和条件变量也支持 '<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>' 语句:</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>这个锁会在代码块被执行之前锁定并总是会在代码块完成之后释放。</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>编写上下文管理器<a class="headerlink" href="#writing-context-managers" title="永久链接至标题"></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>在更高层级上对于上下文管理器协议的解释:</p>
<ul class="simple">
<li><p>The expression is evaluated and should result in an object called a &quot;context
manager&quot;. The context manager must have <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
methods.</p></li>
<li><p>The context manager's <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> 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><em>BLOCK</em> 中的代码会被执行。</p></li>
<li><p>If <em>BLOCK</em> raises an exception, the context manager's <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> 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 <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> 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 <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> 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 <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> 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>contextlib 模块<a class="headerlink" href="#the-contextlib-module" title="永久链接至标题"></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
<a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> 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 <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> 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">参见</p>
<dl class="simple">
<dt><span class="target" id="index-40"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - &quot;with&quot; 语句</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><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> 模块的文档。</p>
</div>
</section>
</section>
<section id="pep-366-explicit-relative-imports-from-a-main-module">
<span id="pep-0366"></span><h2>PEP 366: 从主模块显式相对导入<a class="headerlink" href="#pep-366-explicit-relative-imports-from-a-main-module" title="永久链接至标题"></a></h2>
<p>Python 的 <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> 开关允许将一个模块作为脚本来运行。 当你运行一个位于某个包内的模块时,相对导入将无法正确运作。</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: 分用户的 site-packages 目录<a class="headerlink" href="#pep-370-per-user-site-packages-directory" title="永久链接至标题"></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 引入了一个用于用户专属站点目录的惯例。 该目录根据具体系统平台各不相同:</p>
<ul class="simple">
<li><p>Unix 和 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">参见</p>
<dl class="simple">
<dt><span class="target" id="index-41"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0370"><strong>PEP 370</strong></a> - 分用户的 site-packages 目录</dt><dd><p>PEP 由 Christian Heimes 撰写并实现</p>
</dd>
</dl>
</div>
</section>
<section id="pep-371-the-multiprocessing-package">
<span id="pep-0371"></span><h2>PEP 371: 多任务处理包<a class="headerlink" href="#pep-371-the-multiprocessing-package" title="永久链接至标题"></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>这会产生以下输出:</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>这将产生如下输出:</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">参见</p>
<p><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> 模块的文档。</p>
<dl class="simple">
<dt><span class="target" id="index-42"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0371"><strong>PEP 371</strong></a> - 添加多任务处理包</dt><dd><p>PEP 由 Jesse Noller 和 Richard Oudkerk 撰写,由 Richard Oudkerk 和 Jesse Noller 实现</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3101-advanced-string-formatting">
<span id="pep-3101"></span><h2>PEP 3101: 高级字符串格式<a class="headerlink" href="#pep-3101-advanced-string-formatting" title="永久链接至标题"></a></h2>
<p>In Python 3.0, the <cite>%</cite> 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 <cite>.format()</cite> method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (<cite>{</cite>, <cite>}</cite>) 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="go">&#39;User ID: root Last seen: 5 Mar 2008 07:20&#39;</span>
</pre></div>
</div>
<p>Curly brackets can be escaped by doubling them:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;Empty dict: {{}}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">()</span>
<span class="go">&quot;Empty dict: {}&quot;</span>
</pre></div>
</div>
<p>Field names can be integers indicating positional arguments, such as
<code class="docutils literal notranslate"><span class="pre">{0}</span></code>, <code class="docutils literal notranslate"><span class="pre">{1}</span></code>, etc. or names of keyword arguments. You can also
supply compound field names that read attributes or access dictionary keys:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;Platform: </span><span class="si">{0.platform}</span><span class="se">\n</span><span class="s1">Python version: </span><span class="si">{0.version}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">sys</span><span class="p">)</span>
<span class="go">Platform: darwin</span>
<span class="go">Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41)</span>
<span class="go">[GCC 4.0.1 (Apple Computer, Inc. build 5367)]&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">mimetypes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Content-type: </span><span class="si">{0[.mp4]}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">mimetypes</span><span class="o">.</span><span class="n">types_map</span><span class="p">)</span>
<span class="go">&#39;Content-type: video/mp4&#39;</span>
</pre></div>
</div>
<p>Note that when using dictionary-style notation such as <code class="docutils literal notranslate"><span class="pre">[.mp4]</span></code>, you
don't need to put any quotation marks around the string; it will look
up the value using <code class="docutils literal notranslate"><span class="pre">.mp4</span></code> as the key. Strings beginning with a
number will be converted to an integer. You can't write more
complicated expressions inside a format string.</p>
<p>So far we've shown how to specify which field to substitute into the
resulting string. The precise formatting used is also controllable by
adding a colon followed by a format specifier. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Field 0: left justify, pad to 15 characters</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Field 1: right justify, pad to 6 characters</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="si">{0:15}</span><span class="s1"> $</span><span class="si">{1:&gt;6}</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Registration&#39;</span><span class="p">,</span> <span class="mi">35</span><span class="p">)</span>
<span class="go">&#39;Registration $ 35&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Tutorial&#39;</span><span class="p">,</span> <span class="mi">50</span><span class="p">)</span>
<span class="go">&#39;Tutorial $ 50&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Banquet&#39;</span><span class="p">,</span> <span class="mi">125</span><span class="p">)</span>
<span class="go">&#39;Banquet $ 125&#39;</span>
</pre></div>
</div>
<p>格式说明符可以通过嵌套来引用其他字段:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;{0:</span><span class="si">{1}</span><span class="s1">}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">15</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Invoice #1234&#39;</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span>
<span class="go">&#39;Invoice #1234 &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">35</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Invoice #1234&#39;</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span>
<span class="go">&#39;Invoice #1234 &#39;</span>
</pre></div>
</div>
<p>可以指定所需宽度内的字段对齐方式:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 27%" />
<col style="width: 73%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>字符</p></th>
<th class="head"><p>效果</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p>&lt; (默认)</p></td>
<td><p>左对齐</p></td>
</tr>
<tr class="row-odd"><td><p>&gt;</p></td>
<td><p>右对齐</p></td>
</tr>
<tr class="row-even"><td><p>^</p></td>
<td><p>居中对齐</p></td>
</tr>
<tr class="row-odd"><td><p>=</p></td>
<td><p>(仅适用于数字类型)在符号后加空格。</p></td>
</tr>
</tbody>
</table>
<p>Format specifiers can also include a presentation type, which
controls how the value is formatted. For example, floating-point numbers
can be formatted as a general number or in exponential notation:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0:g}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.75</span><span class="p">)</span>
<span class="go">&#39;3.75&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0:e}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.75</span><span class="p">)</span>
<span class="go">&#39;3.750000e+00&#39;</span>
</pre></div>
</div>
<p>A variety of presentation types are available. Consult the 2.6
documentation for a <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">complete list</span></a>; here's a sample:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 6%" />
<col style="width: 94%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">b</span></code></p></td>
<td><p>二进制。输出以2为底的数字。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">c</span></code></p></td>
<td><p>字符。在打印之前将整数转换为相应的Unicode字符。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">d</span></code></p></td>
<td><p>十进制整数。 输出以 10 为基数的数字。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">o</span></code></p></td>
<td><p>八进制格式。 输出以 8 为基数的数字。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span></code></p></td>
<td><p>十六进制格式。 输出以 16 为基数的数字,使用小写字母表示 9 以上的数码。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">e</span></code></p></td>
<td><p>指数表示法。用字母 'e' 以科学计数法打印数字以表示指数。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">g</span></code></p></td>
<td><p>General format. This prints the number as a fixed-point number, unless
the number is too large, in which case it switches to 'e' exponent
notation.</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">n</span></code></p></td>
<td><p>Number. This is the same as 'g' (for floats) or 'd' (for integers),
except that it uses the current locale setting to insert the appropriate
number separator characters.</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">%</span></code></p></td>
<td><p>Percentage. Multiplies the number by 100 and displays in fixed ('f')
format, followed by a percent sign.</p></td>
</tr>
</tbody>
</table>
<p>Classes and types can define a <a class="reference internal" href="../reference/datamodel.html#object.__format__" title="object.__format__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code></a> method to control how they're
formatted. It receives a single argument, the format specifier:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="fm">__format__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">format_spec</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">format_spec</span><span class="p">,</span> <span class="n">unicode</span><span class="p">):</span>
<span class="k">return</span> <span class="n">unicode</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
</pre></div>
</div>
<p>There's also a <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> builtin that will format a single
value. It calls the type's <a class="reference internal" href="../reference/datamodel.html#object.__format__" title="object.__format__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code></a> method with the
provided specifier:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="mf">75.6564</span><span class="p">,</span> <span class="s1">&#39;.2f&#39;</span><span class="p">)</span>
<span class="go">&#39;75.66&#39;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">格式字符串语法</span></a></dt><dd><p>格式字段的参考文档。</p>
</dd>
<dt><span class="target" id="index-43"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3101"><strong>PEP 3101</strong></a> - 高级字符串格式</dt><dd><p>PEP 由 Eric V. Smith 撰写并实现</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3105-print-as-a-function">
<span id="pep-3105"></span><h2>PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> 改为函数<a class="headerlink" href="#pep-3105-print-as-a-function" title="永久链接至标题"></a></h2>
<p>在 Python 3.0 中 <code class="docutils literal notranslate"><span class="pre">print</span></code> 语句变成了 <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> 函数。 将 <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> 变成函数使得可以通过 <code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">print(...)</span></code> 或从其他地方导入一个新函数来替换该函数。</p>
<p>Python 2.6 提供了 <code class="docutils literal notranslate"><span class="pre">__future__</span></code> 导入语句来移除 <code class="docutils literal notranslate"><span class="pre">print</span></code> 语法,让你可以改用函数形式。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">print_function</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;# of entries&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">dictionary</span><span class="p">),</span> <span class="n">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">)</span>
</pre></div>
</div>
<p>新函数的签名为:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">print</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">file</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>形参包括:</p>
<blockquote>
<div><ul class="simple">
<li><p><em>args</em>: 相应值将会被打印的位置参数。</p></li>
<li><p><em>sep</em>: 分隔符,它将在参数之间被打印。</p></li>
<li><p><em>end</em>: 结束文本,它将在所有参数输出完毕之后被打印。</p></li>
<li><p><em>file</em>: 将被作为输出发送目标的文件对象。</p></li>
</ul>
</div></blockquote>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-44"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3105"><strong>PEP 3105</strong></a> - print 改为函数</dt><dd><p>PEP 由 Georg Brandl 撰写</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3110-exception-handling-changes">
<span id="pep-3110"></span><h2>PEP 3110: 异常处理的变更<a class="headerlink" href="#pep-3110-exception-handling-changes" title="永久链接至标题"></a></h2>
<p>Python 程序员偶尔会犯的一个错误是编写这样的代码:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">ValueError</span><span class="p">:</span> <span class="c1"># Wrong!</span>
<span class="o">...</span>
</pre></div>
</div>
<p>The author is probably trying to catch both <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> and
<a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exceptions, but this code actually does something
different: it will catch <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> and bind the resulting
exception object to the local name <code class="docutils literal notranslate"><span class="pre">&quot;ValueError&quot;</span></code>. The
<a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception will not be caught at all. The correct
code specifies a tuple of exceptions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">except</span> <span class="p">(</span><span class="ne">TypeError</span><span class="p">,</span> <span class="ne">ValueError</span><span class="p">):</span>
<span class="o">...</span>
</pre></div>
</div>
<p>This error happens because the use of the comma here is ambiguous:
does it indicate two different nodes in the parse tree, or a single
node that's a tuple?</p>
<p>Python 3.0 makes this unambiguous by replacing the comma with the word
&quot;as&quot;. To catch an exception and store the exception object in the
variable <code class="docutils literal notranslate"><span class="pre">exc</span></code>, you must write:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">except</span> <span class="ne">TypeError</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
<span class="o">...</span>
</pre></div>
</div>
<p>Python 3.0 will only support the use of &quot;as&quot;, and therefore interprets
the first example as catching two different exceptions. Python 2.6
supports both the comma and &quot;as&quot;, so existing code will continue to
work. We therefore suggest using &quot;as&quot; when writing new Python code
that will only be executed with 2.6.</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-45"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3110"><strong>PEP 3110</strong></a> - 在 Python 3000 中捕获异常</dt><dd><p>PEP 由 Collin Winter 撰写并实现</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3112-byte-literals">
<span id="pep-3112"></span><h2>PEP 3112: 字节字面值<a class="headerlink" href="#pep-3112-byte-literals" title="永久链接至标题"></a></h2>
<p>Python 3.0 adopts Unicode as the language's fundamental string type and
denotes 8-bit literals differently, either as <code class="docutils literal notranslate"><span class="pre">b'string'</span></code>
or using a <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> constructor. For future compatibility,
Python 2.6 adds <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> as a synonym for the <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> type,
and it also supports the <code class="docutils literal notranslate"><span class="pre">b''</span></code> notation.</p>
<p>The 2.6 <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> differs from 3.0's <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> type in various
ways; most notably, the constructor is completely different. In 3.0,
<code class="docutils literal notranslate"><span class="pre">bytes([65,</span> <span class="pre">66,</span> <span class="pre">67])</span></code> is 3 elements long, containing the bytes
representing <code class="docutils literal notranslate"><span class="pre">ABC</span></code>; in 2.6, <code class="docutils literal notranslate"><span class="pre">bytes([65,</span> <span class="pre">66,</span> <span class="pre">67])</span></code> returns the
12-byte string representing the <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of the list.</p>
<p>The primary use of <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> in 2.6 will be to write tests of
object type such as <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">bytes)</span></code>. This will help the 2to3
converter, which can't tell whether 2.x code intends strings to
contain either characters or 8-bit bytes; you can now
use either <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> or <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> to represent your intention
exactly, and the resulting code will also be correct in Python 3.0.</p>
<p>There's also a <code class="docutils literal notranslate"><span class="pre">__future__</span></code> import that causes all string literals
to become Unicode strings. This means that <code class="docutils literal notranslate"><span class="pre">\u</span></code> escape sequences
can be used to include Unicode characters:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">unicode_literals</span>
<span class="n">s</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;</span><span class="se">\u751f\u3080\u304e\u3000\u751f\u3054</span><span class="s1">&#39;</span>
<span class="s1">&#39;</span><span class="se">\u3081\u3000\u751f\u305f\u307e\u3054</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="c1"># 12 Unicode characters</span>
</pre></div>
</div>
<p>At the C level, Python 3.0 will rename the existing 8-bit
string type, called <code class="xref c c-type docutils literal notranslate"><span class="pre">PyStringObject</span></code> in Python 2.x,
to <a class="reference internal" href="../c-api/bytes.html#c.PyBytesObject" title="PyBytesObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBytesObject</span></code></a>. Python 2.6 uses <code class="docutils literal notranslate"><span class="pre">#define</span></code>
to support using the names <a class="reference internal" href="../c-api/bytes.html#c.PyBytesObject" title="PyBytesObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytesObject()</span></code></a>,
<a class="reference internal" href="../c-api/bytes.html#c.PyBytes_Check" title="PyBytes_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_Check()</span></code></a>, <a class="reference internal" href="../c-api/bytes.html#c.PyBytes_FromStringAndSize" title="PyBytes_FromStringAndSize"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_FromStringAndSize()</span></code></a>,
and all the other functions and macros used with strings.</p>
<p><a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 类型的实例与字符串一样属于不可变对象。 新增的 <a class="reference internal" href="../library/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 类型则用于存储可变的字节序列:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bytearray</span><span class="p">([</span><span class="mi">65</span><span class="p">,</span> <span class="mi">66</span><span class="p">,</span> <span class="mi">67</span><span class="p">])</span>
<span class="go">bytearray(b&#39;ABC&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u21ef\u3244</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;\xe2\x87\xaf\xe3\x89\x84&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="se">\xe3</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;\xe3\x87\xaf\xe3\x89\x84&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">b</span><span class="p">),</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="go">u&#39;\u31ef \u3244&#39;</span>
</pre></div>
</div>
<p>字节数组支持大部分的字符串类型方法,如 <code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code>,以及列表的某些方法,如 <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code><code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code></p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="s1">&#39;ABC&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;e&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;ABCde&#39;)</span>
</pre></div>
</div>
<p>也有一个相应的 C API包含 <a class="reference internal" href="../c-api/bytearray.html#c.PyByteArray_FromObject" title="PyByteArray_FromObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_FromObject()</span></code></a>, <a class="reference internal" href="../c-api/bytearray.html#c.PyByteArray_FromStringAndSize" title="PyByteArray_FromStringAndSize"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_FromStringAndSize()</span></code></a> 以及各种其他函数。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-46"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3112"><strong>PEP 3112</strong></a> - Python 3000 中的字节字面值</dt><dd><p>PEP 由 Jason Orendorff 撰写, 补丁2.6 由 Christian Heimes 撰写。</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3116-new-i-o-library">
<span id="pep-3116"></span><h2>PEP 3116: 新 I/O 库<a class="headerlink" href="#pep-3116-new-i-o-library" title="永久链接至标题"></a></h2>
<p>Python's built-in file objects support a number of methods, but
file-like objects don't necessarily support all of them. Objects that
imitate files usually support <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>, but they
may not support <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, for example. Python 3.0 introduces
a layered I/O library in the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module that separates buffering
and text-handling features from the fundamental read and write
operations.</p>
<p>There are three levels of abstract base classes provided by
the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module:</p>
<ul>
<li><p><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code> defines raw I/O operations: <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code>,
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>.
Most of the methods of this class will often map to a single system call.
There are also <code class="xref py py-meth docutils literal notranslate"><span class="pre">readable()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">writable()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">seekable()</span></code>
methods for determining what operations a given object will allow.</p>
<p>Python 3.0 has concrete implementations of this class for files and
sockets, but Python 2.6 hasn't restructured its file and socket objects
in this way.</p>
</li>
<li><p><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code> is an abstract base class that
buffers data in memory to reduce the number of
system calls used, making I/O processing more efficient.
It supports all of the methods of <code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code>,
and adds a <code class="xref py py-attr docutils literal notranslate"><span class="pre">raw</span></code> attribute holding the underlying raw object.</p>
<p>There are five concrete classes implementing this ABC.
<code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code> are for objects
that support write-only or read-only usage that have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code>
method for random access. <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code> objects support
read and write access upon the same underlying stream, and
<code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code> is for objects such as TTYs that have both
read and write operations acting upon unconnected streams of data.
The <code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code> class supports reading, writing, and seeking
over an in-memory buffer.</p>
</li>
<li id="index-13"><p><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code>: Provides functions for reading and writing
strings (remember, strings will be Unicode in Python 3.0),
and supporting <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a>. <code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code> defines
the <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method and supports iteration upon
objects.</p>
<p>There are two concrete implementations. <code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code>
wraps a buffered I/O object, supporting all of the methods for
text I/O and adding a <code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer</span></code> attribute for access
to the underlying object. <code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code> simply buffers
everything in memory without ever writing anything to disk.</p>
<p>(In Python 2.6, <a class="reference internal" href="../library/io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> is implemented in
pure Python, so it's pretty slow. You should therefore stick with the
existing <code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code> module or <code class="xref py py-mod docutils literal notranslate"><span class="pre">cStringIO</span></code> for now. At some
point Python 3.0's <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module will be rewritten into C for speed,
and perhaps the C implementation will be backported to the 2.x releases.)</p>
</li>
</ul>
<p>In Python 2.6, the underlying implementations haven't been
restructured to build on top of the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module's classes. The
module is being provided to make it easier to write code that's
forward-compatible with 3.0, and to save developers the effort of writing
their own implementations of buffering and text I/O.</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-47"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3116"><strong>PEP 3116</strong></a> - 新 I/O</dt><dd><p>PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
Jeremy Hylton, Martin von Löwis, Tony Lownds, and others.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3118-revised-buffer-protocol">
<span id="pep-3118"></span><h2>PEP 3118: 修改缓冲区协议<a class="headerlink" href="#pep-3118-revised-buffer-protocol" title="永久链接至标题"></a></h2>
<p>The buffer protocol is a C-level API that lets Python types
exchange pointers into their internal representations. A
memory-mapped file can be viewed as a buffer of characters, for
example, and this lets another module such as <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
treat memory-mapped files as a string of characters to be searched.</p>
<p>The primary users of the buffer protocol are numeric-processing
packages such as NumPy, which expose the internal representation
of arrays so that callers can write data directly into an array instead
of going through a slower API. This PEP updates the buffer protocol in light of experience
from NumPy development, adding a number of new features
such as indicating the shape of an array or locking a memory region.</p>
<p>The most important new C API function is
<code class="docutils literal notranslate"><span class="pre">PyObject_GetBuffer(PyObject</span> <span class="pre">*obj,</span> <span class="pre">Py_buffer</span> <span class="pre">*view,</span> <span class="pre">int</span> <span class="pre">flags)</span></code>, which
takes an object and a set of flags, and fills in the
<code class="docutils literal notranslate"><span class="pre">Py_buffer</span></code> structure with information
about the object's memory representation. Objects
can use this operation to lock memory in place
while an external caller could be modifying the contents,
so there's a corresponding <code class="docutils literal notranslate"><span class="pre">PyBuffer_Release(Py_buffer</span> <span class="pre">*view)</span></code> to
indicate that the external caller is done.</p>
<p>The <em>flags</em> argument to <a class="reference internal" href="../c-api/buffer.html#c.PyObject_GetBuffer" title="PyObject_GetBuffer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetBuffer()</span></code></a> specifies
constraints upon the memory returned. Some examples are:</p>
<blockquote>
<div><ul class="simple">
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_WRITABLE</span></code> 指定内存必须为可写。</p></li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_LOCK</span></code> requests a read-only or exclusive lock on the memory.</p></li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_C_CONTIGUOUS</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_F_CONTIGUOUS</span></code>
requests a C-contiguous (last dimension varies the fastest) or
Fortran-contiguous (first dimension varies the fastest) array layout.</p></li>
</ul>
</div></blockquote>
<p>两个用于 <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> 的新参数代码 <code class="docutils literal notranslate"><span class="pre">s*</span></code><code class="docutils literal notranslate"><span class="pre">z*</span></code>,将为形参返回锁定的缓冲区对象。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-48"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3118"><strong>PEP 3118</strong></a> - 修改缓冲区协议</dt><dd><p>PEP 由 Travis Oliphant 和 Carl Banks 撰写,由 Travis Oliphant 实现。</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3119-abstract-base-classes">
<span id="pep-3119"></span><h2>PEP 3119: 抽象基类<a class="headerlink" href="#pep-3119-abstract-base-classes" title="永久链接至标题"></a></h2>
<p>Some object-oriented languages such as Java support interfaces,
declaring that a class has a given set of methods or supports a given
access protocol. Abstract Base Classes (or ABCs) are an equivalent
feature for Python. The ABC support consists of an <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to :pep:`3119`."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module
containing a metaclass called <code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code>, special handling of
this metaclass by the <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a>
builtins, and a collection of basic ABCs that the Python developers
think will be widely useful. Future versions of Python will probably
add more ABCs.</p>
<p>Let's say you have a particular class and wish to know whether it supports
dictionary-style access. The phrase &quot;dictionary-style&quot; is vague, however.
It probably means that accessing items with <code class="docutils literal notranslate"><span class="pre">obj[1]</span></code> works.
Does it imply that setting items with <code class="docutils literal notranslate"><span class="pre">obj[2]</span> <span class="pre">=</span> <span class="pre">value</span></code> works?
Or that the object will have <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>
methods? What about the iterative variants such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>? <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>? Iterating over the object with <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a>?</p>
<p>The Python 2.6 <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 includes a number of
different ABCs that represent these distinctions. <code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code>
indicates that a class defines <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, and
<code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code> means the class defines a <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>
method and therefore supports <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> expressions. The basic
dictionary interface of getting items, setting items, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>, is defined by the
<code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code> ABC.</p>
<p>You can derive your own classes from a particular ABC
to indicate they support that ABC's interface:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">collections</span>
<span class="k">class</span> <span class="nc">Storage</span><span class="p">(</span><span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="p">):</span>
<span class="o">...</span>
</pre></div>
</div>
<p>Alternatively, you could write the class without deriving from
the desired ABC and instead register the class by
calling the ABC's <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code> method:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">collections</span>
<span class="k">class</span> <span class="nc">Storage</span><span class="p">:</span>
<span class="o">...</span>
<span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Storage</span><span class="p">)</span>
</pre></div>
</div>
<p>For classes that you write, deriving from the ABC is probably clearer.
The <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code> method is useful when you've written a new
ABC that can describe an existing type or class, or if you want
to declare that some third-party class implements an ABC.
For example, if you defined a <code class="xref py py-class docutils literal notranslate"><span class="pre">PrintableType</span></code> ABC,
it's legal to do:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Register Python&#39;s types</span>
<span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">float</span><span class="p">)</span>
<span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span>
</pre></div>
</div>
<p>Classes should obey the semantics specified by an ABC, but
Python can't check this; it's up to the class author to
understand the ABC's requirements and to implement the code accordingly.</p>
<p>To check whether an object supports a particular interface, you can
now write:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">d</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Mapping object expected, not </span><span class="si">%r</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">d</span><span class="p">)</span>
</pre></div>
</div>
<p>Don't feel that you must now begin writing lots of checks as in the
above example. Python has a strong tradition of duck-typing, where
explicit type-checking is never done and code simply calls methods on
an object, trusting that those methods will be there and raising an
exception if they aren't. Be judicious in checking for ABCs and only
do it where it's absolutely necessary.</p>
<p>You can write your own ABCs by using <code class="docutils literal notranslate"><span class="pre">abc.ABCMeta</span></code> as the
metaclass in a class definition:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="kn">import</span> <span class="n">ABCMeta</span><span class="p">,</span> <span class="n">abstractmethod</span>
<span class="k">class</span> <span class="nc">Drawable</span><span class="p">():</span>
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
<span class="nd">@abstractmethod</span>
<span class="k">def</span> <span class="nf">draw</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="mf">1.0</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">def</span> <span class="nf">draw_doubled</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">draw</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="mf">2.0</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Square</span><span class="p">(</span><span class="n">Drawable</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">draw</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="p">):</span>
<span class="o">...</span>
</pre></div>
</div>
<p>In the <code class="xref py py-class docutils literal notranslate"><span class="pre">Drawable</span></code> ABC above, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw_doubled()</span></code> method
renders the object at twice its size and can be implemented in terms
of other methods described in <code class="xref py py-class docutils literal notranslate"><span class="pre">Drawable</span></code>. Classes implementing
this ABC therefore don't need to provide their own implementation
of <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw_doubled()</span></code>, though they can do so. An implementation
of <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw()</span></code> is necessary, though; the ABC can't provide
a useful generic implementation.</p>
<p>You can apply the <code class="docutils literal notranslate"><span class="pre">&#64;abstractmethod</span></code> decorator to methods such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">draw()</span></code> that must be implemented; Python will then raise an
exception for classes that don't define the method.
Note that the exception is only raised when you actually
try to create an instance of a subclass lacking the method:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Circle</span><span class="p">(</span><span class="n">Drawable</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Circle</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">Can&#39;t instantiate abstract class Circle with abstract methods draw</span>
<span class="gp">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Abstract data attributes can be declared using the
<code class="docutils literal notranslate"><span class="pre">&#64;abstractproperty</span></code> decorator:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="kn">import</span> <span class="n">abstractproperty</span>
<span class="o">...</span>
<span class="nd">@abstractproperty</span>
<span class="k">def</span> <span class="nf">readonly</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
</pre></div>
</div>
<p>Subclasses must then define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">readonly()</span></code> property.</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-49"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a> - 引入抽象基类</dt><dd><p>PEP written by Guido van Rossum and Talin.
Implemented by Guido van Rossum.
Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3127-integer-literal-support-and-syntax">
<span id="pep-3127"></span><h2>PEP 3127: 整型文字支持和语法<a class="headerlink" href="#pep-3127-integer-literal-support-and-syntax" title="永久链接至标题"></a></h2>
<p>Python 3.0 changes the syntax for octal (base-8) integer literals,
prefixing them with &quot;0o&quot; or &quot;0O&quot; instead of a leading zero, and adds
support for binary (base-2) integer literals, signalled by a &quot;0b&quot; or
&quot;0B&quot; prefix.</p>
<p>Python 2.6 doesn't drop support for a leading 0 signalling
an octal number, but it does add support for &quot;0o&quot; and &quot;0b&quot;:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mo">0o21</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="mi">8</span> <span class="o">+</span> <span class="mi">1</span>
<span class="go">(17, 17)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mb">0b101111</span>
<span class="go">47</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> builtin still returns numbers
prefixed with a leading zero, and a new <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>
builtin returns the binary representation for a number:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">oct</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="go">&#39;052&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">future_builtins</span><span class="o">.</span><span class="n">oct</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="go">&#39;0o52&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bin</span><span class="p">(</span><span class="mi">173</span><span class="p">)</span>
<span class="go">&#39;0b10101101&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> and <code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code> builtins will now accept the &quot;0o&quot;
and &quot;0b&quot; prefixes when base-8 or base-2 are requested, or when the
<em>base</em> argument is zero (signalling that the base used should be
determined from the string):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span> <span class="p">(</span><span class="s1">&#39;0o52&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;1101&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;0b1101&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;0b1101&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">13</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-50"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3127"><strong>PEP 3127</strong></a> - 整型文字支持和语法</dt><dd><p>PEP written by Patrick Maupin; backported to 2.6 by
Eric Smith.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3129-class-decorators">
<span id="pep-3129"></span><h2>PEP 3129: 类装饰器<a class="headerlink" href="#pep-3129-class-decorators" title="永久链接至标题"></a></h2>
<p>装饰器已从函数扩展到类。 现在可以合法地编写:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@foo</span>
<span class="nd">@bar</span>
<span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="k">pass</span>
</pre></div>
</div>
<p>这相当于:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="k">pass</span>
<span class="n">A</span> <span class="o">=</span> <span class="n">foo</span><span class="p">(</span><span class="n">bar</span><span class="p">(</span><span class="n">A</span><span class="p">))</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-51"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3129"><strong>PEP 3129</strong></a> - 类装饰器</dt><dd><p>PEP 由 Collin Winter 撰写</p>
</dd>
</dl>
</div>
</section>
<section id="pep-3141-a-type-hierarchy-for-numbers">
<span id="pep-3141"></span><h2>PEP 3141: 数字的类型层级结构<a class="headerlink" href="#pep-3141-a-type-hierarchy-for-numbers" title="永久链接至标题"></a></h2>
<p>Python 3.0 adds several abstract base classes for numeric types
inspired by Scheme's numeric tower. These classes were backported to
2.6 as the <a class="reference internal" href="../library/numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module.</p>
<p>The most general ABC is <code class="xref py py-class docutils literal notranslate"><span class="pre">Number</span></code>. It defines no operations at
all, and only exists to allow checking if an object is a number by
doing <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">Number)</span></code>.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code> is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Number</span></code>. Complex numbers
can undergo the basic operations of addition, subtraction,
multiplication, division, and exponentiation, and you can retrieve the
real and imaginary parts and obtain a number's conjugate. Python's built-in
complex type is an implementation of <code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code>.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code> further derives from <code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code>, and adds
operations that only work on real numbers: <code class="xref py py-func docutils literal notranslate"><span class="pre">floor()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code>,
rounding, taking the remainder mod N, floor division,
and comparisons.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code> numbers derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code>, have
<code class="xref py py-attr docutils literal notranslate"><span class="pre">numerator</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">denominator</span></code> properties, and can be
converted to floats. Python 2.6 adds a simple rational-number class,
<code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code>, in the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module. (It's called
<code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code> instead of <code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code> to avoid
a name clash with <a class="reference internal" href="../library/numbers.html#numbers.Rational" title="numbers.Rational"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Rational</span></code></a>.)</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> numbers derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code>, and
can be shifted left and right with <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code> and <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>,
combined using bitwise operations such as <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> and <code class="docutils literal notranslate"><span class="pre">|</span></code>,
and can be used as array indexes and slice boundaries.</p>
<p>In Python 3.0, the PEP slightly redefines the existing builtins
<a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a>, <a class="reference internal" href="../library/math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor()</span></code></a>, <a class="reference internal" href="../library/math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil()</span></code></a>, and adds a new
one, <a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a>, that's been backported to Python 2.6.
<a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a> rounds toward zero, returning the closest
<code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> that's between the function's argument and zero.</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt><span class="target" id="index-19"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3141"><strong>PEP 3141</strong></a> - A Type Hierarchy for Numbers</dt><dd><p>PEP 由 Jeffrey Yasskin 撰写</p>
</dd>
</dl>
<p><a class="reference external" href="https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower">Scheme's numerical tower</a>, from the Guile manual.</p>
<p><a class="reference external" href="http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2">Scheme's number datatypes</a> from the R5RS Scheme specification.</p>
</div>
<section id="the-fractions-module">
<h3><a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> 模块<a class="headerlink" href="#the-fractions-module" title="永久链接至标题"></a></h3>
<p>To fill out the hierarchy of numeric types, the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a>
module provides a rational-number class. Rational numbers store their
values as a numerator and denominator forming a fraction, and can
exactly represent numbers such as <code class="docutils literal notranslate"><span class="pre">2/3</span></code> that floating-point numbers
can only approximate.</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code> constructor takes two <code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> values
that will be the numerator and denominator of the resulting fraction.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fractions</span> <span class="kn">import</span> <span class="n">Fraction</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">Fraction</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Fraction</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="nb">float</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="go">(0.66666666666666663, 0.40000000000000002)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="go">Fraction(16, 15)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">/</span><span class="n">b</span>
<span class="go">Fraction(5, 3)</span>
</pre></div>
</div>
<p>For converting floating-point numbers to rationals,
the float type now has an <code class="xref py py-meth docutils literal notranslate"><span class="pre">as_integer_ratio()</span></code> method that returns
the numerator and denominator for a fraction that evaluates to the same
floating-point value:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">2.5</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(5, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">3.1415</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(7074029114692207L, 2251799813685248L)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">1.</span><span class="o">/</span><span class="mi">3</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(6004799503160661L, 18014398509481984L)</span>
</pre></div>
</div>
<p>Note that values that can only be approximated by floating-point
numbers, such as 1./3, are not simplified to the number being
approximated; the fraction attempts to match the floating-point value
<strong>exactly</strong>.</p>
<p>The <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module is based upon an implementation by Sjoerd
Mullender that was in Python's <code class="file docutils literal notranslate"><span class="pre">Demo/classes/</span></code> directory for a
long time. This implementation was significantly updated by Jeffrey
Yasskin.</p>
</section>
</section>
<section id="other-language-changes">
<h2>其他语言特性修改<a class="headerlink" href="#other-language-changes" title="永久链接至标题"></a></h2>
<p>对Python 语言核心进行的小改动:</p>
<ul>
<li><p>Directories and zip archives containing a <code class="file docutils literal notranslate"><span class="pre">__main__.py</span></code> file
can now be executed directly by passing their name to the
interpreter. The directory or zip archive is automatically inserted
as the first entry in sys.path. (Suggestion and initial patch by
Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1739468">bpo-1739468</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> function was catching and ignoring all errors,
under the assumption that they meant a <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method
was failing somehow and the return value of <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> would
therefore be <code class="docutils literal notranslate"><span class="pre">False</span></code>. This logic shouldn't be applied to
<a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>, however; Python 2.6
will no longer discard such exceptions when <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a>
encounters them. (Fixed by Benjamin Peterson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2196">bpo-2196</a>.)</p></li>
<li><p>When calling a function using the <code class="docutils literal notranslate"><span class="pre">**</span></code> syntax to provide keyword
arguments, you are no longer required to use a Python dictionary;
any mapping will now work:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">kw</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="o">=</span><span class="n">UserDict</span><span class="o">.</span><span class="n">UserDict</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;string&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="o">**</span><span class="n">ud</span><span class="p">)</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;]</span>
</pre></div>
</div>
<p>(由 Alexander Belopolsky 在 <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1686487">bpo-1686487</a> 中贡献。)</p>
<p>在函数调用的 <code class="docutils literal notranslate"><span class="pre">*args</span></code> 参数之后提供关键字参数也是合法的。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">args</span><span class="p">,</span> <span class="n">kw</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">),</span> <span class="n">keyword</span><span class="o">=</span><span class="mi">13</span><span class="p">)</span>
<span class="go">(1, 2, 3, 4, 5, 6) {&#39;keyword&#39;: 13}</span>
</pre></div>
</div>
<p>在之前版本中这会导致语法错误。 (由 Amaury Forgeot d'Arc 贡献;<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3473">bpo-3473</a>。)</p>
</li>
<li><p>A new builtin, <code class="docutils literal notranslate"><span class="pre">next(iterator,</span> <span class="pre">[default])</span></code> returns the next item
from the specified iterator. If the <em>default</em> argument is supplied,
it will be returned if <em>iterator</em> has been exhausted; otherwise,
the <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception will be raised. (Backported
in <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2719">bpo-2719</a>.)</p></li>
<li><p>Tuples now have <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code> methods matching the
list type's <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code> methods:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">2</span>
</pre></div>
</div>
<p>(由 Raymond Hettinger 贡献)</p>
</li>
<li><p>The built-in types now have improved support for extended slicing syntax,
accepting various combinations of <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code>.
Previously, the support was partial and certain corner cases wouldn't work.
(Implemented by Thomas Wouters.)</p>
</li>
<li><p>Properties now have three attributes, <code class="xref py py-attr docutils literal notranslate"><span class="pre">getter</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">setter</span></code>
and <code class="xref py py-attr docutils literal notranslate"><span class="pre">deleter</span></code>, that are decorators providing useful shortcuts
for adding a getter, setter or deleter function to an existing
property. You would use them like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
<span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>
<span class="k">def</span> <span class="nf">x</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="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span>
<span class="nd">@x</span><span class="o">.</span><span class="n">deleter</span>
<span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
<span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
<span class="nd">@C</span><span class="o">.</span><span class="n">x</span><span class="o">.</span><span class="n">getter</span>
<span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">*</span> <span class="mi">2</span>
<span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>
<span class="k">def</span> <span class="nf">x</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="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span> <span class="o">/</span> <span class="mi">2</span>
</pre></div>
</div>
</li>
<li><p>Several methods of the built-in set types now accept multiple iterables:
<code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">difference()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">difference_update()</span></code>.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">=</span><span class="nb">set</span><span class="p">(</span><span class="s1">&#39;1234567890&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="s1">&#39;abc123&#39;</span><span class="p">,</span> <span class="s1">&#39;cdf246&#39;</span><span class="p">)</span> <span class="c1"># Intersection between all inputs</span>
<span class="go">set([&#39;2&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">difference</span><span class="p">(</span><span class="s1">&#39;246&#39;</span><span class="p">,</span> <span class="s1">&#39;789&#39;</span><span class="p">)</span>
<span class="go">set([&#39;1&#39;, &#39;0&#39;, &#39;3&#39;, &#39;5&#39;])</span>
</pre></div>
</div>
<p>(由 Raymond Hettinger 贡献。)</p>
</li>
<li><p>Many floating-point features were added. The <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> function
will now turn the string <code class="docutils literal notranslate"><span class="pre">nan</span></code> into an
IEEE 754 Not A Number value, and <code class="docutils literal notranslate"><span class="pre">+inf</span></code> and <code class="docutils literal notranslate"><span class="pre">-inf</span></code> into
positive or negative infinity. This works on any platform with
IEEE 754 semantics. (Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1635">bpo-1635</a>.)</p>
<p>Other functions in the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module, <code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code>, return true if their floating-point argument is
infinite or Not A Number. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1640">bpo-1640</a>)</p>
<p>Conversion functions were added to convert floating-point numbers
into hexadecimal strings (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3008">bpo-3008</a>). These functions
convert floats to and from a string representation without
introducing rounding errors from the conversion between decimal and
binary. Floats have a <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">hex()</span></code></a> method that returns a string
representation, and the <code class="docutils literal notranslate"><span class="pre">float.fromhex()</span></code> method converts a string
back into a number:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mf">3.75</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;0x1.e000000000000p+1&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;0x1.e000000000000p+1&#39;</span><span class="p">)</span>
<span class="go">3.75</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">=</span><span class="mf">1.</span><span class="o">/</span><span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;0x1.5555555555555p-2&#39;</span>
</pre></div>
</div>
</li>
<li><p>A numerical nicety: when creating a complex number from two floats
on systems that support signed zeros (-0 and +0), the
<a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> constructor will now preserve the sign
of the zero. (Fixed by Mark T. Dickinson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1507">bpo-1507</a>.)</p></li>
<li><p>Classes that inherit a <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method from a parent class
can set <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> to indicate that the class isn't
hashable. This will make <code class="docutils literal notranslate"><span class="pre">hash(obj)</span></code> raise a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>
and the class will not be indicated as implementing the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Hashable</span></code> ABC.</p>
<p>You should do this when you've defined a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code> or
<a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method that compares objects by their value rather
than by identity. All objects have a default hash method that uses
<code class="docutils literal notranslate"><span class="pre">id(obj)</span></code> as the hash value. There's no tidy way to remove the
<a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method inherited from a parent class, so
assigning <code class="docutils literal notranslate"><span class="pre">None</span></code> was implemented as an override. At the
C level, extensions can set <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> to
<a class="reference internal" href="../c-api/object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a>.
(Fixed by Nick Coghlan and Amaury Forgeot d'Arc; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2235">bpo-2235</a>.)</p>
</li>
<li><p>The <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception now subclasses
<a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> instead of <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>. This means
that an exception handler that does <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">Exception:</span></code>
will not inadvertently catch <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>.
(Contributed by Chad Austin; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1537">bpo-1537</a>.)</p></li>
<li><p>Generator objects now have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_code</span></code> attribute that refers to
the original code object backing the generator.
(Contributed by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1473257">bpo-1473257</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> built-in function now accepts keyword arguments
as well as positional parameters. (Contributed by Thomas Wouters;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1444529">bpo-1444529</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> constructor now accepts strings containing
parenthesized complex numbers, meaning that <code class="docutils literal notranslate"><span class="pre">complex(repr(cplx))</span></code>
will now round-trip values. For example, <code class="docutils literal notranslate"><span class="pre">complex('(3+4j)')</span></code>
now returns the value (3+4j). (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1491866">bpo-1491866</a>)</p></li>
<li><p>The string <code class="xref py py-meth docutils literal notranslate"><span class="pre">translate()</span></code> method now accepts <code class="docutils literal notranslate"><span class="pre">None</span></code> as the
translation table parameter, which is treated as the identity
transformation. This makes it easier to carry out operations
that only delete characters. (Contributed by Bengt Richter and
implemented by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1193128">bpo-1193128</a>.)</p></li>
<li><p>The built-in <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> function now checks for a <a class="reference internal" href="../reference/datamodel.html#object.__dir__" title="object.__dir__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__dir__()</span></code></a>
method on the objects it receives. This method must return a list
of strings containing the names of valid attributes for the object,
and lets the object control the value that <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> produces.
Objects that have <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a>
methods can use this to advertise pseudo-attributes they will honor.
(<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1591665">bpo-1591665</a>)</p></li>
<li><p>Instance method objects have new attributes for the object and function
comprising the method; the new synonym for <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> is
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> is also available as <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code>.
The old names are still supported in Python 2.6, but are gone in 3.0.</p></li>
<li><p>An obscure change: when you use the <a class="reference internal" href="../library/functions.html#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> function inside a
<a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a> statement, the resulting dictionary no longer returns free
variables. (Free variables, in this case, are variables referenced in the
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code> statement that aren't attributes of the class.)</p></li>
</ul>
<section id="optimizations">
<h3>性能优化<a class="headerlink" href="#optimizations" title="永久链接至标题"></a></h3>
<ul>
<li><p>The <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module has been rewritten in C. This makes
it possible to invoke warnings from the parser, and may also
make the interpreter's startup faster.
(Contributed by Neal Norwitz and Brett Cannon; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1631171">bpo-1631171</a>.)</p></li>
<li><p>Type objects now have a cache of methods that can reduce
the work required to find the correct method implementation
for a particular class; once cached, the interpreter doesn't need to
traverse base classes to figure out the right method to call.
The cache is cleared if a base class or the class itself is modified,
so the cache should remain correct even in the face of Python's dynamic
nature.
(Original optimization implemented by Armin Rigo, updated for
Python 2.6 by Kevin Jacobs; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1700288">bpo-1700288</a>.)</p>
<p>By default, this change is only applied to types that are included with
the Python core. Extension modules may not necessarily be compatible with
this cache,
so they must explicitly add <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_VERSION_TAG</span></code>
to the module's <code class="docutils literal notranslate"><span class="pre">tp_flags</span></code> field to enable the method cache.
(To be compatible with the method cache, the extension module's code
must not directly access and modify the <code class="docutils literal notranslate"><span class="pre">tp_dict</span></code> member of
any of the types it implements. Most modules don't do this,
but it's impossible for the Python interpreter to determine that.
See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1878">bpo-1878</a> for some discussion.)</p>
</li>
<li><p>Function calls that use keyword arguments are significantly faster
by doing a quick pointer comparison, usually saving the time of a
full string comparison. (Contributed by Raymond Hettinger, after an
initial implementation by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1819">bpo-1819</a>.)</p></li>
<li><p>All of the functions in 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 have been rewritten in
C, thanks to work at the Need For Speed sprint.
(Contributed by Raymond Hettinger.)</p></li>
<li><p>Some of the standard built-in types now set a bit in their type
objects. This speeds up checking whether an object is a subclass of
one of these types. (Contributed by Neal Norwitz.)</p></li>
<li><p>Unicode strings now use faster code for detecting
whitespace and line breaks; this speeds up the <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> method
by about 25% and <code class="xref py py-meth docutils literal notranslate"><span class="pre">splitlines()</span></code> by 35%.
(Contributed by Antoine Pitrou.) Memory usage is reduced
by using pymalloc for the Unicode string's data.</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">with</span></code> statement now stores the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method on the stack,
producing a small speedup. (Implemented by Jeffrey Yasskin.)</p></li>
<li><p>To reduce memory usage, the garbage collector will now clear internal
free lists when garbage-collecting the highest generation of objects.
This may return memory to the operating system sooner.</p></li>
</ul>
</section>
<section id="interpreter-changes">
<span id="new-26-interpreter"></span><h3>解释器改动<a class="headerlink" href="#interpreter-changes" title="永久链接至标题"></a></h3>
<p>Two command-line options have been reserved for use by other Python
implementations. The <a class="reference internal" href="../using/cmdline.html#cmdoption-j"><code class="xref std std-option docutils literal notranslate"><span class="pre">-J</span></code></a> switch has been reserved for use by
Jython for Jython-specific options, such as switches that are passed to
the underlying JVM. <a class="reference internal" href="../using/cmdline.html#id5"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span></code></a> has been reserved for options
specific to a particular implementation of Python such as CPython,
Jython, or IronPython. If either option is used with Python 2.6, the
interpreter will report that the option isn't currently used.</p>
<p>Python can now be prevented from writing <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code>
files by supplying the <a class="reference internal" href="../using/cmdline.html#id1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a> switch to the Python interpreter,
or by setting the <span class="target" id="index-20"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment
variable before running the interpreter. This setting is available to
Python programs as the <code class="docutils literal notranslate"><span class="pre">sys.dont_write_bytecode</span></code> variable, and
Python code can change the value to modify the interpreter's
behaviour. (Contributed by Neal Norwitz and Georg Brandl.)</p>
<p>The encoding used for standard input, output, and standard error can
be specified by setting the <span class="target" id="index-21"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONIOENCODING"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONIOENCODING</span></code></a> environment
variable before running the interpreter. The value should be a string
in the form <code class="docutils literal notranslate"><span class="pre">&lt;encoding&gt;</span></code> or <code class="docutils literal notranslate"><span class="pre">&lt;encoding&gt;:&lt;errorhandler&gt;</span></code>.
The <em>encoding</em> part specifies the encoding's name, e.g. <code class="docutils literal notranslate"><span class="pre">utf-8</span></code> or
<code class="docutils literal notranslate"><span class="pre">latin-1</span></code>; the optional <em>errorhandler</em> part specifies
what to do with characters that can't be handled by the encoding,
and should be one of &quot;error&quot;, &quot;ignore&quot;, or &quot;replace&quot;. (Contributed
by Martin von Löwis.)</p>
</section>
</section>
<section id="new-and-improved-modules">
<h2>新增和改进的模块<a class="headerlink" href="#new-and-improved-modules" title="永久链接至标题"></a></h2>
<p>As in every release, Python's standard library received a number of
enhancements and bug fixes. Here's a partial list of the most notable
changes, sorted alphabetically by module name. Consult the
<code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more complete list of
changes, or look through the Subversion logs for all the details.</p>
<ul>
<li><p>The <a class="reference internal" href="../library/asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> and <a class="reference internal" href="../library/asynchat.html#module-asynchat" title="asynchat: Support for asynchronous command/response protocols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code></a> modules are
being actively maintained again, and a number of patches and bugfixes
were applied. (Maintained by Josiah Carlson; see <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1736190">bpo-1736190</a> for
one patch.)</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code> module also has a new maintainer, Jesús Cea Avión, and the package
is now available as a standalone package. The web page for the package is
<a class="reference external" href="https://www.jcea.es/programacion/pybsddb.htm">www.jcea.es/programacion/pybsddb.htm</a>.
The plan is to remove the package from the standard library
in Python 3.0, because its pace of releases is much more frequent than
Python's.</p>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb.dbshelve</span></code> module now uses the highest pickling protocol
available, instead of restricting itself to protocol 1.
(Contributed by W. Barnes.)</p>
</li>
<li><p>The <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module will now read variables from the query string
of an HTTP POST request. This makes it possible to use form actions
with URLs that include query strings such as
&quot;/cgi-bin/add.py?category=1&quot;. (Contributed by Alexandre Fiori and
Nubis; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1817">bpo-1817</a>.)</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qs()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qsl()</span></code> functions have been
relocated from the <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module to the <code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code> module.
The versions still available in the <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module will
trigger <a class="reference internal" href="../library/exceptions.html#PendingDeprecationWarning" title="PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a> messages in 2.6
(<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=600362">bpo-600362</a>).</p>
</li>
<li><p>The <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module underwent extensive revision,
contributed by Mark Dickinson and Christian Heimes.
Five new functions were added:</p>
<ul class="simple">
<li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">polar()</span></code> converts a complex number to polar form, returning
the modulus and argument of the complex number.</p></li>
<li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">rect()</span></code> does the opposite, turning a modulus, argument pair
back into the corresponding complex number.</p></li>
<li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">phase()</span></code> returns the argument (also called the angle) of a complex
number.</p></li>
<li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code> returns True if either
the real or imaginary part of its argument is a NaN.</p></li>
<li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code> returns True if either the real or imaginary part of
its argument is infinite.</p></li>
</ul>
<p>The revisions also improved the numerical soundness of the
<a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module. For all functions, the real and imaginary
parts of the results are accurate to within a few units of least
precision (ulps) whenever possible. See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1381">bpo-1381</a> for the
details. The branch cuts for <code class="xref py py-func docutils literal notranslate"><span class="pre">asinh()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">atanh()</span></code>: and
<code class="xref py py-func docutils literal notranslate"><span class="pre">atan()</span></code> have also been corrected.</p>
<p>The tests for the module have been greatly expanded; nearly 2000 new
test cases exercise the algebraic functions.</p>
<p>On IEEE 754 platforms, the <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module now handles IEEE 754
special values and floating-point exceptions in a manner consistent
with Annex 'G' of the C99 standard.</p>
</li>
<li><p>A new data type in 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: <code class="xref py py-class docutils literal notranslate"><span class="pre">namedtuple(typename,</span>
<span class="pre">fieldnames)</span></code> is a factory function that creates subclasses of the standard tuple
whose fields are accessible by name as well as index. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">var_type</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;variable&#39;</span><span class="p">,</span>
<span class="gp">... </span> <span class="s1">&#39;id name type size&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Names are separated by spaces or commas.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># &#39;id, name, type, size&#39; would also work.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">var_type</span><span class="o">.</span><span class="n">_fields</span>
<span class="go">(&#39;id&#39;, &#39;name&#39;, &#39;type&#39;, &#39;size&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">var</span> <span class="o">=</span> <span class="n">var_type</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;frequency&#39;</span><span class="p">,</span> <span class="s1">&#39;int&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">var</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">var</span><span class="o">.</span><span class="n">id</span> <span class="c1"># Equivalent</span>
<span class="go">1 1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">var</span><span class="p">[</span><span class="mi">2</span><span class="p">],</span> <span class="n">var</span><span class="o">.</span><span class="n">type</span> <span class="c1"># Equivalent</span>
<span class="go">int int</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">var</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
<span class="go">{&#39;size&#39;: 4, &#39;type&#39;: &#39;int&#39;, &#39;id&#39;: 1, &#39;name&#39;: &#39;frequency&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v2</span> <span class="o">=</span> <span class="n">var</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;amplitude&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v2</span>
<span class="go">variable(id=1, name=&#39;amplitude&#39;, type=&#39;int&#39;, size=4)</span>
</pre></div>
</div>
<p>Several places in the standard library that returned tuples have
been modified to return <code class="xref py py-class docutils literal notranslate"><span class="pre">namedtuple</span></code> instances. For example,
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">Decimal.as_tuple()</span></code> method now returns a named tuple with
<code class="xref py py-attr docutils literal notranslate"><span class="pre">sign</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">digits</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">exponent</span></code> fields.</p>
<p>(由 Raymond Hettinger 贡献。)</p>
</li>
<li><p>Another change to 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 is that the
<code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> type now supports an optional <em>maxlen</em> parameter;
if supplied, the deque's size will be restricted to no more
than <em>maxlen</em> items. Adding more items to a full deque causes
old items to be discarded.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">=</span><span class="n">deque</span><span class="p">(</span><span class="n">maxlen</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
<span class="go">deque([], maxlen=3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span> <span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
<span class="go">deque([1, 2, 3], maxlen=3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
<span class="go">deque([2, 3, 4], maxlen=3)</span>
</pre></div>
</div>
<p>(由 Raymond Hettinger 贡献。)</p>
</li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code> module's <code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code> objects now support an
<code class="xref py py-attr docutils literal notranslate"><span class="pre">httponly</span></code> attribute. In some browsers. cookies with this attribute
set cannot be accessed or manipulated by JavaScript code.
(Contributed by Arvin Schnell; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1638033">bpo-1638033</a>.)</p></li>
<li><p>A new window method in the <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">chgat()</span></code>, changes the display attributes for a certain number of
characters on a single line. (Contributed by Fabian Kreutz.)</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Boldface text starting at y=0,x=21</span>
<span class="c1"># and affecting the rest of the line.</span>
<span class="n">stdscr</span><span class="o">.</span><span class="n">chgat</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">21</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">A_BOLD</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> class in the <a class="reference internal" href="../library/curses.html#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> module
now supports editing in insert mode as well as overwrite mode.
Insert mode is enabled by supplying a true value for the <em>insert_mode</em>
parameter when creating the <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> instance.</p>
</li>
<li><p>The <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module's <code class="xref py py-meth docutils literal notranslate"><span class="pre">strftime()</span></code> methods now support a
<code class="docutils literal notranslate"><span class="pre">%f</span></code> format code that expands to the number of microseconds in the
object, zero-padded on
the left to six places. (Contributed by Skip Montanaro; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1158">bpo-1158</a>.)</p></li>
<li><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 was updated to version 1.66 of
<a class="reference external" href="http://speleotrove.com/decimal/decarith.html">the General Decimal Specification</a>. New features
include some methods for some basic mathematical functions such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">exp()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">log10()</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </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">exp</span><span class="p">()</span>
<span class="go">Decimal(&quot;2.718281828459045235360287471&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s2">&quot;2.7182818&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">ln</span><span class="p">()</span>
<span class="go">Decimal(&quot;0.9999999895305022877376682436&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span><span class="o">.</span><span class="n">log10</span><span class="p">()</span>
<span class="go">Decimal(&quot;3&quot;)</span>
</pre></div>
</div>
<p>现在 <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> 对象的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">as_tuple()</span></code> 方法将返回一个由 <code class="xref py py-attr docutils literal notranslate"><span class="pre">sign</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">digits</span></code><code class="xref py py-attr docutils literal notranslate"><span class="pre">exponent</span></code> 字段组成的具名元组。</p>
<p>(由 Facundo Batista 和 Mark Dickinson 实现。 具名元组支持由 Raymond Hettinger 添加。)</p>
</li>
<li><p>现在 <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> 模块的 <code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code> 类将返回代表匹配结果的具名元组,包含 <code class="xref py py-attr docutils literal notranslate"><span class="pre">a</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">b</span></code><code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code> 等属性。 (由 Raymond Hettinger 贡献。)</p></li>
<li><p>An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter, specifying a timeout measured in
seconds, was added to the <a class="reference internal" href="../library/ftplib.html#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">ftplib.FTP</span></code></a> class constructor as
well as the <code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code> method. (Added by Facundo Batista.)
Also, the <code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code> class's <code class="xref py py-meth docutils literal notranslate"><span class="pre">storbinary()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">storlines()</span></code> now take an optional <em>callback</em> parameter that
will be called with each block of data after the data has been sent.
(Contributed by Phil Schwartz; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1221598">bpo-1221598</a>.)</p></li>
<li><p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code> built-in function is also available in the
<a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module. In Python 3.0, the builtin has been
dropped and <code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code> is only available from <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a>;
currently there are no plans to drop the builtin in the 2.x series.
(Patched by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1739906">bpo-1739906</a>.)</p></li>
<li><p>When possible, the <a class="reference internal" href="../library/getpass.html#module-getpass" title="getpass: Portable reading of passwords and retrieval of the userid."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getpass</span></code></a> module will now use
<code class="file docutils literal notranslate"><span class="pre">/dev/tty</span></code> to print a prompt message and read the password,
falling back to standard error and standard input. If the
password may be echoed to the terminal, a warning is printed before
the prompt is displayed. (Contributed by Gregory P. Smith.)</p></li>
<li><p>The <a class="reference internal" href="../library/glob.html#glob.glob" title="glob.glob"><code class="xref py py-func docutils literal notranslate"><span class="pre">glob.glob()</span></code></a> function can now return Unicode filenames if
a Unicode path was used and Unicode filenames are matched within the
directory. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1001604">bpo-1001604</a>)</p></li>
<li><p>A new function in 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, <code class="docutils literal notranslate"><span class="pre">merge(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...)</span></code>,
takes any number of iterables returning data in sorted
order, and returns a new generator that returns the contents of all
the iterators, also in sorted order. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">heapq</span><span class="o">.</span><span class="n">merge</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">9</span><span class="p">],</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">16</span><span class="p">]))</span>
<span class="go">[1, 2, 3, 5, 8, 9, 16]</span>
</pre></div>
</div>
<p>Another new function, <code class="docutils literal notranslate"><span class="pre">heappushpop(heap,</span> <span class="pre">item)</span></code>,
pushes <em>item</em> onto <em>heap</em>, then pops off and returns the smallest item.
This is more efficient than making a call to <code class="xref py py-func docutils literal notranslate"><span class="pre">heappush()</span></code> and then
<code class="xref py py-func docutils literal notranslate"><span class="pre">heappop()</span></code>.</p>
<p><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> is now implemented to only use less-than comparison,
instead of the less-than-or-equal comparison it previously used.
This makes <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>'s usage of a type match the
<a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> method.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p>An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter, specifying a timeout measured in
seconds, was added to the <code class="xref py py-class docutils literal notranslate"><span class="pre">httplib.HTTPConnection</span></code> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPSConnection</span></code> class constructors. (Added by Facundo
Batista.)</p></li>
<li><p>Most of the <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> module's functions, such as
<code class="xref py py-func docutils literal notranslate"><span class="pre">getmoduleinfo()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">getargs()</span></code>, now return named tuples.
In addition to behaving like tuples, the elements of the return value
can also be accessed as attributes.
(Contributed by Raymond Hettinger.)</p>
<p>此模块中的新增函数包括 <code class="xref py py-func docutils literal notranslate"><span class="pre">isgenerator()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">isgeneratorfunction()</span></code><code class="xref py py-func docutils literal notranslate"><span class="pre">isabstract()</span></code></p>
</li>
<li><p><a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> 模块增加了几个新函数。</p>
<p><code class="docutils literal notranslate"><span class="pre">izip_longest(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...[,</span> <span class="pre">fillvalue])</span></code> makes tuples from
each of the elements; if some of the iterables are shorter than
others, the missing values are set to <em>fillvalue</em>. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">tuple</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">izip_longest</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">]))</span>
<span class="go">((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">product(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...,</span> <span class="pre">[repeat=N])</span></code> returns the Cartesian product
of the supplied iterables, a set of tuples containing
every possible combination of the elements returned from each iterable.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">]))</span>
<span class="go">[(1, 4), (1, 5), (1, 6),</span>
<span class="go"> (2, 4), (2, 5), (2, 6),</span>
<span class="go"> (3, 4), (3, 5), (3, 6)]</span>
</pre></div>
</div>
<p>The optional <em>repeat</em> keyword argument is used for taking the
product of an iterable or a set of iterables with themselves,
repeated <em>N</em> times. With a single iterable argument, <em>N</em>-tuples
are returned:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">))</span>
<span class="go">[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),</span>
<span class="go"> (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]</span>
</pre></div>
</div>
<p>With two iterables, <em>2N</em>-tuples are returned.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="n">repeat</span><span class="o">=</span><span class="mi">2</span><span class="p">))</span>
<span class="go">[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),</span>
<span class="go"> (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),</span>
<span class="go"> (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),</span>
<span class="go"> (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">combinations(iterable,</span> <span class="pre">r)</span></code> 基于 <em>iterable</em> 的元素返回长度为 <em>r</em> 的子序列。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;123&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[(&#39;1&#39;, &#39;2&#39;), (&#39;1&#39;, &#39;3&#39;), (&#39;2&#39;, &#39;3&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;123&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="go">[(&#39;1&#39;, &#39;2&#39;, &#39;3&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;1234&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="go">[(&#39;1&#39;, &#39;2&#39;, &#39;3&#39;), (&#39;1&#39;, &#39;2&#39;, &#39;4&#39;),</span>
<span class="go"> (&#39;1&#39;, &#39;3&#39;, &#39;4&#39;), (&#39;2&#39;, &#39;3&#39;, &#39;4&#39;)]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">permutations(iter[,</span> <span class="pre">r])</span></code> returns all the permutations of length <em>r</em> of
the iterable's elements. If <em>r</em> is not specified, it will default to the
number of elements produced by the iterable.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">permutations</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[(1, 2), (1, 3), (1, 4),</span>
<span class="go"> (2, 1), (2, 3), (2, 4),</span>
<span class="go"> (3, 1), (3, 2), (3, 4),</span>
<span class="go"> (4, 1), (4, 2), (4, 3)]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.chain(*iterables)</span></code> is an existing function in
<a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> that gained a new constructor in Python 2.6.
<code class="docutils literal notranslate"><span class="pre">itertools.chain.from_iterable(iterable)</span></code> takes a single
iterable that should return other iterables. <code class="xref py py-func docutils literal notranslate"><span class="pre">chain()</span></code> will
then return all the elements of the first iterable, then
all the elements of the second, and so on.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">chain</span><span class="o">.</span><span class="n">from_iterable</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">]]))</span>
<span class="go">[1, 2, 3, 4, 5, 6]</span>
</pre></div>
</div>
<p>(全部由 Raymond Hettinger 贡献。)</p>
</li>
<li><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's <code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code> class
and its subclasses <code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code>,
and <code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code> now
have an optional <em>delay</em> parameter to their constructors. If <em>delay</em>
is true, opening of the log file is deferred until the first
<code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code> call is made. (Contributed by Vinay Sajip.)</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code> also has a <em>utc</em> constructor
parameter. If the argument is true, UTC time will be used
in determining when midnight occurs and in generating filenames;
otherwise local time will be used.</p>
</li>
<li><p><a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> 模块添加了一些新函数:</p>
<ul class="simple">
<li><p><a class="reference internal" href="../library/math.html#math.isinf" title="math.isinf"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code></a> and <a class="reference internal" href="../library/math.html#math.isnan" title="math.isnan"><code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code></a> determine whether a given float
is a (positive or negative) infinity or a NaN (Not a Number), respectively.</p></li>
<li><p><a class="reference internal" href="../library/math.html#math.copysign" title="math.copysign"><code class="xref py py-func docutils literal notranslate"><span class="pre">copysign()</span></code></a> copies the sign bit of an IEEE 754 number,
returning the absolute value of <em>x</em> combined with the sign bit of
<em>y</em>. For example, <code class="docutils literal notranslate"><span class="pre">math.copysign(1,</span> <span class="pre">-0.0)</span></code> returns -1.0.
(Contributed by Christian Heimes.)</p></li>
<li><p><a class="reference internal" href="../library/math.html#math.factorial" title="math.factorial"><code class="xref py py-func docutils literal notranslate"><span class="pre">factorial()</span></code></a> computes the factorial of a number.
(Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2138">bpo-2138</a>.)</p></li>
<li><p><a class="reference internal" href="../library/math.html#math.fsum" title="math.fsum"><code class="xref py py-func docutils literal notranslate"><span class="pre">fsum()</span></code></a> adds up the stream of numbers from an iterable,
and is careful to avoid loss of precision through using partial sums.
(Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2819">bpo-2819</a>.)</p></li>
<li><p><a class="reference internal" href="../library/math.html#math.acosh" title="math.acosh"><code class="xref py py-func docutils literal notranslate"><span class="pre">acosh()</span></code></a>, <a class="reference internal" href="../library/math.html#math.asinh" title="math.asinh"><code class="xref py py-func docutils literal notranslate"><span class="pre">asinh()</span></code></a>
and <a class="reference internal" href="../library/math.html#math.atanh" title="math.atanh"><code class="xref py py-func docutils literal notranslate"><span class="pre">atanh()</span></code></a> compute the inverse hyperbolic functions.</p></li>
<li><p><a class="reference internal" href="../library/math.html#math.log1p" title="math.log1p"><code class="xref py py-func docutils literal notranslate"><span class="pre">log1p()</span></code></a> 返回 <em>1+x</em> (以 <em>e</em> 为底) 的自然对数。</p></li>
<li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code> rounds a number toward zero, returning the closest
<code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> that's between the function's argument and zero.
Added as part of the backport of
<a class="reference external" href="#pep-3141">PEP 3141's type hierarchy for numbers</a>.</p></li>
</ul>
</li>
<li><p>The <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module has been improved to give more consistent
behaviour across platforms, especially with respect to handling of
floating-point exceptions and IEEE 754 special values.</p>
<p>Whenever possible, the module follows the recommendations of the C99
standard about 754's special values. For example, <code class="docutils literal notranslate"><span class="pre">sqrt(-1.)</span></code>
should now give a <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> across almost all platforms,
while <code class="docutils literal notranslate"><span class="pre">sqrt(float('NaN'))</span></code> should return a NaN on all IEEE 754
platforms. Where Annex 'F' of the C99 standard recommends signaling
'divide-by-zero' or 'invalid', Python will raise <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.
Where Annex 'F' of the C99 standard recommends signaling 'overflow',
Python will raise <a class="reference internal" href="../library/exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>. (See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=711019">bpo-711019</a> and
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1640">bpo-1640</a>.)</p>
<p>(由 Christian Heimes 和 Mark Dickinson 贡献。)</p>
</li>
<li><p><a class="reference internal" href="../library/mmap.html#mmap.mmap" title="mmap.mmap"><code class="xref py py-class docutils literal notranslate"><span class="pre">mmap</span></code></a> objects now have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code> method that searches for a
substring beginning at the end of the string and searching
backwards. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code> method also gained an <em>end</em> parameter
giving an index at which to stop searching.
(Contributed by John Lenton.)</p></li>
<li><p>The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module gained a
<code class="xref py py-func docutils literal notranslate"><span class="pre">methodcaller()</span></code> function that takes a name and an optional
set of arguments, returning a callable that will call
the named function on any arguments passed to it. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Equivalent to lambda s: s.replace(&#39;old&#39;, &#39;new&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">replacer</span> <span class="o">=</span> <span class="n">operator</span><span class="o">.</span><span class="n">methodcaller</span><span class="p">(</span><span class="s1">&#39;replace&#39;</span><span class="p">,</span> <span class="s1">&#39;old&#39;</span><span class="p">,</span> <span class="s1">&#39;new&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">replacer</span><span class="p">(</span><span class="s1">&#39;old wine in old bottles&#39;</span><span class="p">)</span>
<span class="go">&#39;new wine in new bottles&#39;</span>
</pre></div>
</div>
<p>(由 Gregory Petrosyan 提供建议,之后由 Georg Brandl 贡献。)</p>
<p>现在 <code class="xref py py-func docutils literal notranslate"><span class="pre">attrgetter()</span></code> 函数可接受带点号的名称并执行相应的属性查找:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span> <span class="o">=</span> <span class="n">operator</span><span class="o">.</span><span class="n">attrgetter</span><span class="p">(</span>
<span class="gp">... </span> <span class="s1">&#39;__class__.__name__&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="go">&#39;str&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span><span class="p">(</span><span class="n">help</span><span class="p">)</span>
<span class="go">&#39;_Helper&#39;</span>
</pre></div>
</div>
<p>(由 Barry Warsaw 提供建议,之后由 Georg Brandl 贡献。)</p>
</li>
<li><p>The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module now wraps several new system calls.
<code class="docutils literal notranslate"><span class="pre">fchmod(fd,</span> <span class="pre">mode)</span></code> and <code class="docutils literal notranslate"><span class="pre">fchown(fd,</span> <span class="pre">uid,</span> <span class="pre">gid)</span></code> change the mode
and ownership of an opened file, and <code class="docutils literal notranslate"><span class="pre">lchmod(path,</span> <span class="pre">mode)</span></code> changes
the mode of a symlink. (Contributed by Georg Brandl and Christian
Heimes.)</p>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">chflags()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">lchflags()</span></code> are wrappers for the
corresponding system calls (where they're available), changing the
flags set on a file. Constants for the flag values are defined in
the <a class="reference internal" href="../library/stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> module; some possible values include
<code class="xref py py-const docutils literal notranslate"><span class="pre">UF_IMMUTABLE</span></code> to signal the file may not be changed and
<code class="xref py py-const docutils literal notranslate"><span class="pre">UF_APPEND</span></code> to indicate that data can only be appended to the
file. (Contributed by M. Levinson.)</p>
<p><code class="docutils literal notranslate"><span class="pre">os.closerange(low,</span> <span class="pre">high)</span></code> efficiently closes all file descriptors
from <em>low</em> to <em>high</em>, ignoring any errors and not including <em>high</em> itself.
This function is now used by the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module to make starting
processes faster. (Contributed by Georg Brandl; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1663329">bpo-1663329</a>.)</p>
</li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> object's <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code> method will now unset the
environment variables using <a class="reference internal" href="../library/os.html#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.unsetenv()</span></code></a> in addition to clearing
the object's keys. (Contributed by Martin Horcicka; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1181">bpo-1181</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/os.html#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.walk()</span></code></a> function now has a <code class="docutils literal notranslate"><span class="pre">followlinks</span></code> parameter. If
set to True, it will follow symlinks pointing to directories and
visit the directory's contents. For backward compatibility, the
parameter's default value is false. Note that the function can fall
into an infinite recursion if there's a symlink that points to a
parent directory. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1273829">bpo-1273829</a>)</p></li>
<li><p>In the <a class="reference internal" href="../library/os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module, the <code class="xref py py-func docutils literal notranslate"><span class="pre">splitext()</span></code> function
has been changed to not split on leading period characters.
This produces better results when operating on Unix's dot-files.
For example, <code class="docutils literal notranslate"><span class="pre">os.path.splitext('.ipython')</span></code>
now returns <code class="docutils literal notranslate"><span class="pre">('.ipython',</span> <span class="pre">'')</span></code> instead of <code class="docutils literal notranslate"><span class="pre">('',</span> <span class="pre">'.ipython')</span></code>.
(<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1115886">bpo-1115886</a>)</p>
<p>A new function, <code class="docutils literal notranslate"><span class="pre">os.path.relpath(path,</span> <span class="pre">start='.')</span></code>, returns a relative path
from the <code class="docutils literal notranslate"><span class="pre">start</span></code> path, if it's supplied, or from the current
working directory to the destination <code class="docutils literal notranslate"><span class="pre">path</span></code>. (Contributed by
Richard Barran; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1339796">bpo-1339796</a>.)</p>
<p>On Windows, <a class="reference internal" href="../library/os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a> will now expand environment variables
given in the form &quot;%var%&quot;, and &quot;~user&quot; will be expanded into the
user's home directory path. (Contributed by Josiah Carlson;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=957650">bpo-957650</a>.)</p>
</li>
<li><p>The Python debugger provided by the <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a> module
gained a new command: &quot;run&quot; restarts the Python program being debugged
and can optionally take new command-line arguments for the program.
(Contributed by Rocky Bernstein; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1393667">bpo-1393667</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/pdb.html#pdb.post_mortem" title="pdb.post_mortem"><code class="xref py py-func docutils literal notranslate"><span class="pre">pdb.post_mortem()</span></code></a> function, used to begin debugging a
traceback, will now use the traceback 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>
if no traceback is supplied. (Contributed by Facundo Batista;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1106316">bpo-1106316</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/pickletools.html#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a> module now has an <code class="xref py py-func docutils literal notranslate"><span class="pre">optimize()</span></code> function
that takes a string containing a pickle and removes some unused
opcodes, returning a shorter pickle that contains the same data structure.
(Contributed by Raymond Hettinger.)</p></li>
<li><p>A <code class="xref py py-func docutils literal notranslate"><span class="pre">get_data()</span></code> function was added to the <a class="reference internal" href="../library/pkgutil.html#module-pkgutil" title="pkgutil: Utilities for the import system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pkgutil</span></code></a>
module that returns the contents of resource files included
with an installed Python package. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pkgutil</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">pkgutil</span><span class="o">.</span><span class="n">get_data</span><span class="p">(</span><span class="s1">&#39;test&#39;</span><span class="p">,</span> <span class="s1">&#39;exception_hierarchy.txt&#39;</span><span class="p">)</span>
<span class="go">BaseException</span>
<span class="go"> +-- SystemExit</span>
<span class="go"> +-- KeyboardInterrupt</span>
<span class="go"> +-- GeneratorExit</span>
<span class="go"> +-- Exception</span>
<span class="go"> +-- StopIteration</span>
<span class="go"> +-- StandardError</span>
<span class="go"> ...</span>
</pre></div>
</div>
<p>(由 Paul Moore 在 <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2439">bpo-2439</a> 中贡献。)</p>
</li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module's <code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code> objects now allow setting
their <code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_size</span></code> attribute to change the size of the buffer
used to hold character data.
(Contributed by Achim Gaedke; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1137">bpo-1137</a>.)</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code> module now provides queue variants that retrieve entries
in different orders. The <code class="xref py py-class docutils literal notranslate"><span class="pre">PriorityQueue</span></code> class stores
queued items in a heap and retrieves them in priority order,
and <code class="xref py py-class docutils literal notranslate"><span class="pre">LifoQueue</span></code> retrieves the most recently added entries first,
meaning that it behaves like a stack.
(Contributed by Raymond Hettinger.)</p></li>
<li><p>The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module's <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> objects can
now be pickled on a 32-bit system and unpickled on a 64-bit
system, and vice versa. Unfortunately, this change also means
that Python 2.6's <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> objects can't be unpickled correctly
on earlier versions of Python.
(Contributed by Shawn Ligocki; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1727780">bpo-1727780</a>.)</p>
<p>The new <code class="docutils literal notranslate"><span class="pre">triangular(low,</span> <span class="pre">high,</span> <span class="pre">mode)</span></code> function returns random
numbers following a triangular distribution. The returned values
are between <em>low</em> and <em>high</em>, not including <em>high</em> itself, and
with <em>mode</em> as the most frequently occurring value
in the distribution. (Contributed by Wladmir van der Laan and
Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1681432">bpo-1681432</a>.)</p>
</li>
<li><p>Long regular expression searches carried out by the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
module will check for signals being delivered, so
time-consuming searches can now be interrupted.
(Contributed by Josh Hoyt and Ralf Schmitt; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=846388">bpo-846388</a>.)</p>
<p>The regular expression module is implemented by compiling bytecodes
for a tiny regex-specific virtual machine. Untrusted code
could create malicious strings of bytecode directly and cause crashes,
so Python 2.6 includes a verifier for the regex bytecode.
(Contributed by Guido van Rossum from work for Google App Engine;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3487">bpo-3487</a>.)</p>
</li>
<li><p>The <a class="reference internal" href="../library/rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> module's <code class="xref py py-meth docutils literal notranslate"><span class="pre">Completer.complete()</span></code> method
will now ignore exceptions triggered while evaluating a name.
(Fixed by Lorenz Quack; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2250">bpo-2250</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/sched.html#module-sched" title="sched: General purpose event scheduler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sched</span></code></a> module's <code class="xref py py-class docutils literal notranslate"><span class="pre">scheduler</span></code> instances now
have a read-only <a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-attr docutils literal notranslate"><span class="pre">queue</span></code></a> attribute that returns the
contents of the scheduler's queue, represented as a list of
named tuples with the fields <code class="docutils literal notranslate"><span class="pre">(time,</span> <span class="pre">priority,</span> <span class="pre">action,</span> <span class="pre">argument)</span></code>.
(Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1861">bpo-1861</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/select.html#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">select</span></code></a> module now has wrapper functions
for the Linux <code class="xref c c-func docutils literal notranslate"><span class="pre">epoll()</span></code> and BSD <code class="xref c c-func docutils literal notranslate"><span class="pre">kqueue()</span></code> system calls.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">modify()</span></code> method was added to the existing <code class="xref py py-class docutils literal notranslate"><span class="pre">poll</span></code>
objects; <code class="docutils literal notranslate"><span class="pre">pollobj.modify(fd,</span> <span class="pre">eventmask)</span></code> takes a file descriptor
or file object and an event mask, modifying the recorded event mask
for that file.
(Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1657">bpo-1657</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/shutil.html#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copytree()</span></code></a> function now has an optional <em>ignore</em> argument
that takes a callable object. This callable will receive each directory path
and a list of the directory's contents, and returns a list of names that
will be ignored, not copied.</p>
<p>The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module also provides an <code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code>
function for use with this new parameter. <code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code>
takes an arbitrary number of glob-style patterns and returns a
callable that will ignore any files and directories that match any
of these patterns. The following example copies a directory tree,
but skips both <code class="file docutils literal notranslate"><span class="pre">.svn</span></code> directories and Emacs backup files,
which have names ending with '~':</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">shutil</span><span class="o">.</span><span class="n">copytree</span><span class="p">(</span><span class="s1">&#39;Doc/library&#39;</span><span class="p">,</span> <span class="s1">&#39;/tmp/library&#39;</span><span class="p">,</span>
<span class="n">ignore</span><span class="o">=</span><span class="n">shutil</span><span class="o">.</span><span class="n">ignore_patterns</span><span class="p">(</span><span class="s1">&#39;*~&#39;</span><span class="p">,</span> <span class="s1">&#39;.svn&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>(由 Tarek Ziadé 在 <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2663">bpo-2663</a> 中贡献。)</p>
</li>
<li><p>Integrating signal handling with GUI handling event loops
like those used by Tkinter or GTk+ has long been a problem; most
software ends up polling, waking up every fraction of a second to check
if any GUI events have occurred.
The <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module can now make this more efficient.
Calling <code class="docutils literal notranslate"><span class="pre">signal.set_wakeup_fd(fd)</span></code> sets a file descriptor
to be used; when a signal is received, a byte is written to that
file descriptor. There's also a C-level function,
<a class="reference internal" href="../c-api/exceptions.html#c.PySignal_SetWakeupFd" title="PySignal_SetWakeupFd"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySignal_SetWakeupFd()</span></code></a>, for setting the descriptor.</p>
<p>Event loops will use this by opening a pipe to create two descriptors,
one for reading and one for writing. The writable descriptor
will be passed to <code class="xref py py-func docutils literal notranslate"><span class="pre">set_wakeup_fd()</span></code>, and the readable descriptor
will be added to the list of descriptors monitored by the event loop via
<code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> or <code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code>.
On receiving a signal, a byte will be written and the main event loop
will be woken up, avoiding the need to poll.</p>
<p>(由 Adam Olsen 在 <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1583">bpo-1583</a> 中贡献。)</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">siginterrupt()</span></code> function is now available from Python code,
and allows changing whether signals can interrupt system calls or not.
(Contributed by Ralf Schmitt.)</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">getitimer()</span></code> functions have also been
added (where they're available). <code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code>
allows setting interval timers that will cause a signal to be
delivered to the process after a specified time, measured in
wall-clock time, consumed process time, or combined process+system
time. (Contributed by Guilherme Polo; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2240">bpo-2240</a>.)</p>
</li>
<li><p>The <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> module now supports SMTP over SSL thanks to the
addition of the <code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP_SSL</span></code> class. This class supports an
interface identical to the existing <code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code> class.
(Contributed by Monty Taylor.) Both class constructors also have an
optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter that specifies a timeout for the
initial connection attempt, measured in seconds. (Contributed by
Facundo Batista.)</p>
<p>An implementation of the LMTP protocol (<span class="target" id="index-22"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2033.html"><strong>RFC 2033</strong></a>) was also added
to the module. LMTP is used in place of SMTP when transferring
e-mail between agents that don't manage a mail queue. (LMTP
implemented by Leif Hedstrom; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=957003">bpo-957003</a>.)</p>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">SMTP.starttls()</span></code> now complies with <span class="target" id="index-23"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3207.html"><strong>RFC 3207</strong></a> and forgets any
knowledge obtained from the server not obtained from the TLS
negotiation itself. (Patch contributed by Bill Fenner;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=829951">bpo-829951</a>.)</p>
</li>
<li><p>The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module now supports TIPC (<a class="reference external" href="http://tipc.sourceforge.net/">http://tipc.sourceforge.net/</a>),
a high-performance non-IP-based protocol designed for use in clustered
environments. TIPC addresses are 4- or 5-tuples.
(Contributed by Alberto Bertogli; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1646">bpo-1646</a>.)</p>
<p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">create_connection()</span></code>, takes an address and
connects to it using an optional timeout value, returning the
connected socket object. This function also looks up the address's
type and connects to it using IPv4 or IPv6 as appropriate. Changing
your code to use <code class="xref py py-func docutils literal notranslate"><span class="pre">create_connection()</span></code> instead of
<code class="docutils literal notranslate"><span class="pre">socket(socket.AF_INET,</span> <span class="pre">...)</span></code> may be all that's required to make
your code work with IPv6.</p>
</li>
<li><p>The base classes in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code> module now support
calling a <code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_timeout()</span></code> method after a span of inactivity
specified by the server's <code class="xref py py-attr docutils literal notranslate"><span class="pre">timeout</span></code> attribute. (Contributed
by Michael Pomraning.) The <code class="xref py py-meth docutils literal notranslate"><span class="pre">serve_forever()</span></code> method
now takes an optional poll interval measured in seconds,
controlling how often the server will check for a shutdown request.
(Contributed by Pedro Werneck and Jeffrey Yasskin;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=742598">bpo-742598</a>, <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1193577">bpo-1193577</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module, maintained by Gerhard Häring,
has been updated from version 2.3.2 in Python 2.5 to
version 2.4.1.</p></li>
<li><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 now supports the C99 <code class="xref c c-type docutils literal notranslate"><span class="pre">_Bool</span></code> type,
using the format character <code class="docutils literal notranslate"><span class="pre">'?'</span></code>.
(Contributed by David Remahl.)</p></li>
<li><p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code> objects provided by the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module
now have <code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">kill()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">send_signal()</span></code> methods.
On Windows, <code class="xref py py-meth docutils literal notranslate"><span class="pre">send_signal()</span></code> only supports the <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGTERM</span></code>
signal, and all these methods are aliases for the Win32 API function
<code class="xref c c-func docutils literal notranslate"><span class="pre">TerminateProcess()</span></code>.
(Contributed by Christian Heimes.)</p></li>
<li><p>A new variable in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module, <code class="xref py py-attr docutils literal notranslate"><span class="pre">float_info</span></code>, is an
object containing information derived from the <code class="file docutils literal notranslate"><span class="pre">float.h</span></code> file
about the platform's floating-point support. Attributes of this
object include <code class="xref py py-attr docutils literal notranslate"><span class="pre">mant_dig</span></code> (number of digits in the mantissa),
<code class="xref py py-attr docutils literal notranslate"><span class="pre">epsilon</span></code> (smallest difference between 1.0 and the next
largest value representable), and several others. (Contributed by
Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1534">bpo-1534</a>.)</p>
<p>Another new variable, <code class="xref py py-attr docutils literal notranslate"><span class="pre">dont_write_bytecode</span></code>, controls whether Python
writes any <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files on importing a module.
If this variable is true, the compiled files are not written. The
variable is initially set on start-up by supplying the <a class="reference internal" href="../using/cmdline.html#id1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a>
switch to the Python interpreter, or by setting the
<span class="target" id="index-24"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment variable before
running the interpreter. Python code can subsequently
change the value of this variable to control whether bytecode files
are written or not.
(Contributed by Neal Norwitz and Georg Brandl.)</p>
<p>Information about the command-line arguments supplied to the Python
interpreter is available by reading attributes of a named
tuple available as <code class="docutils literal notranslate"><span class="pre">sys.flags</span></code>. For example, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">verbose</span></code>
attribute is true if Python
was executed in verbose mode, <code class="xref py py-attr docutils literal notranslate"><span class="pre">debug</span></code> is true in debugging mode, etc.
These attributes are all read-only.
(Contributed by Christian Heimes.)</p>
<p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">getsizeof()</span></code>, takes a Python object and returns
the amount of memory used by the object, measured in bytes. Built-in
objects return correct results; third-party extensions may not,
but can define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__sizeof__()</span></code> method to return the
object's size.
(Contributed by Robert Schuppenies; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2898">bpo-2898</a>.)</p>
<p>It's now possible to determine the current profiler and tracer functions
by calling <a class="reference internal" href="../library/sys.html#sys.getprofile" title="sys.getprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getprofile()</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.gettrace" title="sys.gettrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.gettrace()</span></code></a>.
(Contributed by Georg Brandl; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1648">bpo-1648</a>.)</p>
</li>
<li><p>The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module now supports POSIX.1-2001 (pax) tarfiles in
addition to the POSIX.1-1988 (ustar) and GNU tar formats that were
already supported. The default format is GNU tar; specify the
<code class="docutils literal notranslate"><span class="pre">format</span></code> parameter to open a file using a different format:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;output.tar&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">,</span>
<span class="nb">format</span><span class="o">=</span><span class="n">tarfile</span><span class="o">.</span><span class="n">PAX_FORMAT</span><span class="p">)</span>
</pre></div>
</div>
<p>The new <code class="docutils literal notranslate"><span class="pre">encoding</span></code> and <code class="docutils literal notranslate"><span class="pre">errors</span></code> parameters specify an encoding and
an error handling scheme for character conversions. <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> are the three standard ways Python can
handle errors,;
<code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> is a special value that replaces bad characters with
their UTF-8 representation. (Character conversions occur because the
PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">TarFile.add()</span></code> method now accepts an <code class="docutils literal notranslate"><span class="pre">exclude</span></code> argument that's
a function that can be used to exclude certain filenames from
an archive.
The function must take a filename and return true if the file
should be excluded or false if it should be archived.
The function is applied to both the name initially passed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>
and to the names of files in recursively-added directories.</p>
<p>(所有改变均由 Lars Gustäbel 贡献)。</p>
</li>
<li><p><a class="reference internal" href="../library/telnetlib.html#telnetlib.Telnet" title="telnetlib.Telnet"><code class="xref py py-class docutils literal notranslate"><span class="pre">telnetlib.Telnet</span></code></a> 类构造器增加了可选的 <code class="docutils literal notranslate"><span class="pre">timeout</span></code> 形参,指定以秒为单位的超时设置。 (由 Facundo Batista 添加。)</p></li>
<li><p>The <a class="reference internal" href="../library/tempfile.html#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">tempfile.NamedTemporaryFile</span></code></a> class usually deletes
the temporary file it created when the file is closed. This
behaviour can now be changed by passing <code class="docutils literal notranslate"><span class="pre">delete=False</span></code> to the
constructor. (Contributed by Damien Miller; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1537850">bpo-1537850</a>.)</p>
<p>A new class, <code class="xref py py-class docutils literal notranslate"><span class="pre">SpooledTemporaryFile</span></code>, behaves like
a temporary file but stores its data in memory until a maximum size is
exceeded. On reaching that limit, the contents will be written to
an on-disk temporary file. (Contributed by Dustin J. Mitchell.)</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">NamedTemporaryFile</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">SpooledTemporaryFile</span></code> classes
both work as context managers, so you can write
<code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">tempfile.NamedTemporaryFile()</span> <span class="pre">as</span> <span class="pre">tmp:</span> <span class="pre">...</span></code>.
(Contributed by Alexander Belopolsky; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2021">bpo-2021</a>.)</p>
</li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.test_support</span></code> module gained a number
of context managers useful for writing tests.
<code class="xref py py-func docutils literal notranslate"><span class="pre">EnvironmentVarGuard()</span></code> is a
context manager that temporarily changes environment variables and
automatically restores them to their old values.</p>
<p>Another context manager, <code class="xref py py-class docutils literal notranslate"><span class="pre">TransientResource</span></code>, can surround calls
to resources that may or may not be available; it will catch and
ignore a specified list of exceptions. For example,
a network test may ignore certain failures when connecting to an
external web site:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">test_support</span><span class="o">.</span><span class="n">TransientResource</span><span class="p">(</span><span class="ne">IOError</span><span class="p">,</span>
<span class="n">errno</span><span class="o">=</span><span class="n">errno</span><span class="o">.</span><span class="n">ETIMEDOUT</span><span class="p">):</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;https://sf.net&#39;</span><span class="p">)</span>
<span class="o">...</span>
</pre></div>
</div>
<p>Finally, <code class="xref py py-func docutils literal notranslate"><span class="pre">check_warnings()</span></code> resets the <code class="xref py py-mod docutils literal notranslate"><span class="pre">warning</span></code> module's
warning filters and returns an object that will record all warning
messages triggered (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3781">bpo-3781</a>):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">test_support</span><span class="o">.</span><span class="n">check_warnings</span><span class="p">()</span> <span class="k">as</span> <span class="n">wrec</span><span class="p">:</span>
<span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;always&quot;</span><span class="p">)</span>
<span class="c1"># ... code that triggers a warning ...</span>
<span class="k">assert</span> <span class="nb">str</span><span class="p">(</span><span class="n">wrec</span><span class="o">.</span><span class="n">message</span><span class="p">)</span> <span class="o">==</span> <span class="s2">&quot;function is outdated&quot;</span>
<span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">wrec</span><span class="o">.</span><span class="n">warnings</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;Multiple warnings raised&quot;</span>
</pre></div>
</div>
<p>(由 Brett Cannon 贡献。)</p>
</li>
<li><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 can now preserve existing whitespace
at the beginnings and ends of the newly-created lines
by specifying <code class="docutils literal notranslate"><span class="pre">drop_whitespace=False</span></code>
as an argument:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;This sentence has a bunch of</span>
<span class="gp">... </span><span class="s2"> extra whitespace.&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">S</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
<span class="go">This sentence</span>
<span class="go">has a bunch</span>
<span class="go">of extra</span>
<span class="go">whitespace.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">S</span><span class="p">,</span> <span class="n">drop_whitespace</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
<span class="go">This sentence</span>
<span class="go"> has a bunch</span>
<span class="go"> of extra</span>
<span class="go"> whitespace.</span>
<span class="gp">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>(由 Dwayne Bailey 在 <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1581073">bpo-1581073</a> 中贡献。)</p>
</li>
<li><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 API is being changed to use properties
such as <code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code> instead of <code class="xref py py-meth docutils literal notranslate"><span class="pre">setDaemon()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">isDaemon()</span></code> methods, and some methods have been renamed to use
underscores instead of camel-case; for example, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">activeCount()</span></code> method is renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">active_count()</span></code>. Both
the 2.6 and 3.0 versions of the module support the same properties
and renamed methods, but don't remove the old methods. No date has been set
for the deprecation of the old APIs in Python 3.x; the old APIs won't
be removed in any 2.x version.
(Carried out by several people, most notably Benjamin Peterson.)</p>
<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 <code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code> objects
gained an <code class="xref py py-attr docutils literal notranslate"><span class="pre">ident</span></code> property that returns the thread's
identifier, a nonzero integer. (Contributed by Gregory P. Smith;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2871">bpo-2871</a>.)</p>
</li>
<li><p>The <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module now accepts callables as well as strings
for the statement being timed and for the setup code.
Two convenience functions were added for creating
<code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code> instances:
<code class="docutils literal notranslate"><span class="pre">repeat(stmt,</span> <span class="pre">setup,</span> <span class="pre">time,</span> <span class="pre">repeat,</span> <span class="pre">number)</span></code> and
<code class="docutils literal notranslate"><span class="pre">timeit(stmt,</span> <span class="pre">setup,</span> <span class="pre">time,</span> <span class="pre">number)</span></code> create an instance and call
the corresponding method. (Contributed by Erik Demaine;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1533909">bpo-1533909</a>.)</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code> module now accepts lists and tuples for options,
separating the elements by spaces before passing the resulting value to
Tcl/Tk.
(Contributed by Guilherme Polo; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2906">bpo-2906</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/turtle.html#module-turtle" title="turtle: An educational framework for simple graphics applications"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> module for turtle graphics was greatly enhanced by
Gregor Lingl. New features in the module include:</p>
<ul class="simple">
<li><p>Better animation of turtle movement and rotation.</p></li>
<li><p>Control over turtle movement using the new <code class="xref py py-meth docutils literal notranslate"><span class="pre">delay()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">tracer()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">speed()</span></code> methods.</p></li>
<li><p>The ability to set new shapes for the turtle, and to
define a new coordinate system.</p></li>
<li><p>Turtles now have an <code class="xref py py-meth docutils literal notranslate"><span class="pre">undo()</span></code> method that can roll back actions.</p></li>
<li><p>Simple support for reacting to input events such as mouse and keyboard
activity, making it possible to write simple games.</p></li>
<li><p><code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> 文件可被用来定制海龟绘图屏幕的初始外观。</p></li>
<li><p>The module's docstrings can be replaced by new docstrings that have been
translated into another language.</p></li>
</ul>
<p>(<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1513695">bpo-1513695</a>)</p>
</li>
<li><p>An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter was added to the
<code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlopen()</span></code> function and the
<code class="xref py py-class docutils literal notranslate"><span class="pre">urllib.ftpwrapper</span></code> class constructor, as well as the
<code class="xref py py-func docutils literal notranslate"><span class="pre">urllib2.urlopen()</span></code> function. The parameter specifies a timeout
measured in seconds. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s2">&quot;http://slow.example.com&quot;</span><span class="p">,</span>
<span class="go"> timeout=3)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="w"> </span><span class="c">...</span>
<span class="gr">urllib2.URLError</span>: <span class="n">&lt;urlopen error timed out&gt;</span>
<span class="gp">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>(由 Facundo Batista 添加。)</p>
</li>
<li><p>The Unicode database provided by the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module
has been updated to version 5.1.0. (Updated by
Martin von Löwis; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3811">bpo-3811</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module's <code class="xref py py-func docutils literal notranslate"><span class="pre">formatwarning()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code>
gained an optional <em>line</em> argument that can be used to supply the
line of source code. (Added as part of <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1631171">bpo-1631171</a>, which re-implemented
part of the <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module in C code.)</p>
<p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">catch_warnings()</span></code>, is a context manager
intended for testing purposes that lets you temporarily modify the
warning filters and then restore their original values (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3781">bpo-3781</a>).</p>
</li>
<li><p>The XML-RPC <code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code>
classes can now be prevented from immediately opening and binding to
their socket by passing <code class="docutils literal notranslate"><span class="pre">False</span></code> as the <em>bind_and_activate</em>
constructor parameter. This can be used to modify the instance's
<code class="xref py py-attr docutils literal notranslate"><span class="pre">allow_reuse_address</span></code> attribute before calling the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">server_bind()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">server_activate()</span></code> methods to
open the socket and begin listening for connections.
(Contributed by Peter Parente; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1599845">bpo-1599845</a>.)</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> also has a <code class="xref py py-attr docutils literal notranslate"><span class="pre">_send_traceback_header</span></code>
attribute; if true, the exception and formatted traceback are returned
as HTTP headers &quot;X-Exception&quot; and &quot;X-Traceback&quot;. This feature is
for debugging purposes only and should not be used on production servers
because the tracebacks might reveal passwords or other sensitive
information. (Contributed by Alan McIntyre as part of his
project for Google's Summer of Code 2007.)</p>
</li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> module no longer automatically converts
<a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.time</span></code></a> to the
<code class="xref py py-class docutils literal notranslate"><span class="pre">xmlrpclib.DateTime</span></code> type; the conversion semantics were
not necessarily correct for all applications. Code using
<code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> should convert <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>
instances. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1330538">bpo-1330538</a>) The code can also handle
dates before 1900 (contributed by Ralf Schmitt; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2014">bpo-2014</a>)
and 64-bit integers represented by using <code class="docutils literal notranslate"><span class="pre">&lt;i8&gt;</span></code> in XML-RPC responses
(contributed by Riku Lindblad; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2985">bpo-2985</a>).</p></li>
<li><p>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's <code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code> class now has
<code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">extractall()</span></code> methods that will unpack
a single file or all the files in the archive to the current directory, or
to a specified directory:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">z</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="s1">&#39;python-251.zip&#39;</span><span class="p">)</span>
<span class="c1"># Unpack a single file, writing it relative</span>
<span class="c1"># to the /tmp directory.</span>
<span class="n">z</span><span class="o">.</span><span class="n">extract</span><span class="p">(</span><span class="s1">&#39;Python/sysmodule.c&#39;</span><span class="p">,</span> <span class="s1">&#39;/tmp&#39;</span><span class="p">)</span>
<span class="c1"># Unpack all the files in the archive.</span>
<span class="n">z</span><span class="o">.</span><span class="n">extractall</span><span class="p">()</span>
</pre></div>
</div>
<p>(由 Alan McIntyre 在 <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=467924">bpo-467924</a> 中贡献。)</p>
<p>The <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code> methods can now
take either a filename or a <code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code> object. This is useful when an
archive accidentally contains a duplicated filename.
(Contributed by Graham Horler; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1775025">bpo-1775025</a>.)</p>
<p>Finally, <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> now supports using Unicode filenames
for archived files. (Contributed by Alexey Borzenkov; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1734346">bpo-1734346</a>.)</p>
</li>
</ul>
<section id="the-ast-module">
<h3><a class="reference internal" href="../library/ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> 模块<a class="headerlink" href="#the-ast-module" title="永久链接至标题"></a></h3>
<p>The <a class="reference internal" href="../library/ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module provides an Abstract Syntax Tree
representation of Python code, and Armin Ronacher
contributed a set of helper functions that perform a variety of
common tasks. These will be useful for HTML templating
packages, code analyzers, and similar tools that process
Python code.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code> function takes an expression and returns an AST.
The <code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code> function outputs a representation of a tree, suitable
for debugging:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ast</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;</span>
<span class="s2">d = </span><span class="si">{}</span>
<span class="s2">for i in &#39;abcdefghijklm&#39;:</span>
<span class="s2"> d[i + i] = ord(i) - ord(&#39;a&#39;) + 1</span>
<span class="s2">print d</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
</pre></div>
</div>
<p>输出是一棵深度嵌套的树:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Module</span><span class="p">(</span><span class="n">body</span><span class="o">=</span><span class="p">[</span>
<span class="n">Assign</span><span class="p">(</span><span class="n">targets</span><span class="o">=</span><span class="p">[</span>
<span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">())</span>
<span class="p">],</span> <span class="n">value</span><span class="o">=</span><span class="n">Dict</span><span class="p">(</span><span class="n">keys</span><span class="o">=</span><span class="p">[],</span> <span class="n">values</span><span class="o">=</span><span class="p">[]))</span>
<span class="n">For</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">()),</span>
<span class="nb">iter</span><span class="o">=</span><span class="n">Str</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;abcdefghijklm&#39;</span><span class="p">),</span> <span class="n">body</span><span class="o">=</span><span class="p">[</span>
<span class="n">Assign</span><span class="p">(</span><span class="n">targets</span><span class="o">=</span><span class="p">[</span>
<span class="n">Subscript</span><span class="p">(</span><span class="n">value</span><span class="o">=</span>
<span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span>
<span class="nb">slice</span><span class="o">=</span>
<span class="n">Index</span><span class="p">(</span><span class="n">value</span><span class="o">=</span>
<span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">op</span><span class="o">=</span><span class="n">Add</span><span class="p">(),</span>
<span class="n">right</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()))),</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">())</span>
<span class="p">],</span> <span class="n">value</span><span class="o">=</span>
<span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span>
<span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span>
<span class="n">Call</span><span class="p">(</span><span class="n">func</span><span class="o">=</span>
<span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;ord&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span>
<span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">())</span>
<span class="p">],</span> <span class="n">keywords</span><span class="o">=</span><span class="p">[],</span> <span class="n">starargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="kc">None</span><span class="p">),</span>
<span class="n">op</span><span class="o">=</span><span class="n">Sub</span><span class="p">(),</span> <span class="n">right</span><span class="o">=</span><span class="n">Call</span><span class="p">(</span><span class="n">func</span><span class="o">=</span>
<span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;ord&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span>
<span class="n">Str</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="p">],</span> <span class="n">keywords</span><span class="o">=</span><span class="p">[],</span> <span class="n">starargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="kc">None</span><span class="p">)),</span>
<span class="n">op</span><span class="o">=</span><span class="n">Add</span><span class="p">(),</span> <span class="n">right</span><span class="o">=</span><span class="n">Num</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="p">],</span> <span class="n">orelse</span><span class="o">=</span><span class="p">[])</span>
<span class="n">Print</span><span class="p">(</span><span class="n">dest</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">values</span><span class="o">=</span><span class="p">[</span>
<span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">())</span>
<span class="p">],</span> <span class="n">nl</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="p">])</span>
</pre></div>
</div>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">literal_eval()</span></code> method takes a string or an AST
representing a literal expression, parses and evaluates it, and
returns the resulting value. A literal expression is a Python
expression containing only strings, numbers, dictionaries,
etc. but no statements or function calls. If you need to
evaluate an expression but cannot accept the security risk of using an
<a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> call, <code class="xref py py-func docutils literal notranslate"><span class="pre">literal_eval()</span></code> will handle it safely:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">literal</span> <span class="o">=</span> <span class="s1">&#39;(&quot;a&quot;, &quot;b&quot;, {2:4, 3:8, 1:2})&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">literal_eval</span><span class="p">(</span><span class="n">literal</span><span class="p">)</span>
<span class="go">(&#39;a&#39;, &#39;b&#39;, {1: 2, 2: 4, 3: 8})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">literal_eval</span><span class="p">(</span><span class="s1">&#39;&quot;a&quot; + &quot;b&quot;&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="w"> </span><span class="c">...</span>
<span class="gr">ValueError</span>: <span class="n">malformed string</span>
</pre></div>
</div>
<p>The module also includes <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeVisitor</span></code> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">NodeTransformer</span></code> classes for traversing and modifying an AST,
and functions for common transformations such as changing line
numbers.</p>
</section>
<section id="the-future-builtins-module">
<h3><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> 模块<a class="headerlink" href="#the-future-builtins-module" title="永久链接至标题"></a></h3>
<p>Python 3.0 makes many changes to the repertoire of built-in
functions, and most of the changes can't be introduced in the Python
2.x series because they would break compatibility.
The <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module provides versions
of these built-in functions that can be imported when writing
3.0-compatible code.</p>
<p>目前此模块中的函数包括:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">ascii(obj)</span></code>: equivalent to <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>. In Python 3.0,
<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> will return a Unicode string, while <a class="reference internal" href="../library/functions.html#ascii" title="ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a> will
return a pure ASCII bytestring.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">filter(predicate,</span> <span class="pre">iterable)</span></code>,
<code class="docutils literal notranslate"><span class="pre">map(func,</span> <span class="pre">iterable1,</span> <span class="pre">...)</span></code>: the 3.0 versions
return iterators, unlike the 2.x builtins which return lists.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">hex(value)</span></code>, <code class="docutils literal notranslate"><span class="pre">oct(value)</span></code>: instead of calling the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__hex__()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__oct__()</span></code> methods, these versions will
call the <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method and convert the result to hexadecimal
or octal. <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> will use the new <code class="docutils literal notranslate"><span class="pre">0o</span></code> notation for its
result.</p></li>
</ul>
</section>
<section id="the-json-module-javascript-object-notation">
<h3><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> 模块: JavaScript Object Notation<a class="headerlink" href="#the-json-module-javascript-object-notation" title="永久链接至标题"></a></h3>
<p>The new <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> module supports the encoding and decoding of Python types in
JSON (Javascript Object Notation). JSON is a lightweight interchange format
often used in web applications. For more information about JSON, see
<a class="reference external" href="http://www.json.org">http://www.json.org</a>.</p>
<p><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> comes with support for decoding and encoding most built-in Python
types. The following example encodes and decodes a dictionary:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;spam&quot;</span><span class="p">:</span> <span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="s2">&quot;parrot&quot;</span><span class="p">:</span> <span class="mi">42</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">in_json</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="c1"># Encode the data</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">in_json</span>
<span class="go">&#39;{&quot;parrot&quot;: 42, &quot;spam&quot;: &quot;foo&quot;}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">in_json</span><span class="p">)</span> <span class="c1"># Decode into a Python object</span>
<span class="go">{&quot;spam&quot;: &quot;foo&quot;, &quot;parrot&quot;: 42}</span>
</pre></div>
</div>
<p>It's also possible to write your own decoders and encoders to support
more types. Pretty-printing of the JSON strings is also supported.</p>
<p><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> (originally called simplejson) was written by Bob
Ippolito.</p>
</section>
<section id="the-plistlib-module-a-property-list-parser">
<h3><a class="reference internal" href="../library/plistlib.html#module-plistlib" title="plistlib: Generate and parse Mac OS X plist files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code></a> 模块:属性列表解析器<a class="headerlink" href="#the-plistlib-module-a-property-list-parser" title="永久链接至标题"></a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">.plist</span></code> format is commonly used on Mac OS X to
store basic data types (numbers, strings, lists,
and dictionaries) by serializing them into an XML-based format.
It resembles the XML-RPC serialization of data types.</p>
<p>Despite being primarily used on Mac OS X, the format
has nothing Mac-specific about it and the Python implementation works
on any platform that Python supports, so the <a class="reference internal" href="../library/plistlib.html#module-plistlib" title="plistlib: Generate and parse Mac OS X plist files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code></a> module
has been promoted to the standard library.</p>
<p>此模块的用法很简单:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">plistlib</span>
<span class="kn">import</span> <span class="nn">datetime</span>
<span class="c1"># Create data structure</span>
<span class="n">data_struct</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">lastAccessed</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(),</span>
<span class="n">version</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
<span class="n">categories</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;Personal&#39;</span><span class="p">,</span><span class="s1">&#39;Shared&#39;</span><span class="p">,</span><span class="s1">&#39;Private&#39;</span><span class="p">))</span>
<span class="c1"># Create string containing XML.</span>
<span class="n">plist_str</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">writePlistToString</span><span class="p">(</span><span class="n">data_struct</span><span class="p">)</span>
<span class="n">new_struct</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">readPlistFromString</span><span class="p">(</span><span class="n">plist_str</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">data_struct</span>
<span class="nb">print</span> <span class="n">new_struct</span>
<span class="c1"># Write data structure to a file and read it back.</span>
<span class="n">plistlib</span><span class="o">.</span><span class="n">writePlist</span><span class="p">(</span><span class="n">data_struct</span><span class="p">,</span> <span class="s1">&#39;/tmp/customizations.plist&#39;</span><span class="p">)</span>
<span class="n">new_struct</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">readPlist</span><span class="p">(</span><span class="s1">&#39;/tmp/customizations.plist&#39;</span><span class="p">)</span>
<span class="c1"># read/writePlist accepts file-like objects as well as paths.</span>
<span class="n">plistlib</span><span class="o">.</span><span class="n">writePlist</span><span class="p">(</span><span class="n">data_struct</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
</pre></div>
</div>
</section>
<section id="ctypes-enhancements">
<h3>ctypes Enhancements<a class="headerlink" href="#ctypes-enhancements" title="永久链接至标题"></a></h3>
<p>Thomas Heller continued to maintain and enhance the
<a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module.</p>
<p><a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> now supports a <code class="xref py py-class docutils literal notranslate"><span class="pre">c_bool</span></code> datatype
that represents the C99 <code class="docutils literal notranslate"><span class="pre">bool</span></code> type. (Contributed by David Remahl;
<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1649190">bpo-1649190</a>.)</p>
<p>The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> string, buffer and array types have improved
support for extended slicing syntax,
where various combinations of <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code> are supplied.
(Implemented by Thomas Wouters.)</p>
<p>All <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> data types now support
<code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer_copy()</span></code>
methods that create a ctypes instance based on a
provided buffer object. <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer_copy()</span></code> copies
the contents of the object,
while <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer()</span></code> will share the same memory area.</p>
<p>A new calling convention tells <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> to clear the <code class="docutils literal notranslate"><span class="pre">errno</span></code> or
Win32 LastError variables at the outset of each wrapped call.
(Implemented by Thomas Heller; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1798">bpo-1798</a>.)</p>
<p>You can now retrieve the Unix <code class="docutils literal notranslate"><span class="pre">errno</span></code> variable after a function
call. When creating a wrapped function, you can supply
<code class="docutils literal notranslate"><span class="pre">use_errno=True</span></code> as a keyword parameter to the <code class="xref py py-func docutils literal notranslate"><span class="pre">DLL()</span></code> function
and then call the module-level methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_errno()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_errno()</span></code> to set and retrieve the error value.</p>
<p>The Win32 LastError variable is similarly supported by
the <code class="xref py py-func docutils literal notranslate"><span class="pre">DLL()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">OleDLL()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">WinDLL()</span></code> functions.
You supply <code class="docutils literal notranslate"><span class="pre">use_last_error=True</span></code> as a keyword parameter
and then call the module-level methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_last_error()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_last_error()</span></code>.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">byref()</span></code> function, used to retrieve a pointer to a ctypes
instance, now has an optional <em>offset</em> parameter that is a byte
count that will be added to the returned pointer.</p>
</section>
<section id="improved-ssl-support">
<h3>改进的 SSL 支持<a class="headerlink" href="#improved-ssl-support" title="永久链接至标题"></a></h3>
<p>Bill Janssen made extensive improvements to Python 2.6's support for
the Secure Sockets Layer by adding a new module, <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a>, that's
built atop the <a class="reference external" href="https://www.openssl.org/">OpenSSL</a> library.
This new module provides more control over the protocol negotiated,
the X.509 certificates used, and has better support for writing SSL
servers (as opposed to clients) in Python. The existing SSL support
in the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module hasn't been removed and continues to work,
though it will be removed in Python 3.0.</p>
<p>To use the new module, you must first create a TCP connection in the
usual way and then pass it to the <a class="reference internal" href="../library/ssl.html#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.wrap_socket()</span></code></a> function.
It's possible to specify whether a certificate is required, and to
obtain certificate info by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">getpeercert()</span></code> method.</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> 模块的文档。</p>
</div>
</section>
</section>
<section id="deprecations-and-removals">
<h2>弃用和移除<a class="headerlink" href="#deprecations-and-removals" title="永久链接至标题"></a></h2>
<ul>
<li><p>String exceptions have been removed. Attempting to use them raises a
<a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p></li>
<li><p>Changes to the <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a> interface
as dictated by <span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0352"><strong>PEP 352</strong></a> continue to be made. For 2.6,
the <code class="xref py py-attr docutils literal notranslate"><span class="pre">message</span></code> attribute is being deprecated in favor of the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code> attribute.</p></li>
<li><p>(3.0-warning mode) Python 3.0 will feature a reorganized standard
library that will drop many outdated modules and rename others.
Python 2.6 running in 3.0-warning mode will warn about these modules
when they are imported.</p>
<p>The list of deprecated modules is:
<code class="xref py py-mod docutils literal notranslate"><span class="pre">audiodev</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">bgenlocations</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">buildtools</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">bundlebuilder</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Canvas</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">dircache</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">fpformat</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">imageop</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">imgfile</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">mhlib</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pure</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">statvfs</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">test.testall</span></code>, and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">toaiff</span></code>.</p>
</li>
<li><p><code class="xref py py-mod docutils literal notranslate"><span class="pre">gopherlib</span></code> 模块已被移除。</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">MimeWriter</span></code> module and <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimify</span></code> module
have been deprecated; use the <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a>
package instead.</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code> module has been deprecated; use the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module
instead.</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">posixfile</span></code> module has been deprecated; <a class="reference internal" href="../library/fcntl.html#fcntl.lockf" title="fcntl.lockf"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.lockf()</span></code></a>
provides better locking.</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code> module has been deprecated; use the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a>
module.</p></li>
<li><p><code class="xref py py-mod docutils literal notranslate"><span class="pre">rgbimg</span></code> 模块已被移除。</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code> module has been deprecated; it's better to
use the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> types.</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code> module has been deprecated; use the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module
instead.</p></li>
</ul>
</section>
<section id="build-and-c-api-changes">
<h2>构建和 C API 的改变<a class="headerlink" href="#build-and-c-api-changes" title="永久链接至标题"></a></h2>
<p>针对 Python 构建过程和 C API 的改变包括:</p>
<ul>
<li><p>Python now must be compiled with C89 compilers (after 19
years!). This means that the Python source tree has dropped its
own implementations of <code class="xref c c-func docutils literal notranslate"><span class="pre">memmove()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">strerror()</span></code>, which
are in the C89 standard library.</p></li>
<li><p>Python 2.6 can be built with Microsoft Visual Studio 2008 (version
9.0), and this is the new default compiler. See the
<code class="file docutils literal notranslate"><span class="pre">PCbuild</span></code> directory for the build files. (Implemented by
Christian Heimes.)</p></li>
<li><p>On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
The <strong class="program">configure</strong> script
can take a <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-universal-archs=[32-bit|64-bit|all]</span></code>
switch, controlling whether the binaries are built for 32-bit
architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
(Contributed by Ronald Oussoren.)</p></li>
<li><p>The BerkeleyDB module now has a C API object, available as
<code class="docutils literal notranslate"><span class="pre">bsddb.db.api</span></code>. This object can be used by other C extensions
that wish to use the <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code> module for their own purposes.
(Contributed by Duncan Grisby.)</p></li>
<li><p>The new buffer interface, previously described in
<a class="reference external" href="#pep-3118-revised-buffer-protocol">the PEP 3118 section</a>,
adds <a class="reference internal" href="../c-api/buffer.html#c.PyObject_GetBuffer" title="PyObject_GetBuffer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetBuffer()</span></code></a> and <a class="reference internal" href="../c-api/buffer.html#c.PyBuffer_Release" title="PyBuffer_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_Release()</span></code></a>,
as well as a few other functions.</p></li>
<li><p>Python's use of the C stdio library is now thread-safe, or at least
as thread-safe as the underlying library is. A long-standing potential
bug occurred if one thread closed a file object while another thread
was reading from or writing to the object. In 2.6 file objects
have a reference count, manipulated by the
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code>
functions. File objects can't be closed unless the reference count
is zero. <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code> should be called while the GIL
is still held, before carrying out an I/O operation using the
<code class="docutils literal notranslate"><span class="pre">FILE</span> <span class="pre">*</span></code> pointer, and <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code> should be called
immediately after the GIL is re-acquired.
(Contributed by Antoine Pitrou and Gregory P. Smith.)</p></li>
<li><p>Importing modules simultaneously in two different threads no longer
deadlocks; it will now raise an <a class="reference internal" href="../library/exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>. A new API
function, <a class="reference internal" href="../c-api/import.html#c.PyImport_ImportModuleNoBlock" title="PyImport_ImportModuleNoBlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModuleNoBlock()</span></code></a>, will look for a
module in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> first, then try to import it after
acquiring an import lock. If the import lock is held by another
thread, an <a class="reference internal" href="../library/exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> is raised.
(Contributed by Christian Heimes.)</p></li>
<li><p>Several functions return information about the platform's
floating-point support. <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetMax" title="PyFloat_GetMax"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetMax()</span></code></a> returns
the maximum representable floating point value,
and <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetMin" title="PyFloat_GetMin"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetMin()</span></code></a> returns the minimum
positive value. <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetInfo" title="PyFloat_GetInfo"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetInfo()</span></code></a> returns an object
containing more information from the <code class="file docutils literal notranslate"><span class="pre">float.h</span></code> file, such as
<code class="docutils literal notranslate"><span class="pre">&quot;mant_dig&quot;</span></code> (number of digits in the mantissa), <code class="docutils literal notranslate"><span class="pre">&quot;epsilon&quot;</span></code>
(smallest difference between 1.0 and the next largest value
representable), and several others.
(Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1534">bpo-1534</a>.)</p></li>
<li><p>C functions and methods that use
<a class="reference internal" href="../c-api/complex.html#c.PyComplex_AsCComplex" title="PyComplex_AsCComplex"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyComplex_AsCComplex()</span></code></a> will now accept arguments that
have a <a class="reference internal" href="../reference/datamodel.html#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a> method. In particular, the functions in the
<a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module will now accept objects with this method.
This is a backport of a Python 3.0 change.
(Contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1675423">bpo-1675423</a>.)</p></li>
<li><p>Python's C API now includes two functions for case-insensitive string
comparisons, <code class="docutils literal notranslate"><span class="pre">PyOS_stricmp(char*,</span> <span class="pre">char*)</span></code>
and <code class="docutils literal notranslate"><span class="pre">PyOS_strnicmp(char*,</span> <span class="pre">char*,</span> <span class="pre">Py_ssize_t)</span></code>.
(Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1635">bpo-1635</a>.)</p></li>
<li><p>Many C extensions define their own little macro for adding
integers and strings to the module's dictionary in the
<code class="docutils literal notranslate"><span class="pre">init*</span></code> function. Python 2.6 finally defines standard macros
for adding values to a module, <a class="reference internal" href="../c-api/module.html#c.PyModule_AddStringMacro" title="PyModule_AddStringMacro"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyModule_AddStringMacro</span></code></a>
and <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyModule_AddIntMacro()</span></code>. (Contributed by
Christian Heimes.)</p></li>
<li><p>Some macros were renamed in both 3.0 and 2.6 to make it clearer that
they are macros,
not functions. <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Size()</span></code> became <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_SIZE()</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Type()</span></code> became <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TYPE()</span></code>, and
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Refcnt()</span></code> became <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_REFCNT()</span></code>.
The mixed-case macros are still available
in Python 2.6 for backward compatibility.
(<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1629">bpo-1629</a>)</p></li>
<li><p>Distutils now places C extensions it builds in a
different directory when running on a debug version of Python.
(Contributed by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1530959">bpo-1530959</a>.)</p></li>
<li><p>Several basic data types, such as integers and strings, maintain
internal free lists of objects that can be re-used. The data
structures for these free lists now follow a naming convention: the
variable is always named <code class="docutils literal notranslate"><span class="pre">free_list</span></code>, the counter is always named
<code class="docutils literal notranslate"><span class="pre">numfree</span></code>, and a macro <code class="docutils literal notranslate"><span class="pre">Py&lt;typename&gt;_MAXFREELIST</span></code> is
always defined.</p></li>
<li><p>A new Makefile target, &quot;make patchcheck&quot;, prepares the Python source tree
for making a patch: it fixes trailing whitespace in all modified
<code class="docutils literal notranslate"><span class="pre">.py</span></code> files, checks whether the documentation has been changed,
and reports whether the <code class="file docutils literal notranslate"><span class="pre">Misc/ACKS</span></code> and <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> files
have been updated.
(Contributed by Brett Cannon.)</p>
<p>Another new target, &quot;make profile-opt&quot;, compiles a Python binary
using GCC's profile-guided optimization. It compiles Python with
profiling enabled, runs the test suite to obtain a set of profiling
results, and then compiles using these results for optimization.
(Contributed by Gregory P. Smith.)</p>
</li>
</ul>
<section id="port-specific-changes-windows">
<h3>特定于 Windows 的更改:<a class="headerlink" href="#port-specific-changes-windows" title="永久链接至标题"></a></h3>
<ul>
<li><p>The support for Windows 95, 98, ME and NT4 has been dropped.
Python 2.6 requires at least Windows 2000 SP4.</p></li>
<li><p>The new default compiler on Windows is Visual Studio 2008 (version
9.0). The build directories for Visual Studio 2003 (version 7.1) and
2005 (version 8.0) were moved into the PC/ directory. The new
<code class="file docutils literal notranslate"><span class="pre">PCbuild</span></code> directory supports cross compilation for X64, debug
builds and Profile Guided Optimization (PGO). PGO builds are roughly
10% faster than normal builds. (Contributed by Christian Heimes
with help from Amaury Forgeot d'Arc and Martin von Löwis.)</p></li>
<li><p>The <a class="reference internal" href="../library/msvcrt.html#module-msvcrt" title="msvcrt: Miscellaneous useful routines from the MS VC++ runtime. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msvcrt</span></code></a> module now supports
both the normal and wide char variants of the console I/O
API. The <code class="xref py py-func docutils literal notranslate"><span class="pre">getwch()</span></code> function reads a keypress and returns a Unicode
value, as does the <code class="xref py py-func docutils literal notranslate"><span class="pre">getwche()</span></code> function. The <code class="xref py py-func docutils literal notranslate"><span class="pre">putwch()</span></code> function
takes a Unicode character and writes it to the console.
(Contributed by Christian Heimes.)</p></li>
<li><p><a class="reference internal" href="../library/os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a> will now expand environment variables in
the form &quot;%var%&quot;, and &quot;~user&quot; will be expanded into the user's home
directory path. (Contributed by Josiah Carlson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=957650">bpo-957650</a>.)</p></li>
<li><p>The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module's socket objects now have an
<code class="xref py py-meth docutils literal notranslate"><span class="pre">ioctl()</span></code> method that provides a limited interface to the
<code class="xref c c-func docutils literal notranslate"><span class="pre">WSAIoctl()</span></code> system interface.</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code> module now has a function,
<code class="xref py py-func docutils literal notranslate"><span class="pre">ExpandEnvironmentStrings()</span></code>,
that expands environment variable references such as <code class="docutils literal notranslate"><span class="pre">%NAME%</span></code>
in an input string. The handle objects provided by this
module now support the context protocol, so they can be used
in <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. (Contributed by Christian Heimes.)</p>
<p><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code> also has better support for x64 systems,
exposing the <code class="xref py py-func docutils literal notranslate"><span class="pre">DisableReflectionKey()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">EnableReflectionKey()</span></code>,
and <code class="xref py py-func docutils literal notranslate"><span class="pre">QueryReflectionKey()</span></code> functions, which enable and disable
registry reflection for 32-bit processes running on 64-bit systems.
(<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1753245">bpo-1753245</a>)</p>
</li>
<li><p>The <a class="reference internal" href="../library/msilib.html#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> module's <code class="xref py py-class docutils literal notranslate"><span class="pre">Record</span></code> object
gained <code class="xref py py-meth docutils literal notranslate"><span class="pre">GetInteger()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">GetString()</span></code> methods that
return field values as an integer or a string.
(Contributed by Floris Bruynooghe; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2125">bpo-2125</a>.)</p></li>
</ul>
</section>
<section id="port-specific-changes-mac-os-x">
<h3>特定于 Mac OS X 的更改:<a class="headerlink" href="#port-specific-changes-mac-os-x" title="永久链接至标题"></a></h3>
<ul class="simple">
<li><p>现在在编译Python的框架版本时可以为 <strong class="program">configure</strong> 脚本添加 <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-framework-name=</span></code> 选项来指定要使用的框架名称。</p></li>
<li><p><code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code> 模块已被删除。这反过来要求删除 <code class="xref py py-func docutils literal notranslate"><span class="pre">macostools.touched()</span></code> 函数,因为它依赖于 <code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code> 模块。 (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1490190">bpo-1490190</a>)</p></li>
<li><p>许多其他 Mac OS 模块已弃用并将在 Python 3.0 中被删除: <code class="xref py py-mod docutils literal notranslate"><span class="pre">_builtinSuites</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">applesingle</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">appletrawmain</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">appletrunner</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">argvemulator</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Audio_mac</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">autoGIL</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">cfmfile</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">CodeWarrior</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">ColorPicker</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">EasyDialogs</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Explorer</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Finder</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">findertools</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">icglue</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">icopen</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">macerrors</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">MacOS</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">macostools</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">macresource</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">MiniAEFrame</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Nav</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Netscape</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">OSATerminology</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">pimp</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">PixMapWrapper</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">StdSuites</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">SystemEvents</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Terminal</span></code><code class="xref py py-mod docutils literal notranslate"><span class="pre">terminalcommand</span></code></p></li>
</ul>
</section>
<section id="port-specific-changes-irix">
<h3>特定于 IRIX 的更改:<a class="headerlink" href="#port-specific-changes-irix" title="永久链接至标题"></a></h3>
<p>许多旧的 IRIX 专用模块已被弃用并将在Python 3.0中删除: <code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code><code class="xref py py-mod docutils literal notranslate"><span class="pre">AL</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">cd</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">cddb</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">cdplayer</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">CL</span></code><code class="xref py py-mod docutils literal notranslate"><span class="pre">cl</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">DEVICE</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">ERRNO</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">FILE</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">FL</span></code><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">flp</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">fm</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">GET</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">GLWS</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">GL</span></code><code class="xref py py-mod docutils literal notranslate"><span class="pre">gl</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">IN</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">IOCTL</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">jpeg</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">panelparser</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">readcd</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">SV</span></code><code class="xref py py-mod docutils literal notranslate"><span class="pre">sv</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">torgb</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">videoreader</span></code>, 和 <code class="xref py py-mod docutils literal notranslate"><span class="pre">WAIT</span></code>.</p>
</section>
</section>
<section id="porting-to-python-2-6">
<h2>移植到Python 2.6<a class="headerlink" href="#porting-to-python-2-6" title="永久链接至标题"></a></h2>
<p>本节列出了先前描述的改变以及可能需要修改你的代码的其他问题修正:</p>
<ul>
<li><p>预期为不可哈希的类应当在其定义中设置 <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> 来指明这一点。</p></li>
<li><p>String exceptions have been removed. Attempting to use them raises a
<a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p></li>
<li><p>The <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method of <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">collections.deque</span></code></a>
now clears any existing contents of the deque
before adding elements from the iterable. This change makes the
behavior match <code class="docutils literal notranslate"><span class="pre">list.__init__()</span></code>.</p></li>
<li><p><a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__init__()</span></code></a> previously accepted arbitrary arguments and
keyword arguments, ignoring them. In Python 2.6, this is no longer
allowed and will result in a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>. This will affect
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> methods that end up calling the corresponding
method on <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> (perhaps through using <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>).
See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1683368">bpo-1683368</a> for discussion.</p></li>
<li><p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> constructor now accepts leading and trailing
whitespace when passed a string. Previously it would raise an
<code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidOperation</span></code> exception. On the other hand, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">create_decimal()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> objects now
explicitly disallows extra whitespace, raising a
<code class="xref py py-exc docutils literal notranslate"><span class="pre">ConversionSyntax</span></code> exception.</p></li>
<li><p>Due to an implementation accident, if you passed a file path to
the built-in <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> function, it would actually import
the specified file. This was never intended to work, however, and
the implementation now explicitly checks for this case and raises
an <a class="reference internal" href="../library/exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.</p></li>
<li><p>C API: the <a class="reference internal" href="../c-api/import.html#c.PyImport_Import" title="PyImport_Import"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_Import()</span></code></a> and <a class="reference internal" href="../c-api/import.html#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a>
functions now default to absolute imports, not relative imports.
This will affect C extensions that import other modules.</p></li>
<li><p>C API: extension data types that shouldn't be hashable
should define their <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> slot to
<a class="reference internal" href="../c-api/object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a>.</p></li>
<li><p>The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module exception <a class="reference internal" href="../library/socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> now inherits
from <a class="reference internal" href="../library/exceptions.html#IOError" title="IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>. Previously it wasn't a subclass of
<code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code> but now it is, through <a class="reference internal" href="../library/exceptions.html#IOError" title="IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.
(Implemented by Gregory P. Smith; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1706815">bpo-1706815</a>.)</p></li>
<li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> module no longer automatically converts
<a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.time</span></code></a> to the
<code class="xref py py-class docutils literal notranslate"><span class="pre">xmlrpclib.DateTime</span></code> type; the conversion semantics were
not necessarily correct for all applications. Code using
<code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> should convert <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>
instances. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1330538">bpo-1330538</a>)</p></li>
<li><p>(3.0-warning mode) The <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a> class now warns
when accessed using slicing or index access; having
<a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a> behave like a tuple is being phased out.</p></li>
<li><p>(3.0-warning mode) inequality comparisons between two dictionaries
or two objects that don't implement comparison methods are reported
as warnings. <code class="docutils literal notranslate"><span class="pre">dict1</span> <span class="pre">==</span> <span class="pre">dict2</span></code> still works, but <code class="docutils literal notranslate"><span class="pre">dict1</span> <span class="pre">&lt;</span> <span class="pre">dict2</span></code>
is being phased out.</p>
<p>Comparisons between cells, which are an implementation detail of Python's
scoping rules, also cause warnings because such comparisons are forbidden
entirely in 3.0.</p>
</li>
</ul>
</section>
<section id="acknowledgements">
<span id="acks"></span><h2>致谢<a class="headerlink" href="#acknowledgements" title="永久链接至标题"></a></h2>
<p>作者感谢以下人员对本文各种草稿给予的建议,更正和协助: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, Antoine Pitrou, Brian Warner.</p>
</section>
</section>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">目录</a></h3>
<ul>
<li><a class="reference internal" href="#">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">开发过程的变化</a><ul>
<li><a class="reference internal" href="#new-issue-tracker-roundup">新问题追踪:简述</a></li>
<li><a class="reference internal" href="#new-documentation-format-restructuredtext-using-sphinx">新的文档格式:使用 Sphinx 的 reStructuredText</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: &quot;with&quot; 语句</a><ul>
<li><a class="reference internal" href="#writing-context-managers">编写上下文管理器</a></li>
<li><a class="reference internal" href="#the-contextlib-module">contextlib 模块</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: 从主模块显式相对导入</a></li>
<li><a class="reference internal" href="#pep-370-per-user-site-packages-directory">PEP 370: 分用户的 site-packages 目录</a></li>
<li><a class="reference internal" href="#pep-371-the-multiprocessing-package">PEP 371: 多任务处理包</a></li>
<li><a class="reference internal" href="#pep-3101-advanced-string-formatting">PEP 3101: 高级字符串格式</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> 改为函数</a></li>
<li><a class="reference internal" href="#pep-3110-exception-handling-changes">PEP 3110: 异常处理的变更</a></li>
<li><a class="reference internal" href="#pep-3112-byte-literals">PEP 3112: 字节字面值</a></li>
<li><a class="reference internal" href="#pep-3116-new-i-o-library">PEP 3116: 新 I/O 库</a></li>
<li><a class="reference internal" href="#pep-3118-revised-buffer-protocol">PEP 3118: 修改缓冲区协议</a></li>
<li><a class="reference internal" href="#pep-3119-abstract-base-classes">PEP 3119: 抽象基类</a></li>
<li><a class="reference internal" href="#pep-3127-integer-literal-support-and-syntax">PEP 3127: 整型文字支持和语法</a></li>
<li><a class="reference internal" href="#pep-3129-class-decorators">PEP 3129: 类装饰器</a></li>
<li><a class="reference internal" href="#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: 数字的类型层级结构</a><ul>
<li><a class="reference internal" href="#the-fractions-module"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code> 模块</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-language-changes">其他语言特性修改</a><ul>
<li><a class="reference internal" href="#optimizations">性能优化</a></li>
<li><a class="reference internal" href="#interpreter-changes">解释器改动</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-and-improved-modules">新增和改进的模块</a><ul>
<li><a class="reference internal" href="#the-ast-module"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code> 模块</a></li>
<li><a class="reference internal" href="#the-future-builtins-module"><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> 模块</a></li>
<li><a class="reference internal" href="#the-json-module-javascript-object-notation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code> 模块: JavaScript Object Notation</a></li>
<li><a class="reference internal" href="#the-plistlib-module-a-property-list-parser"><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code> 模块:属性列表解析器</a></li>
<li><a class="reference internal" href="#ctypes-enhancements">ctypes Enhancements</a></li>
<li><a class="reference internal" href="#improved-ssl-support">改进的 SSL 支持</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deprecations-and-removals">弃用和移除</a></li>
<li><a class="reference internal" href="#build-and-c-api-changes">构建和 C API 的改变</a><ul>
<li><a class="reference internal" href="#port-specific-changes-windows">特定于 Windows 的更改:</a></li>
<li><a class="reference internal" href="#port-specific-changes-mac-os-x">特定于 Mac OS X 的更改:</a></li>
<li><a class="reference internal" href="#port-specific-changes-irix">特定于 IRIX 的更改:</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-6">移植到Python 2.6</a></li>
<li><a class="reference internal" href="#acknowledgements">致谢</a></li>
</ul>
</li>
</ul>
<h4>上一个主题</h4>
<p class="topless"><a href="2.7.html"
title="上一章">Python 2.7 有什么新变化</a></p>
<h4>下一个主题</h4>
<p class="topless"><a href="2.5.html"
title="下一章">Python 2.5 有什么新变化</a></p>
<div role="note" aria-label="source link">
<h3>本页</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">报告 Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.8/Doc/whatsnew/2.6.rst"
rel="nofollow">显示源代码
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>导航</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="总目录"
>索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模块索引"
>模块</a> |</li>
<li class="right" >
<a href="2.5.html" title="Python 2.5 有什么新变化"
>下一页</a> |</li>
<li class="right" >
<a href="2.7.html" title="Python 2.7 有什么新变化"
>上一页</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.8.20 Documentation</a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python的新变化</a> &#187;</li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜索" aria-label="快速搜索" type="text" name="q" />
<input type="submit" value="转向" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">版权所有</a> 2001-2024, Python Software Foundation.
<br />
This page is licensed under the Python Software Foundation License Version 2.
<br />
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
<br />
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
<br />
最后更新于 12月 09, 2024.
<a href="https://docs.python.org/3/bugs.html">Found a bug</a>?
<br />
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
</div>
</body>
</html>