“Python/docs/3.9/whatsnew/2.4”的版本间差异

来自菜鸟教程
Python/docs/3.9/whatsnew/2.4
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:Python 2.4 的新特性 — Python 文档}}
 
<div id="what-s-new-in-python-2-4" class="section">
 
<div id="what-s-new-in-python-2-4" class="section">
  
= What's New in Python 2.4 =
+
= Python 2.4 中的新功能 =
  
; Author
+
; 作者
: A.M. Kuchling
+
: 是 库克林
  
This article explains the new features in Python 2.4.1, released on March 30,
+
本文介绍了 2005 年 3 月 30 日发布的 Python 2.4.1 中的新功能。
2005.
 
  
Python 2.4 is a medium-sized release. It doesn't introduce as many changes as
+
Python 2.4 是一个中等规模的版本。 它没有像激进的 Python 2.2 那样引入那么多的变化,但引入了比保守的 2.3 版本更多的特性。 最重要的新语言特性是函数装饰器和生成器表达式; 大多数其他更改都针对标准库。
the radical Python 2.2, but introduces more features than the conservative 2.3
 
release. The most significant new language features are function decorators and
 
generator expressions; most other changes are to the standard library.
 
  
According to the CVS change logs, there were 481 patches applied and 502 bugs
+
根据 CVS 更改日志,在 Python 2.3 2.4 之间应用了 481 个补丁并修复了 502 个错误。 这两个数字都可能被低估。
fixed between Python 2.3 and 2.4. Both figures are likely to be underestimates.
 
  
This article doesn't attempt to provide a complete specification of every single
+
本文并不试图提供每个新功能的完整规范,而是提供对每个功能的简要介绍。 有关完整的详细信息,您应该参考 Python 2.4 的文档,例如 Python 库参考和 Python 参考手册。 通常,您会被称为 PEP 以获得特定的新功能,以解释实现和设计原理。
new feature, but instead provides a brief introduction to each feature. For
 
full details, you should refer to the documentation for Python 2.4, such as the
 
Python Library Reference and the Python Reference Manual. Often you will be
 
referred to the PEP for a particular new feature for explanations of the
 
implementation and design rationale.
 
  
 
<div id="pep-218-built-in-set-objects" class="section">
 
<div id="pep-218-built-in-set-objects" class="section">
  
== PEP 218: Built-In Set Objects ==
+
== PEP 218:内置集合对象 ==
  
Python 2.3 introduced the <code>sets</code> module. C implementations of set data
+
Python 2.3 引入了 <code>sets</code> 模块。 集合数据类型的 C 实现现在已作为两个新的内置类型添加到 Python 核心中,<code>set(iterable)</code> <code>frozenset(iterable)</code>。 它们为成员测试、从序列中消除重复项以及诸如并集、交集、差异和对称差异之类的数学运算提供高速运算。
types have now been added to the Python core as two new built-in types,
 
<code>set(iterable)</code> and <code>frozenset(iterable)</code>. They provide high speed
 
operations for membership testing, for eliminating duplicates from sequences,
 
and for mathematical operations like unions, intersections, differences, and
 
symmetric differences.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第39行: 第25行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; a = set('abracadabra')              # form a set from a string
+
<syntaxhighlight lang="python3">>>> a = set('abracadabra')              # form a set from a string
&gt;&gt;&gt; 'z' in a                            # fast membership testing
+
>>> 'z' in a                            # fast membership testing
 
False
 
False
&gt;&gt;&gt; a                                  # unique letters in a
+
>>> a                                  # unique letters in a
 
set(['a', 'r', 'b', 'c', 'd'])
 
set(['a', 'r', 'b', 'c', 'd'])
&gt;&gt;&gt; ''.join(a)                          # convert back into a string
+
>>> ''.join(a)                          # convert back into a string
 
'arbcd'
 
'arbcd'
  
&gt;&gt;&gt; b = set('alacazam')                # form a second set
+
>>> b = set('alacazam')                # form a second set
&gt;&gt;&gt; a - b                              # letters in a but not in b
+
>>> a - b                              # letters in a but not in b
 
set(['r', 'd', 'b'])
 
set(['r', 'd', 'b'])
&gt;&gt;&gt; a | b                              # letters in either a or b
+
>>> a | b                              # letters in either a or b
 
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
 
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
&gt;&gt;&gt; a &amp; b                              # letters in both a and b
+
>>> a & b                              # letters in both a and b
 
set(['a', 'c'])
 
set(['a', 'c'])
&gt;&gt;&gt; a ^ b                              # letters in a or b but not both
+
>>> a ^ b                              # letters in a or b but not both
 
set(['r', 'd', 'b', 'm', 'z', 'l'])
 
set(['r', 'd', 'b', 'm', 'z', 'l'])
  
&gt;&gt;&gt; a.add('z')                          # add a new element
+
>>> a.add('z')                          # add a new element
&gt;&gt;&gt; a.update('wxy')                    # add multiple new elements
+
>>> a.update('wxy')                    # add multiple new elements
&gt;&gt;&gt; a
+
>>> a
 
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
 
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
&gt;&gt;&gt; a.remove('x')                      # take one element out
+
>>> a.remove('x')                      # take one element out
&gt;&gt;&gt; a
+
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])</pre>
+
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[../../library/stdtypes#frozenset|<code>frozenset()</code>]] type is an immutable version of [[../../library/stdtypes#set|<code>set()</code>]]. Since it is
+
[[../../library/stdtypes#frozenset|frozenset()]] 类型是 [[../../library/stdtypes#set|set()]] 的不可变版本。 由于它是不可变和可散列的,因此它可以用作字典键或另一个集合的成员。
immutable and hashable, it may be used as a dictionary key or as a member of
 
another set.
 
  
The <code>sets</code> module remains in the standard library, and may be useful if you
+
<code>sets</code> 模块保留在标准库中,如果您希望对 <code>Set</code> <code>ImmutableSet</code> 类进行子类化,它可能很有用。 目前没有计划弃用该模块。
wish to subclass the <code>Set</code> or <code>ImmutableSet</code> classes. There are
 
currently no plans to deprecate the module.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0218 '''PEP 218'''] - Adding a Built-In Set Object Type
+
; <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0218 PEP 218] - 添加内置集对象类型
: Originally proposed by Greg Wilson and ultimately implemented by Raymond Hettinger.
+
: 最初由 Greg Wilson 提出,最终由 Raymond Hettinger 实施。
  
  
第89行: 第71行:
 
<div id="pep-237-unifying-long-integers-and-integers" class="section">
 
<div id="pep-237-unifying-long-integers-and-integers" class="section">
  
== PEP 237: Unifying Long Integers and Integers ==
+
== PEP 237:统一长整数和整数 ==
  
The lengthy transition process for this PEP, begun in Python 2.2, takes another
+
PEP 的漫长过渡过程始于 Python 2.2,在 Python 2.4 中又向前迈进了一步。 在 2.3 中,某些整数运算在 int/long 统一触发 [[../../library/exceptions#FutureWarning|FutureWarning]] 警告并返回限制为 32 64 位的值(取决于您的平台)后表现不同。 在 2.4 中,这些表达式不再产生警告,而是产生不同的结果,通常是一个长整数。
step forward in Python 2.4. In 2.3, certain integer operations that would
 
behave differently after int/long unification triggered [[../../library/exceptions#FutureWarning|<code>FutureWarning</code>]]
 
warnings and returned values limited to 32 or 64 bits (depending on your
 
platform). In 2.4, these expressions no longer produce a warning and instead
 
produce a different result that's usually a long integer.
 
  
The problematic expressions are primarily left shifts and lengthy hexadecimal
+
有问题的表达式主要是左移和冗长的十六进制和八进制常量。 例如,<code>2 &lt;&lt; 32</code> 2.3 中导致警告,在 32 位平台上计算为 0。 在 Python 2.4 中,此表达式现在返回正确答案 8589934592。
and octal constants. For example, <code>2 &lt;&lt; 32</code> results in a warning in 2.3,
 
evaluating to 0 on 32-bit platforms. In Python 2.4, this expression now returns
 
the correct answer, 8589934592.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-1" class="target"></span>[https://www.python.org/dev/peps/pep-0237 '''PEP 237'''] - Unifying Long Integers and Integers
+
; <span id="index-1" class="target"></span>[https://www.python.org/dev/peps/pep-0237 PEP 237] - 统一长整数和整数
: Original PEP written by Moshe Zadka and GvR. The changes for 2.4 were implemented by Kalle Svensson.
+
: Moshe Zadka GvR 编写的原始 PEP。 2.4 的更改由 Kalle Svensson 实施。
  
  
第116行: 第90行:
 
<div id="pep-289-generator-expressions" class="section">
 
<div id="pep-289-generator-expressions" class="section">
  
== PEP 289: Generator Expressions ==
+
== PEP 289:生成器表达式 ==
  
The iterator feature introduced in Python 2.2 and the [[../../library/itertools#module-itertools|<code>itertools</code>]] module
+
Python 2.2 中引入的迭代器功能和 [[../../library/itertools#module-itertools|itertools]] 模块可以更轻松地编写循环遍历大型数据集的程序,而无需一次将整个数据集保存在内存中。 列表推导式不太适合这张图,因为它们生成了一个包含所有项目的 Python 列表对象。 这不可避免地将所有对象拉入内存,如果您的数据集非常大,这可能是一个问题。 当试图编写一个函数式风格的程序时,很自然地编写如下内容:
make it easier to write programs that loop through large data sets without
 
having the entire data set in memory at one time. List comprehensions don't fit
 
into this picture very well because they produce a Python list object containing
 
all of the items. This unavoidably pulls all of the objects into memory, which
 
can be a problem if your data set is very large. When trying to write a
 
functionally-styled program, it would be natural to write something like:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第130行: 第98行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>links = [link for link in get_all_links() if not link.followed]
+
<syntaxhighlight lang="python3">links = [link for link in get_all_links() if not link.followed]
 
for link in links:
 
for link in links:
     ...</pre>
+
     ...</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
instead of
+
代替
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第143行: 第111行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>for link in get_all_links():
+
<syntaxhighlight lang="python3">for link in get_all_links():
 
     if link.followed:
 
     if link.followed:
 
         continue
 
         continue
     ...</pre>
+
     ...</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The first form is more concise and perhaps more readable, but if you're dealing
+
第一种形式更简洁,可能更具可读性,但如果您正在处理大量链接对象,则必须编写第二种形式以避免将所有链接对象同时放入内存中。
with a large number of link objects you'd have to write the second form to avoid
 
having all link objects in memory at the same time.
 
  
Generator expressions work similarly to list comprehensions but don't
+
生成器表达式的工作方式类似于列表推导式,但不会具体化整个列表; 相反,他们创建了一个生成器,它将一个一个地返回元素。 上面的例子可以写成:
materialize the entire list; instead they create a generator that will return
 
elements one by one. The above example could be written as:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第163行: 第127行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>links = (link for link in get_all_links() if not link.followed)
+
<syntaxhighlight lang="python3">links = (link for link in get_all_links() if not link.followed)
 
for link in links:
 
for link in links:
     ...</pre>
+
     ...</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Generator expressions always have to be written inside parentheses, as in the
+
生成器表达式总是必须写在括号内,如上例所示。 表示函数调用的括号也很重要,因此如果您想创建一个将立即传递给函数的迭代器,您可以编写:
above example. The parentheses signalling a function call also count, so if you
 
want to create an iterator that will be immediately passed to a function you
 
could write:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第179行: 第140行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>print sum(obj.count for obj in list_all_objects())</pre>
+
<syntaxhighlight lang="python3">print sum(obj.count for obj in list_all_objects())</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Generator expressions differ from list comprehensions in various small ways.
+
生成器表达式与列表推导式在各种小方面有所不同。 最值得注意的是,循环变量(上面例子中的 ''obj'')在生成器表达式之外是不可访问的。 列表推导式将变量分配给它的最后一个值; Python 的未来版本将改变这一点,使列表推导式在这方面与生成器表达式相匹配。
Most notably, the loop variable (''obj'' in the above example) is not accessible
 
outside of the generator expression. List comprehensions leave the variable
 
assigned to its last value; future versions of Python will change this, making
 
list comprehensions match generator expressions in this respect.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0289 '''PEP 289'''] - Generator Expressions
+
; <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0289 PEP 289] - 生成器表达式
: Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.
+
: Raymond Hettinger 提出,由 Jiwon Seo 实施,早期工作由 Hye-Shik Chang 指导。
  
  
第203行: 第160行:
 
<div id="pep-292-simpler-string-substitutions" class="section">
 
<div id="pep-292-simpler-string-substitutions" class="section">
  
== PEP 292: Simpler String Substitutions ==
+
== PEP 292:更简单的字符串替换 ==
  
Some new classes in the standard library provide an alternative mechanism for
+
标准库中的一些新类提供了将变量替换为字符串的替代机制; 这种替换风格可能更适合未经培训的用户需要编辑模板的应用程序。
substituting variables into strings; this style of substitution may be better
 
for applications where untrained users need to edit templates.
 
  
The usual way of substituting variables by name is the <code>%</code> operator:
+
按名称替换变量的常用方法是 <code>%</code> 运算符:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第215行: 第170行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
+
<syntaxhighlight lang="python3">>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
'2: The Best of Times'</pre>
+
'2: The Best of Times'</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
When writing the template string, it can be easy to forget the <code>i</code> or <code>s</code>
+
在编写模板字符串时,很容易忘记右括号后的 <code>i</code> <code>s</code>。 如果模板在 Python 模块中,这不是大问题,因为您运行代码,得到“不支持的格式字符”[[../../library/exceptions#ValueError|ValueError]],然后修复问题。 但是,考虑一个应用程序,例如 Mailman,其中模板字符串或翻译由不了解 Python 语言的用户编辑。 向这些用户解释格式字符串的语法很复杂,如果他们犯了错误,也很难向他们提供有用的反馈。
after the closing parenthesis. This isn't a big problem if the template is in a
 
Python module, because you run the code, get an &quot;Unsupported format character&quot;
 
[[../../library/exceptions#ValueError|<code>ValueError</code>]], and fix the problem. However, consider an application such
 
as Mailman where template strings or translations are being edited by users who
 
aren't aware of the Python language. The format string's syntax is complicated
 
to explain to such users, and if they make a mistake, it's difficult to provide
 
helpful feedback to them.
 
  
PEP 292 adds a <code>Template</code> class to the [[../../library/string#module-string|<code>string</code>]] module that uses
+
PEP 292 <code>Template</code> 类添加到 [[../../library/string#module-string|string]] 模块中,该模块使用 <code>$</code> 来指示替换:
<code>$</code> to indicate a substitution:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第237行: 第184行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import string
+
<syntaxhighlight lang="python3">>>> import string
&gt;&gt;&gt; t = string.Template('$page: $title')
+
>>> t = string.Template('$page: $title')
&gt;&gt;&gt; t.substitute({'page':2, 'title': 'The Best of Times'})
+
>>> t.substitute({'page':2, 'title': 'The Best of Times'})
'2: The Best of Times'</pre>
+
'2: The Best of Times'</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If a key is missing from the dictionary, the <code>substitute()</code> method will
+
如果字典中缺少键,<code>substitute()</code> 方法将引发 [[../../library/exceptions#KeyError|KeyError]]。 还有一个 <code>safe_substitute()</code> 方法可以忽略丢失的键:
raise a [[../../library/exceptions#KeyError|<code>KeyError</code>]]. There's also a <code>safe_substitute()</code> method that
 
ignores missing keys:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第253行: 第198行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; t = string.Template('$page: $title')
+
<syntaxhighlight lang="python3">>>> t = string.Template('$page: $title')
&gt;&gt;&gt; t.safe_substitute({'page':3})
+
>>> t.safe_substitute({'page':3})
'3: $title'</pre>
+
'3: $title'</syntaxhighlight>
  
 
</div>
 
</div>
第262行: 第207行:
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-3" class="target"></span>[https://www.python.org/dev/peps/pep-0292 '''PEP 292'''] - Simpler String Substitutions
+
; <span id="index-3" class="target"></span>[https://www.python.org/dev/peps/pep-0292 PEP 292] - 更简单的字符串替换
: Written and implemented by Barry Warsaw.
+
: Barry Warsaw 编写和实施。
  
  
第273行: 第218行:
 
<div id="pep-318-decorators-for-functions-and-methods" class="section">
 
<div id="pep-318-decorators-for-functions-and-methods" class="section">
  
== PEP 318: Decorators for Functions and Methods ==
+
== PEP 318:函数和方法的装饰器 ==
  
Python 2.2 extended Python's object model by adding static methods and class
+
Python 2.2 通过添加静态方法和类方法扩展了 Python 的对象模型,但它没有扩展 Python 的语法以提供任何定义静态或类方法的新方法。 相反,您必须以通常的方式编写 [[../../reference/compound_stmts#def|def]] 语句,并将结果方法传递给 [[../../library/functions#staticmethod|staticmethod()]] [[../../library/functions#classmethod|classmethod()]] 函数,该函数将包装将函数作为新类型的方法。 您的代码如下所示:
methods, but it didn't extend Python's syntax to provide any new way of defining
 
static or class methods. Instead, you had to write a [[../../reference/compound_stmts#def|<code>def</code>]] statement
 
in the usual way, and pass the resulting method to a [[../../library/functions#staticmethod|<code>staticmethod()</code>]] or
 
[[../../library/functions#classmethod|<code>classmethod()</code>]] function that would wrap up the function as a method of the
 
new type. Your code would look like this:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第286行: 第226行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class C:
+
<syntaxhighlight lang="python3">class C:
 
   def meth (cls):
 
   def meth (cls):
 
       ...
 
       ...
  
   meth = classmethod(meth)  # Rebind name to wrapped-up class method</pre>
+
   meth = classmethod(meth)  # Rebind name to wrapped-up class method</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If the method was very long, it would be easy to miss or forget the
+
如果方法很长,很容易错过或忘记函数体后面的 [[../../library/functions#classmethod|classmethod()]] 调用。
[[../../library/functions#classmethod|<code>classmethod()</code>]] invocation after the function body.
 
  
The intention was always to add some syntax to make such definitions more
+
其意图始终是添加一些语法以使此类定义更具可读性,但在 2.2 发布时,好的语法并不明显。 今天,一个好的语法 ''still'' 并不明显,但用户要求更容易访问该功能; 添加了一个新的语法特性来满足这一需求。
readable, but at the time of 2.2's release a good syntax was not obvious. Today
 
a good syntax ''still'' isn't obvious but users are asking for easier access to
 
the feature; a new syntactic feature has been added to meet this need.
 
  
The new feature is called &quot;function decorators&quot;. The name comes from the idea
+
新功能称为“函数装饰器”。 这个名字来源于[[../../library/functions#classmethod|classmethod()]][[../../library/functions#staticmethod|staticmethod()]]和朋友们在一个函数对象上存储附加信息的想法; 它们是 ''装饰'' 功能更多细节。
that [[../../library/functions#classmethod|<code>classmethod()</code>]], [[../../library/functions#staticmethod|<code>staticmethod()</code>]], and friends are storing
 
additional information on a function object; they're ''decorating'' functions with
 
more details.
 
  
The notation borrows from Java and uses the <code>'@'</code> character as an indicator.
+
该符号借用 Java 并使用 <code>'@'</code> 字符作为指示符。 使用新语法,上面的例子将被写成:
Using the new syntax, the example above would be written:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第315行: 第247行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class C:
+
<syntaxhighlight lang="python3">class C:
  
 
   @classmethod
 
   @classmethod
 
   def meth (cls):
 
   def meth (cls):
       ...</pre>
+
       ...</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The <code>@classmethod</code> is shorthand for the <code>meth=classmethod(meth)</code> assignment.
+
<code>@classmethod</code> <code>meth=classmethod(meth)</code> 赋值的简写。 更一般地说,如果您有以下情况:
More generally, if you have the following:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第331行: 第262行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>@A
+
<syntaxhighlight lang="python3">@A
 
@B
 
@B
 
@C
 
@C
 
def f ():
 
def f ():
     ...</pre>
+
     ...</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
It's equivalent to the following pre-decorator code:
+
它相当于下面的预装饰器代码:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第346行: 第277行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def f(): ...
+
<syntaxhighlight lang="python3">def f(): ...
f = A(B(C(f)))</pre>
+
f = A(B(C(f)))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Decorators must come on the line before a function definition, one decorator per
+
装饰器必须在函数定义之前,每行一个装饰器,并且不能与 def 语句在同一行,这意味着 <code>@A def f(): ...</code> 是非法的。 您只能在模块级别或类内部装饰函数定义; 你不能装饰类定义。
line, and can't be on the same line as the def statement, meaning that <code>@A def f(): ...</code> is illegal. You can only decorate function definitions, either at
 
the module level or inside a class; you can't decorate class definitions.
 
  
A decorator is just a function that takes the function to be decorated as an
+
装饰器只是一个函数,它将要装饰的函数作为参数并返回相同的函数或某个新对象。 装饰器的返回值不需要是可调用的(尽管它通常是),除非将进一步的装饰器应用于结果。 编写自己的装饰器很容易。 下面的简单示例只是在函数对象上设置一个属性:
argument and returns either the same function or some new object. The return
 
value of the decorator need not be callable (though it typically is), unless
 
further decorators will be applied to the result. It's easy to write your own
 
decorators. The following simple example just sets an attribute on the function
 
object:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第367行: 第291行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; def deco(func):
+
<syntaxhighlight lang="python3">>>> def deco(func):
 
...    func.attr = 'decorated'
 
...    func.attr = 'decorated'
 
...    return func
 
...    return func
 
...
 
...
&gt;&gt;&gt; @deco
+
>>> @deco
 
... def f(): pass
 
... def f(): pass
 
...
 
...
&gt;&gt;&gt; f
+
>>> f
&lt;function f at 0x402ef0d4&gt;
+
<function f at 0x402ef0d4>
&gt;&gt;&gt; f.attr
+
>>> f.attr
 
'decorated'
 
'decorated'
&gt;&gt;&gt;</pre>
+
>>></syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
As a slightly more realistic example, the following decorator checks that the
+
作为一个更现实的例子,以下装饰器检查提供的参数是否为整数:
supplied argument is an integer:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第390行: 第313行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def require_int (func):
+
<syntaxhighlight lang="python3">def require_int (func):
 
     def wrapper (arg):
 
     def wrapper (arg):
 
         assert isinstance(arg, int)
 
         assert isinstance(arg, int)
第403行: 第326行:
 
@require_int
 
@require_int
 
def p2(arg):
 
def p2(arg):
     print arg*2</pre>
+
     print arg*2</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
An example in <span id="index-4" class="target"></span>[https://www.python.org/dev/peps/pep-0318 '''PEP 318'''] contains a fancier version of this idea that lets you
+
<span id="index-4" class="target"></span>[https://www.python.org/dev/peps/pep-0318 PEP 318] 中的一个例子包含了这个想法的一个更高级的版本,它允许你指定所需的类型并检查返回的类型。
both specify the required type and check the returned type.
 
  
Decorator functions can take arguments. If arguments are supplied, your
+
装饰器函数可以带参数。 如果提供了参数,则仅使用这些参数调用装饰器函数,并且必须返回新的装饰器函数; 如前所述,此函数必须采用单个函数并返回一个函数。 换句话说,<code>@A @B @C(args)</code> 变成:
decorator function is called with only those arguments and must return a new
 
decorator function; this function must take a single function and return a
 
function, as previously described. In other words, <code>@A @B @C(args)</code> becomes:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第420行: 第339行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def f(): ...
+
<syntaxhighlight lang="python3">def f(): ...
 
_deco = C(args)
 
_deco = C(args)
f = A(B(_deco(f)))</pre>
+
f = A(B(_deco(f)))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Getting this right can be slightly brain-bending, but it's not too difficult.
+
正确地做到这一点可能有点费脑筋,但这并不太难。
  
A small related change makes the <code>func_name</code> attribute of functions
+
一个小的相关更改使函数的 <code>func_name</code> 属性可写。 此属性用于在回溯中显示函数名称,因此装饰器应更改构造和返回的任何新函数的名称。
writable. This attribute is used to display function names in tracebacks, so
 
decorators should change the name of any new function that's constructed and
 
returned.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-5" class="target"></span>[https://www.python.org/dev/peps/pep-0318 '''PEP 318'''] - Decorators for Functions, Methods and Classes
+
; <span id="index-5" class="target"></span>[https://www.python.org/dev/peps/pep-0318 PEP 318] - 函数、方法和类的装饰器
: Written by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people wrote patches implementing function decorators, but the one that was actually checked in was patch #979728, written by Mark Russell.
+
: 由凯文 D 撰写 史密斯、吉姆·朱伊特和跳过蒙塔纳罗。 有几个人编写了实现函数装饰器的补丁,但实际签入的是由 Mark Russell 编写的补丁 #979728。
 
; https://wiki.python.org/moin/PythonDecoratorLibrary
 
; https://wiki.python.org/moin/PythonDecoratorLibrary
: This Wiki page contains several examples of decorators.
+
: Wiki 页面包含几个装饰器示例。
  
  
第449行: 第365行:
 
<div id="pep-322-reverse-iteration" class="section">
 
<div id="pep-322-reverse-iteration" class="section">
  
== PEP 322: Reverse Iteration ==
+
== PEP 322:反向迭代 ==
  
A new built-in function, <code>reversed(seq)</code>, takes a sequence and returns an
+
一个新的内置函数 <code>reversed(seq)</code> 接受一个序列并返回一个迭代器,该迭代器以相反的顺序循环遍历该序列的元素。
iterator that loops over the elements of the sequence in reverse order.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第458行: 第373行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; for i in reversed(xrange(1,4)):
+
<syntaxhighlight lang="python3">>>> for i in reversed(xrange(1,4)):
 
...    print i
 
...    print i
 
...
 
...
 
3
 
3
 
2
 
2
1</pre>
+
1</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Compared to extended slicing, such as <code>range(1,4)[::-1]</code>, [[../../library/functions#reversed|<code>reversed()</code>]] is
+
与扩展切片(例如 <code>range(1,4)[::-1]</code>)相比,[[../../library/functions#reversed|reversed()]] 更易于阅读,运行速度更快,并且使用的内存要少得多。
easier to read, runs faster, and uses substantially less memory.
 
  
Note that [[../../library/functions#reversed|<code>reversed()</code>]] only accepts sequences, not arbitrary iterators. If
+
请注意, [[../../library/functions#reversed|reversed()]] 只接受序列,而不是任意迭代器。 如果要反转迭代器,请首先使用 [[../../library/stdtypes#list|list()]] 将其转换为列表。
you want to reverse an iterator, first convert it to a list with [[../../library/stdtypes#list|<code>list()</code>]].
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第478行: 第391行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; input = open('/etc/passwd', 'r')
+
<syntaxhighlight lang="python3">>>> input = open('/etc/passwd', 'r')
&gt;&gt;&gt; for line in reversed(list(input)):
+
>>> for line in reversed(list(input)):
 
...  print line
 
...  print line
 
...
 
...
 
root:*:0:0:System Administrator:/var/root:/bin/tcsh
 
root:*:0:0:System Administrator:/var/root:/bin/tcsh
   ...</pre>
+
   ...</syntaxhighlight>
  
 
</div>
 
</div>
第490行: 第403行:
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-6" class="target"></span>[https://www.python.org/dev/peps/pep-0322 '''PEP 322'''] - Reverse Iteration
+
; <span id="index-6" class="target"></span>[https://www.python.org/dev/peps/pep-0322 PEP 322] - 反向迭代
: Written and implemented by Raymond Hettinger.
+
: Raymond Hettinger 编写和实施。
  
  
第501行: 第414行:
 
<div id="pep-324-new-subprocess-module" class="section">
 
<div id="pep-324-new-subprocess-module" class="section">
  
== PEP 324: New subprocess Module ==
+
== PEP 324:新的子流程模块 ==
  
The standard library provides a number of ways to execute a subprocess, offering
+
标准库提供了多种执行子流程的方法,提供不同的功能和不同级别的复杂性。 <code>os.system(command)</code> 易于使用,但速度慢(它运行执行命令的 shell 进程)且危险(您必须小心转义 shell 的元字符)。 <code>popen2</code> 模块提供了可以从子进程捕获标准输出和标准错误的类,但命名令人困惑。 [[../../library/subprocess#module-subprocess|subprocess]] 模块对此进行了清理,提供了一个统一的界面,可以提供您可能需要的所有功能。
different features and different levels of complexity.
 
<code>os.system(command)</code> is easy to use, but slow (it runs a shell process
 
which executes the command) and dangerous (you have to be careful about escaping
 
the shell's metacharacters). The <code>popen2</code> module offers classes that can
 
capture standard output and standard error from the subprocess, but the naming
 
is confusing. The [[../../library/subprocess#module-subprocess|<code>subprocess</code>]] module cleans this up, providing a unified
 
interface that offers all the features you might need.
 
  
Instead of <code>popen2</code>'s collection of classes, [[../../library/subprocess#module-subprocess|<code>subprocess</code>]] contains a
+
代替 <code>popen2</code> 的类集合,[[../../library/subprocess#module-subprocess|subprocess]] 包含一个名为 <code>Popen</code> 的类,其构造函数支持许多不同的关键字参数。
single class called <code>Popen</code> whose constructor supports a number of
 
different keyword arguments.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第520行: 第424行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class Popen(args, bufsize=0, executable=None,
+
<syntaxhighlight lang="python3">class Popen(args, bufsize=0, executable=None,
 
             stdin=None, stdout=None, stderr=None,
 
             stdin=None, stdout=None, stderr=None,
 
             preexec_fn=None, close_fds=False, shell=False,
 
             preexec_fn=None, close_fds=False, shell=False,
 
             cwd=None, env=None, universal_newlines=False,
 
             cwd=None, env=None, universal_newlines=False,
             startupinfo=None, creationflags=0):</pre>
+
             startupinfo=None, creationflags=0):</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
''args'' is commonly a sequence of strings that will be the arguments to the
+
''args'' 通常是一个字符串序列,它们将作为作为子进程执行的程序的参数。 (如果 ''shell'' 参数为真,''args'' 可以是一个字符串,然后将传递给 shell 进行解释,就像 [[../../library/os#os|os.system()]]做。)
program executed as the subprocess. (If the ''shell'' argument is true, ''args''
 
can be a string which will then be passed on to the shell for interpretation,
 
just as [[../../library/os#os|<code>os.system()</code>]] does.)
 
  
''stdin'', ''stdout'', and ''stderr'' specify what the subprocess's input, output, and
+
''stdin''''stdout'' ''stderr'' 指定子进程的输入、输出和错误流将是什么。 您可以提供文件对象或文件描述符,也可以使用常量 <code>subprocess.PIPE</code> 在子进程和父进程之间创建管道。
error streams will be. You can provide a file object or a file descriptor, or
 
you can use the constant <code>subprocess.PIPE</code> to create a pipe between the
 
subprocess and the parent.
 
  
The constructor has a number of handy options:
+
构造函数有许多方便的选项:
  
* ''close_fds'' requests that all file descriptors be closed before running the subprocess.
+
* ''close_fds'' 请求在运行子进程之前关闭所有文件描述符。
* ''cwd'' specifies the working directory in which the subprocess will be executed (defaulting to whatever the parent's working directory is).
+
* ''cwd'' 指定子进程将在其中执行的工作目录(默认为父进程的任何工作目录)。
* ''env'' is a dictionary specifying environment variables.
+
* ''env'' 是一个指定环境变量的字典。
* ''preexec_fn'' is a function that gets called before the child is started.
+
* ''preexec_fn'' 是在子进程启动之前调用的函数。
* ''universal_newlines'' opens the child's input and output using Python's [[../../glossary#term-universal-newlines|<span class="xref std std-term">universal newlines</span>]] feature.
+
* ''universal_newlines'' 使用 Python [[../../glossary#term-universal-newlines|universal newlines]] 功能打开孩子的输入和输出。
  
Once you've created the <code>Popen</code> instance, you can call its <code>wait()</code>
+
一旦你创建了 <code>Popen</code> 实例,你可以调用它的 <code>wait()</code> 方法暂停直到子进程退出,<code>poll()</code> 检查它是否在没有暂停的情况下退出,或者 <code>communicate(data)</code> 将字符串 ''data'' 发送到子进程的标准输入。 <code>communicate(data)</code> 然后读取子进程发送到其标准输出或标准错误的任何数据,返回一个元组 <code>(stdout_data, stderr_data)</code>
method to pause until the subprocess has exited, <code>poll()</code> to check if it's
 
exited without pausing, or <code>communicate(data)</code> to send the string ''data''
 
to the subprocess's standard input. <code>communicate(data)</code> then reads any
 
data that the subprocess has sent to its standard output or standard error,
 
returning a tuple <code>(stdout_data, stderr_data)</code>.
 
  
<code>call()</code> is a shortcut that passes its arguments along to the <code>Popen</code>
+
<code>call()</code> 是一个快捷方式,将其参数传递给 <code>Popen</code> 构造函数,等待命令完成,并返回子进程的状态代码。 它可以作为 [[../../library/os#os|os.system()]] 的更安全的模拟:
constructor, waits for the command to complete, and returns the status code of
 
the subprocess. It can serve as a safer analog to [[../../library/os#os|<code>os.system()</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第562行: 第453行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
+
<syntaxhighlight lang="python3">sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
 
if sts == 0:
 
if sts == 0:
 
     # Success
 
     # Success
第568行: 第459行:
 
else:
 
else:
 
     # dpkg returned an error
 
     # dpkg returned an error
     ...</pre>
+
     ...</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The command is invoked without use of the shell. If you really do want to use
+
该命令是在不使用 shell 的情况下调用的。 如果你真的想使用 shell,你可以添加 <code>shell=True</code> 作为关键字参数并提供一个字符串而不是一个序列:
the shell, you can add <code>shell=True</code> as a keyword argument and provide a string
 
instead of a sequence:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第581行: 第470行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)</pre>
+
<syntaxhighlight lang="python3">sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The PEP takes various examples of shell and Python code and shows how they'd be
+
PEP 采用各种 shell Python 代码示例,并展示了如何将它们转换为使用 [[../../library/subprocess#module-subprocess|子进程]] 的 Python 代码。 强烈建议阅读 PEP 的这一部分。
translated into Python code that uses [[../../library/subprocess#module-subprocess|<code>subprocess</code>]]. Reading this section
 
of the PEP is highly recommended.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-8" class="target"></span>[https://www.python.org/dev/peps/pep-0324 '''PEP 324'''] - subprocess - New process module
+
; <span id="index-8" class="target"></span>[https://www.python.org/dev/peps/pep-0324 PEP 324] - 子流程 - 新流程模块
: Written and implemented by Peter Åstrand, with assistance from Fredrik Lundh and others.
+
: Peter Åstrand Fredrik Lundh 和其他人的协助下编写和实施。
  
  
第603行: 第490行:
 
<div id="pep-327-decimal-data-type" class="section">
 
<div id="pep-327-decimal-data-type" class="section">
  
== PEP 327: Decimal Data Type ==
+
== PEP 327:十进制数据类型 ==
  
Python has always supported floating-point (FP) numbers, based on the underlying
+
Python 一直支持基于底层 C <span class="xref c c-texpr">double</span> 类型的浮点 (FP) 数作为数据类型。 然而,虽然大多数编程语言都提供浮点类型,但许多人(甚至程序员)并不知道浮点数不能准确地表示某些小数。 新的 <code>Decimal</code> 类型可以准确地表示这些分数,最高可达用户指定的精度限制。
C <span class="xref c c-texpr">double</span> type, as a data type. However, while most programming
 
languages provide a floating-point type, many people (even programmers) are
 
unaware that floating-point numbers don't represent certain decimal fractions
 
accurately. The new <code>Decimal</code> type can represent these fractions
 
accurately, up to a user-specified precision limit.
 
  
 
<div id="why-is-decimal-needed" class="section">
 
<div id="why-is-decimal-needed" class="section">
  
=== Why is Decimal needed? ===
+
=== 为什么需要十进制? ===
  
The limitations arise from the representation used for floating-point numbers.
+
限制来自用于浮点数的表示。 FP 数字由三个部分组成:
FP numbers are made up of three components:
 
  
* The sign, which is positive or negative.
+
* 正负号。
* The mantissa, which is a single-digit binary number followed by a fractional part. For example, <code>1.01</code> in base-2 notation is <code>1 + 0/2 + 1/4</code>, or 1.25 in decimal notation.
+
* 尾数,它是一位二进制数,后跟小数部分。 例如,以 2 进制表示的 <code>1.01</code> <code>1 + 0/2 + 1/4</code>,或十进制表示法中的 1.25。
* The exponent, which tells where the decimal point is located in the number represented.
+
* 指数,它告诉小数点在所表示的数字中的位置。
  
For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in
+
例如,数字 1.25 为正号,尾数值为 1.01(二进制),指数为 0(小数点不需要移动)。 数字 5 具有相同的符号和尾数,但指数为 2,因为尾数乘以 4(2 的指数 2 次方); 1.25 * 4 等于 5。
binary), and an exponent of 0 (the decimal point doesn't need to be shifted).
 
The number 5 has the same sign and mantissa, but the exponent is 2 because the
 
mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 * 4 equals
 
5.
 
  
Modern systems usually provide floating-point support that conforms to a
+
现代系统通常提供符合 IEEE 754 标准的浮点支持。 C <span class="xref c c-texpr">double</span> 类型通常实现为 64 IEEE 754 数字,它使用 52 位空间作为尾数。 这意味着数字只能指定为 52 位精度。 如果您试图表示无限重复扩展的数字,则扩展会在 52 位后被切断。 不幸的是,大多数软件需要产生以 10 为基数的输出,而以 10 为基数的常见分数通常是重复二进制的十进制数。 例如1.1十进制就是二进制<code>1.0001100110011 ...</code>.1 = 1/16 + 1/32 + 1/256 加上无限数量的附加项。 IEEE 754 必须在 52 位数字后去掉无限重复的小数,因此表示有点不准确。
standard called IEEE 754. C's <span class="xref c c-texpr">double</span> type is usually implemented as a
 
64-bit IEEE 754 number, which uses 52 bits of space for the mantissa. This
 
means that numbers can only be specified to 52 bits of precision. If you're
 
trying to represent numbers whose expansion repeats endlessly, the expansion is
 
cut off after 52 bits. Unfortunately, most software needs to produce output in
 
base 10, and common fractions in base 10 are often repeating decimals in binary.
 
For example, 1.1 decimal is binary <code>1.0001100110011 ...</code>; .1 = 1/16 + 1/32 +
 
1/256 plus an infinite number of additional terms. IEEE 754 has to chop off
 
that infinitely repeated decimal after 52 digits, so the representation is
 
slightly inaccurate.
 
  
Sometimes you can see this inaccuracy when the number is printed:
+
有时您会在打印数字时看到这种不准确:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第647行: 第514行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; 1.1
+
<syntaxhighlight lang="python3">>>> 1.1
1.1000000000000001</pre>
+
1.1000000000000001</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The inaccuracy isn't always visible when you print the number because the
+
当您打印数字时,不准确并不总是可见的,因为 FP 到十进制字符串的转换是由 C 库提供的,并且大多数 C 库都试图产生合理的输出。 然而,即使它不显示,不准确仍然存在,后续操作可能会放大错误。
FP-to-decimal-string conversion is provided by the C library, and most C libraries try
 
to produce sensible output. Even if it's not displayed, however, the inaccuracy
 
is still there and subsequent operations can magnify the error.
 
  
For many applications this doesn't matter. If I'm plotting points and
+
对于许多应用程序,这无关紧要。 如果我正在绘制点并将它们显示在我的监视器上,1.1 1.10000000000000001 之间的差异太小而无法看到。 报告通常将输出限制为一定数量的小数位,如果将数字四舍五入到两位、三位甚至八位小数,则错误永远不会明显。 但是,对于重要的应用程序,实现您自己的自定义算术例程需要大量工作。
displaying them on my monitor, the difference between 1.1 and 1.1000000000000001
 
is too small to be visible. Reports often limit output to a certain number of
 
decimal places, and if you round the number to two or three or even eight
 
decimal places, the error is never apparent. However, for applications where it
 
does matter, it's a lot of work to implement your own custom arithmetic
 
routines.
 
  
Hence, the <code>Decimal</code> type was created.
+
因此,创建了 <code>Decimal</code> 类型。
  
  
第672行: 第530行:
 
<div id="the-decimal-type" class="section">
 
<div id="the-decimal-type" class="section">
  
=== The <code>Decimal</code> type ===
+
=== Decimal型 ===
  
A new module, [[../../library/decimal#module-decimal|<code>decimal</code>]], was added to Python's standard library. It
+
Python 的标准库中添加了一个新模块 [[../../library/decimal#module-decimal|decimal]]。 它包含两个类,<code>Decimal</code> <code>Context</code><code>Decimal</code> 实例代表数字,<code>Context</code> 实例用于包装精度和默认舍入模式等各种设置。
contains two classes, <code>Decimal</code> and <code>Context</code>. <code>Decimal</code>
 
instances represent numbers, and <code>Context</code> instances are used to wrap up
 
various settings such as the precision and default rounding mode.
 
  
<code>Decimal</code> instances are immutable, like regular Python integers and FP
+
<code>Decimal</code> 实例是不可变的,就像常规的 Python 整数和 FP 数一样; 一旦它被创建,你就不能改变一个实例代表的值。 <code>Decimal</code> 实例可以从整数或字符串创建:
numbers; once it's been created, you can't change the value an instance
 
represents. <code>Decimal</code> instances can be created from integers or
 
strings:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第688行: 第540行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import decimal
+
<syntaxhighlight lang="python3">>>> import decimal
&gt;&gt;&gt; decimal.Decimal(1972)
+
>>> decimal.Decimal(1972)
Decimal(&quot;1972&quot;)
+
Decimal("1972")
&gt;&gt;&gt; decimal.Decimal(&quot;1.1&quot;)
+
>>> decimal.Decimal("1.1")
Decimal(&quot;1.1&quot;)</pre>
+
Decimal("1.1")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
You can also provide tuples containing the sign, the mantissa represented as a
+
您还可以提供包含符号、表示为十进制数字元组的尾数和指数的元组:
tuple of decimal digits, and the exponent:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第704行: 第555行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; decimal.Decimal((1, (1, 4, 7, 5), -2))
+
<syntaxhighlight lang="python3">>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
Decimal(&quot;-14.75&quot;)</pre>
+
Decimal("-14.75")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is
+
注意事项:符号位是布尔值,因此 0 为正,1 为负。
negative.
 
  
Converting from floating-point numbers poses a bit of a problem: should the FP
+
从浮点数转换会带来一些问题:代表 1.1 的 FP 数是否应该变成十进制数正好是 1.1,还是 1.1 加上引入的任何不准确之处? 决定是为了避免这个问题并将这样的转换排除在 API 之外。 相反,您应该使用所需的精度将浮点数转换为字符串,并将该字符串传递给 <code>Decimal</code> 构造函数:
number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1
 
plus whatever inaccuracies are introduced? The decision was to dodge the issue
 
and leave such a conversion out of the API. Instead, you should convert the
 
floating-point number into a string using the desired precision and pass the
 
string to the <code>Decimal</code> constructor:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第724行: 第569行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; f = 1.1
+
<syntaxhighlight lang="python3">>>> f = 1.1
&gt;&gt;&gt; decimal.Decimal(str(f))
+
>>> decimal.Decimal(str(f))
Decimal(&quot;1.1&quot;)
+
Decimal("1.1")
&gt;&gt;&gt; decimal.Decimal('%.12f' % f)
+
>>> decimal.Decimal('%.12f' % f)
Decimal(&quot;1.100000000000&quot;)</pre>
+
Decimal("1.100000000000")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Once you have <code>Decimal</code> instances, you can perform the usual mathematical
+
一旦您拥有 <code>Decimal</code> 实例,您就可以对它们执行通常的数学运算。 一个限制:求幂需要一个整数指数:
operations on them. One limitation: exponentiation requires an integer
 
exponent:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第741行: 第584行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; a = decimal.Decimal('35.72')
+
<syntaxhighlight lang="python3">>>> a = decimal.Decimal('35.72')
&gt;&gt;&gt; b = decimal.Decimal('1.73')
+
>>> b = decimal.Decimal('1.73')
&gt;&gt;&gt; a+b
+
>>> a+b
Decimal(&quot;37.45&quot;)
+
Decimal("37.45")
&gt;&gt;&gt; a-b
+
>>> a-b
Decimal(&quot;33.99&quot;)
+
Decimal("33.99")
&gt;&gt;&gt; a*b
+
>>> a*b
Decimal(&quot;61.7956&quot;)
+
Decimal("61.7956")
&gt;&gt;&gt; a/b
+
>>> a/b
Decimal(&quot;20.64739884393063583815028902&quot;)
+
Decimal("20.64739884393063583815028902")
&gt;&gt;&gt; a ** 2
+
>>> a ** 2
Decimal(&quot;1275.9184&quot;)
+
Decimal("1275.9184")
&gt;&gt;&gt; a**b
+
>>> a**b
 
Traceback (most recent call last):
 
Traceback (most recent call last):
 
   ...
 
   ...
decimal.InvalidOperation: x ** (non-integer)</pre>
+
decimal.InvalidOperation: x ** (non-integer)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
You can combine <code>Decimal</code> instances with integers, but not with
+
您可以将 <code>Decimal</code> 实例与整数组合,但不能与浮点数组合:
floating-point numbers:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第768行: 第610行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; a + 4
+
<syntaxhighlight lang="python3">>>> a + 4
Decimal(&quot;39.72&quot;)
+
Decimal("39.72")
&gt;&gt;&gt; a + 4.5
+
>>> a + 4.5
 
Traceback (most recent call last):
 
Traceback (most recent call last):
 
   ...
 
   ...
 
TypeError: You can interact Decimal only with int, long or Decimal data types.
 
TypeError: You can interact Decimal only with int, long or Decimal data types.
&gt;&gt;&gt;</pre>
+
>>></syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>Decimal</code> numbers can be used with the [[../../library/math#module-math|<code>math</code>]] and [[../../library/cmath#module-cmath|<code>cmath</code>]]
+
<code>Decimal</code> 数可以与 [[../../library/math#module-math|math]] [[../../library/cmath#module-cmath|cmath]] 模块一起使用,但请注意,在执行运算之前,它们会立即转换为浮点数,结果可能会损失精度和准确度。 您还将得到一个常规的浮点数,而不是 <code>Decimal</code>
modules, but note that they'll be immediately converted to floating-point
 
numbers before the operation is performed, resulting in a possible loss of
 
precision and accuracy. You'll also get back a regular floating-point number
 
and not a <code>Decimal</code>.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第789行: 第627行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import math, cmath
+
<syntaxhighlight lang="python3">>>> import math, cmath
&gt;&gt;&gt; d = decimal.Decimal('123456789012.345')
+
>>> d = decimal.Decimal('123456789012.345')
&gt;&gt;&gt; math.sqrt(d)
+
>>> math.sqrt(d)
 
351364.18288201344
 
351364.18288201344
&gt;&gt;&gt; cmath.sqrt(-d)
+
>>> cmath.sqrt(-d)
351364.18288201344j</pre>
+
351364.18288201344j</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>Decimal</code> instances have a <code>sqrt()</code> method that returns a
+
<code>Decimal</code> 实例有一个 <code>sqrt()</code> 方法,该方法返回一个 <code>Decimal</code>,但是如果您需要其他东西,例如三角函数,则必须实现它们。
<code>Decimal</code>, but if you need other things such as trigonometric functions
 
you'll have to implement them.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第807行: 第643行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; d.sqrt()
+
<syntaxhighlight lang="python3">>>> d.sqrt()
Decimal(&quot;351364.1828820134592177245001&quot;)</pre>
+
Decimal("351364.1828820134592177245001")</syntaxhighlight>
  
 
</div>
 
</div>
第817行: 第653行:
 
<div id="the-context-type" class="section">
 
<div id="the-context-type" class="section">
  
=== The <code>Context</code> type ===
+
=== Context型 ===
  
Instances of the <code>Context</code> class encapsulate several settings for
+
<code>Context</code> 类的实例封装了十进制运算的几个设置:
decimal operations:
 
  
* <code>prec</code> is the precision, the number of decimal places.
+
* <code>prec</code>为精度,小数位数。
* <code>rounding</code> specifies the rounding mode. The [[../../library/decimal#module-decimal|<code>decimal</code>]] module has constants for the various possibilities: <code>ROUND_DOWN</code>, <code>ROUND_CEILING</code>, <code>ROUND_HALF_EVEN</code>, and various others.
+
* <code>rounding</code> 指定舍入模式。 [[../../library/decimal#module-decimal|decimal]] 模块具有用于各种可能性的常量:<code>ROUND_DOWN</code><code>ROUND_CEILING</code><code>ROUND_HALF_EVEN</code> 和各种其他。
* <code>traps</code> is a dictionary specifying what happens on encountering certain error conditions: either an exception is raised or a value is returned. Some examples of error conditions are division by zero, loss of precision, and overflow.
+
* <code>traps</code> 是一个字典,指定在遇到某些错误条件时会发生什么:引发异常或返回值。 错误条件的一些示例是被零除、精度损失和溢出。
  
There's a thread-local default context available by calling <code>getcontext()</code>;
+
通过调用 <code>getcontext()</code> 可以使用线程本地默认上下文; 您可以更改此上下文的属性以更改默认精度、舍入或陷阱处理。 以下示例显示了更改默认上下文精度的效果:
you can change the properties of this context to alter the default precision,
 
rounding, or trap handling. The following example shows the effect of changing
 
the precision of the default context:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第835行: 第667行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; decimal.getcontext().prec
+
<syntaxhighlight lang="python3">>>> decimal.getcontext().prec
 
28
 
28
&gt;&gt;&gt; decimal.Decimal(1) / decimal.Decimal(7)
+
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal(&quot;0.1428571428571428571428571429&quot;)
+
Decimal("0.1428571428571428571428571429")
&gt;&gt;&gt; decimal.getcontext().prec = 9
+
>>> decimal.getcontext().prec = 9
&gt;&gt;&gt; decimal.Decimal(1) / decimal.Decimal(7)
+
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal(&quot;0.142857143&quot;)</pre>
+
Decimal("0.142857143")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The default action for error conditions is selectable; the module can either
+
错误条件的默认操作是可选的; 该模块可以返回一个特殊值,例如无穷大或非数字,或者可以引发异常:
return a special value such as infinity or not-a-number, or exceptions can be
 
raised:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第854行: 第684行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; decimal.Decimal(1) / decimal.Decimal(0)
+
<syntaxhighlight lang="python3">>>> decimal.Decimal(1) / decimal.Decimal(0)
 
Traceback (most recent call last):
 
Traceback (most recent call last):
 
   ...
 
   ...
 
decimal.DivisionByZero: x / 0
 
decimal.DivisionByZero: x / 0
&gt;&gt;&gt; decimal.getcontext().traps[decimal.DivisionByZero] = False
+
>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
&gt;&gt;&gt; decimal.Decimal(1) / decimal.Decimal(0)
+
>>> decimal.Decimal(1) / decimal.Decimal(0)
Decimal(&quot;Infinity&quot;)
+
Decimal("Infinity")
&gt;&gt;&gt;</pre>
+
>>></syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The <code>Context</code> instance also has various methods for formatting numbers
+
<code>Context</code> 实例也有多种格式化数字的方法,例如 <code>to_eng_string()</code> <code>to_sci_string()</code>
such as <code>to_eng_string()</code> and <code>to_sci_string()</code>.
 
  
For more information, see the documentation for the [[../../library/decimal#module-decimal|<code>decimal</code>]] module, which
+
有关详细信息,请参阅 [[../../library/decimal#module-decimal|decimal]] 模块的文档,其中包括快速入门教程和参考。
includes a quick-start tutorial and a reference.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-9" class="target"></span>[https://www.python.org/dev/peps/pep-0327 '''PEP 327'''] - Decimal Data Type
+
; <span id="index-9" class="target"></span>[https://www.python.org/dev/peps/pep-0327 PEP 327] - 十进制数据类型
: Written by Facundo Batista and implemented by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.
+
: Facundo Batista 编写,由 Facundo Batista、Eric Price、Raymond Hettinger、Aahz 和 Tim Peters 实施。
 
; http://www.lahey.com/float.htm
 
; http://www.lahey.com/float.htm
: The article uses Fortran code to illustrate many of the problems that floating-point inaccuracy can cause.
+
: 本文使用 Fortran 代码来说明浮点不准确可能导致的许多问题。
 
; http://speleotrove.com/decimal/
 
; http://speleotrove.com/decimal/
: A description of a decimal-based representation. This representation is being proposed as a standard, and underlies the new Python decimal type. Much of this material was written by Mike Cowlishaw, designer of the Rexx language.
+
: 基于十进制表示的描述。 这种表示被提议作为标准,并且是新的 Python 十进制类型的基础。 这些材料的大部分是由 Rexx 语言的设计者 Mike Cowlishaw 编写的。
  
  
第891行: 第719行:
 
<div id="pep-328-multi-line-imports" class="section">
 
<div id="pep-328-multi-line-imports" class="section">
  
== PEP 328: Multi-line Imports ==
+
== PEP 328:多行导入 ==
  
One language change is a small syntactic tweak aimed at making it easier to
+
一种语言更改是一个小的语法调整,旨在使从模块中导入许多名称变得更加容易。 在 <code>from module import names</code> 语句中,''names'' 是由逗号分隔的名称序列。 如果序列很长,您可以从同一个模块中编写多个导入,或者您可以使用反斜杠来转义行结尾,如下所示:
import many names from a module. In a <code>from module import names</code> statement,
 
''names'' is a sequence of names separated by commas. If the sequence is very
 
long, you can either write multiple imports from the same module, or you can use
 
backslashes to escape the line endings like this:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第903行: 第727行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from SimpleXMLRPCServer import SimpleXMLRPCServer,\
+
<syntaxhighlight lang="python3">from SimpleXMLRPCServer import SimpleXMLRPCServer,\
 
             SimpleXMLRPCRequestHandler,\
 
             SimpleXMLRPCRequestHandler,\
 
             CGIXMLRPCRequestHandler,\
 
             CGIXMLRPCRequestHandler,\
             resolve_dotted_attribute</pre>
+
             resolve_dotted_attribute</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The syntactic change in Python 2.4 simply allows putting the names within
+
Python 2.4 中的语法更改只是允许将名称放在括号内。 Python 忽略括号表达式中的换行符,因此不再需要反斜杠:
parentheses. Python ignores newlines within a parenthesized expression, so the
 
backslashes are no longer needed:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第919行: 第741行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from SimpleXMLRPCServer import (SimpleXMLRPCServer,
+
<syntaxhighlight lang="python3">from SimpleXMLRPCServer import (SimpleXMLRPCServer,
 
                                 SimpleXMLRPCRequestHandler,
 
                                 SimpleXMLRPCRequestHandler,
 
                                 CGIXMLRPCRequestHandler,
 
                                 CGIXMLRPCRequestHandler,
                                 resolve_dotted_attribute)</pre>
+
                                 resolve_dotted_attribute)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The PEP also proposes that all [[../../reference/simple_stmts#import|<code>import</code>]] statements be absolute imports,
+
PEP 还建议所有 [[../../reference/simple_stmts#import|import]] 语句都是绝对导入,前导 <code>.</code> 字符表示相对导入。 PEP 的这部分不是为 Python 2.4 实现的,而是为 Python 2.5 完成的。
with a leading <code>.</code> character to indicate a relative import. This part of the
 
PEP was not implemented for Python 2.4, but was completed for Python 2.5.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-10" class="target"></span>[https://www.python.org/dev/peps/pep-0328 '''PEP 328'''] - Imports: Multi-Line and Absolute/Relative
+
; <span id="index-10" class="target"></span>[https://www.python.org/dev/peps/pep-0328 PEP 328] - 进口:多线和绝对/相对
: Written by Aahz. Multi-line imports were implemented by Dima Dorfman.
+
: 阿兹写的。 多行导入由 Dima Dorfman 实现。
  
  
第944行: 第764行:
 
<div id="pep-331-locale-independent-float-string-conversions" class="section">
 
<div id="pep-331-locale-independent-float-string-conversions" class="section">
  
== PEP 331: Locale-Independent Float/String Conversions ==
+
== PEP 331:与语言环境无关的浮点/字符串转换 ==
  
The [[../../library/locale#module-locale|<code>locale</code>]] modules lets Python software select various conversions and
+
[[../../library/locale#module-locale|locale]] 模块允许 Python 软件选择本地化为特定国家或语言的各种转换和显示约定。 但是,该模块小心地不更改数字语言环境,因为 Python 实现中的各种函数要求数字语言环境保持设置为 <code>'C'</code> 语言环境。 这通常是因为代码使用了 C 库的 <code>atof()</code> 函数。
display conventions that are localized to a particular country or language.
 
However, the module was careful to not change the numeric locale because various
 
functions in Python's implementation required that the numeric locale remain set
 
to the <code>'C'</code> locale. Often this was because the code was using the C
 
library's <code>atof()</code> function.
 
  
Not setting the numeric locale caused trouble for extensions that used third-party
+
但是,不设置数字语言环境会给使用第三方 C 库的扩展带来麻烦,因为它们没有正确的语言环境设置。 激励示例是 GTK+,其用户界面小部件未在当前语言环境中显示数字。
C libraries, however, because they wouldn't have the correct locale set.
 
The motivating example was GTK+, whose user interface widgets weren't displaying
 
numbers in the current locale.
 
  
The solution described in the PEP is to add three new functions to the Python
+
PEP 中描述的解决方案是向 Python API 添加三个新函数,这些函数执行 ASCII-only 转换,忽略区域设置:
API that perform ASCII-only conversions, ignoring the locale setting:
 
  
* <code>PyOS_ascii_strtod(str, ptr)</code> and <code>PyOS_ascii_atof(str, ptr)</code> both convert a string to a C <span class="xref c c-texpr">double</span>.
+
* <code>PyOS_ascii_strtod(str, ptr)</code> <code>PyOS_ascii_atof(str, ptr)</code> 都将字符串转换为 C <span class="xref c c-texpr">double</span>
* <code>PyOS_ascii_formatd(buffer, buf_len, format, d)</code> converts a <span class="xref c c-texpr">double</span> to an ASCII string.
+
* <code>PyOS_ascii_formatd(buffer, buf_len, format, d)</code> <span class="xref c c-texpr">double</span> 转换为 ASCII 字符串。
  
The code for these functions came from the GLib library
+
这些函数的代码来自 GLib 库(https://developer.gnome.org/glib/stable/),其开发者好心地将相关函数重新授权并捐赠给了 Python 软件基金会。 [[../../library/locale#module-locale|locale]] 模块现在可以更改数字区域设置,让 GTK+ 等扩展产生正确的结果。
(https://developer.gnome.org/glib/stable/), whose developers kindly
 
relicensed the relevant functions and donated them to the Python Software
 
Foundation. The [[../../library/locale#module-locale|<code>locale</code>]] module can now change the numeric locale,
 
letting extensions such as GTK+ produce the correct results.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-11" class="target"></span>[https://www.python.org/dev/peps/pep-0331 '''PEP 331'''] - Locale-Independent Float/String Conversions
+
; <span id="index-11" class="target"></span>[https://www.python.org/dev/peps/pep-0331 PEP 331] - 与语言环境无关的浮点/字符串转换
: Written by Christian R. Reis, and implemented by Gustavo Carneiro.
+
: 由克里斯蒂安 R 撰写。 Reis,由 Gustavo Carneiro 实施。
  
  
第983行: 第790行:
 
<div id="other-language-changes" class="section">
 
<div id="other-language-changes" class="section">
  
== Other Language Changes ==
+
== 其他语言更改 ==
  
Here are all of the changes that Python 2.4 makes to the core Python language.
+
以下是 Python 2.4 对核心 Python 语言所做的所有更改。
  
 
<ul>
 
<ul>
<li><p>Decorators for functions and methods were added (<span id="index-12" class="target"></span>[https://www.python.org/dev/peps/pep-0318 '''PEP 318''']).</p></li>
+
<li><p>添加了函数和方法的装饰器(<span id="index-12" class="target"></span>[https://www.python.org/dev/peps/pep-0318 PEP 318])。</p></li>
<li><p>Built-in [[../../library/stdtypes#set|<code>set()</code>]] and [[../../library/stdtypes#frozenset|<code>frozenset()</code>]] types were added (<span id="index-13" class="target"></span>[https://www.python.org/dev/peps/pep-0218 '''PEP 218''']).
+
<li><p>添加了内置 [[../../library/stdtypes#set|set()]] [[../../library/stdtypes#frozenset|frozenset()]] 类型(<span id="index-13" class="target"></span>[https://www.python.org/dev/peps/pep-0218 PEP 218])。 其他新的内置函数包括 <code>reversed(seq)</code> 函数(<span id="index-14" class="target"></span>[https://www.python.org/dev/peps/pep-0322 PEP 322])。</p></li>
Other new built-ins include the <code>reversed(seq)</code> function (<span id="index-14" class="target"></span>[https://www.python.org/dev/peps/pep-0322 '''PEP 322''']).</p></li>
+
<li><p>添加了生成器表达式(<span id="index-15" class="target"></span>[https://www.python.org/dev/peps/pep-0289 PEP 289])。</p></li>
<li><p>Generator expressions were added (<span id="index-15" class="target"></span>[https://www.python.org/dev/peps/pep-0289 '''PEP 289''']).</p></li>
+
<li><p>某些数值表达式不再返回限制为 32 64 位的值(<span id="index-16" class="target"></span>[https://www.python.org/dev/peps/pep-0237 PEP 237])。</p></li>
<li><p>Certain numeric expressions no longer return values restricted to 32 or 64
+
<li><p>您现在可以在 <code>from module import names</code> 语句 (<span id="index-17" class="target"></span>[https://www.python.org/dev/peps/pep-0328 PEP 328]) 中的名称列表周围加上括号。</p></li>
bits (<span id="index-16" class="target"></span>[https://www.python.org/dev/peps/pep-0237 '''PEP 237''']).</p></li>
+
<li><p>[[../../library/stdtypes#dict|dict.update()]] 方法现在接受与 [[../../library/stdtypes#dict|dict]] 构造函数相同的参数形式。 这包括任何映射、任何可迭代的键/值对和关键字参数。 (雷蒙德·赫廷格供稿。)</p></li>
<li><p>You can now put parentheses around the list of names in a <code>from module import names</code> statement (<span id="index-17" class="target"></span>[https://www.python.org/dev/peps/pep-0328 '''PEP 328''']).</p></li>
+
<li><p>字符串方法 <code>ljust()</code><code>rjust()</code> <code>center()</code> 现在采用可选参数来指定空格以外的填充字符。 (雷蒙德·赫廷格供稿。)</p></li>
<li><p>The [[../../library/stdtypes#dict|<code>dict.update()</code>]] method now accepts the same argument forms as the
+
<li><p>字符串还获得了 <code>rsplit()</code> 方法,其工作方式类似于 <code>split()</code> 方法,但从字符串的末尾拆分。 (由肖恩·赖夫施奈德提供。)</p>
[[../../library/stdtypes#dict|<code>dict</code>]] constructor. This includes any mapping, any iterable of key/value
 
pairs, and keyword arguments. (Contributed by Raymond Hettinger.)</p></li>
 
<li><p>The string methods <code>ljust()</code>, <code>rjust()</code>, and <code>center()</code> now take
 
an optional argument for specifying a fill character other than a space.
 
(Contributed by Raymond Hettinger.)</p></li>
 
<li><p>Strings also gained an <code>rsplit()</code> method that works like the <code>split()</code>
 
method but splits from the end of the string. (Contributed by Sean
 
Reifschneider.)</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; 'www.python.org'.split('.', 1)
+
<syntaxhighlight lang="python3">>>> 'www.python.org'.split('.', 1)
 
['www', 'python.org']
 
['www', 'python.org']
 
'www.python.org'.rsplit('.', 1)
 
'www.python.org'.rsplit('.', 1)
['www.python', 'org']</pre>
+
['www.python', 'org']</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p>Three keyword parameters, ''cmp'', ''key'', and ''reverse'', were added to the
+
<li><p>三个关键字参数,''cmp''''key''''reverse'',被添加到列表的<code>sort()</code>方法中。 这些参数使 <code>sort()</code> 的一些常见用法变得更简单。 所有这些参数都是可选的。</p>
<code>sort()</code> method of lists. These parameters make some common usages of
+
<p>对于 ''cmp'' 参数,该值应该是一个比较函数,它接受两个参数并根据参数的比较方式返回 -1、0 或 +1。 然后将使用此函数对列表进行排序。 以前,这是唯一可以提供给 <code>sort()</code> 的参数。</p>
<code>sort()</code> simpler. All of these parameters are optional.</p>
+
<p>''key'' 应该是一个单参数函数,它接受一个列表元素并返回该元素的比较键。 然后使用比较键对列表进行排序。 以下示例不区分大小写地对列表进行排序:</p>
<p>For the ''cmp'' parameter, the value should be a comparison function that takes
 
two parameters and returns -1, 0, or +1 depending on how the parameters compare.
 
This function will then be used to sort the list. Previously this was the only
 
parameter that could be provided to <code>sort()</code>.</p>
 
<p>''key'' should be a single-parameter function that takes a list element and
 
returns a comparison key for the element. The list is then sorted using the
 
comparison keys. The following example sorts a list case-insensitively:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; L = ['A', 'b', 'c', 'D']
+
<syntaxhighlight lang="python3">>>> L = ['A', 'b', 'c', 'D']
&gt;&gt;&gt; L.sort()                # Case-sensitive sort
+
>>> L.sort()                # Case-sensitive sort
&gt;&gt;&gt; L
+
>>> L
 
['A', 'D', 'b', 'c']
 
['A', 'D', 'b', 'c']
&gt;&gt;&gt; # Using 'key' parameter to sort list
+
>>> # Using 'key' parameter to sort list
&gt;&gt;&gt; L.sort(key=lambda x: x.lower())
+
>>> L.sort(key=lambda x: x.lower())
&gt;&gt;&gt; L
+
>>> L
 
['A', 'b', 'c', 'D']
 
['A', 'b', 'c', 'D']
&gt;&gt;&gt; # Old-fashioned way
+
>>> # Old-fashioned way
&gt;&gt;&gt; L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
+
>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
&gt;&gt;&gt; L
+
>>> L
['A', 'b', 'c', 'D']</pre>
+
['A', 'b', 'c', 'D']</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The last example, which uses the ''cmp'' parameter, is the old way to perform a
+
<p>最后一个示例使用 ''cmp'' 参数,是执行不区分大小写排序的旧方法。 它可以工作,但比使用 ''key'' 参数慢。 使用 ''key'' 为列表中的每个元素调用一次 <code>lower()</code> 方法,而使用 ''cmp'' 将在每次比较时调用它两次,因此使用 ''key'' 节省在调用 <code>lower()</code> 方法时。</p>
case-insensitive sort. It works but is slower than using a ''key'' parameter.
+
<p>对于简单的键函数和比较函数,通常可以通过使用未绑定的方法来避免 [[../../reference/expressions#lambda|lambda]] 表达式。 例如,上面不区分大小写的排序最好写成:</p>
Using ''key'' calls <code>lower()</code> method once for each element in the list while
 
using ''cmp'' will call it twice for each comparison, so using ''key'' saves on
 
invocations of the <code>lower()</code> method.</p>
 
<p>For simple key functions and comparison functions, it is often possible to avoid
 
a [[../../reference/expressions#lambda|<code>lambda</code>]] expression by using an unbound method instead. For example,
 
the above case-insensitive sort is best written as:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; L.sort(key=str.lower)
+
<syntaxhighlight lang="python3">>>> L.sort(key=str.lower)
&gt;&gt;&gt; L
+
>>> L
['A', 'b', 'c', 'D']</pre>
+
['A', 'b', 'c', 'D']</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Finally, the ''reverse'' parameter takes a Boolean value. If the value is true,
+
<p>最后,''reverse'' 参数采用布尔值。 如果值为 true,则列表将按相反顺序排序。 您现在可以编写 <code>L.sort(reverse=True)</code>,而不是 <code>L.sort(); L.reverse()</code></p>
the list will be sorted into reverse order. Instead of <code>L.sort(); L.reverse()</code>, you can now write <code>L.sort(reverse=True)</code>.</p>
+
<p>现在保证排序的结果是稳定的。 这意味着具有相同键的两个条目将按照与输入相同的顺序返回。 例如,您可以按姓名对人员列表进行排序,然后按年龄对列表进行排序,从而得到按年龄排序的列表,其中年龄相同的人员按姓名排序。</p>
<p>The results of sorting are now guaranteed to be stable. This means that two
+
<p>(对 <code>sort()</code> 的所有更改均由 Raymond Hettinger 提供。)</p></li>
entries with equal keys will be returned in the same order as they were input.
+
<li><p>有一个新的内置函数 <code>sorted(iterable)</code>,其工作方式类似于就地 [[../../library/stdtypes#list|list.sort()]] 方法,但可以在表达式中使用。 区别在于:</p></li>
For example, you can sort a list of people by name, and then sort the list by
+
<li><p>输入可以是任何可迭代的;</p></li>
age, resulting in a list sorted by age where people with the same age are in
+
<li><p>对新形成的副本进行排序,原件完好无损; 和</p></li>
name-sorted order.</p>
+
<li><p>表达式返回新的排序副本</p>
<p>(All changes to <code>sort()</code> contributed by Raymond Hettinger.)</p></li>
 
<li><p>There is a new built-in function <code>sorted(iterable)</code> that works like the
 
in-place [[../../library/stdtypes#list|<code>list.sort()</code>]] method but can be used in expressions. The
 
differences are:</p></li>
 
<li><p>the input may be any iterable;</p></li>
 
<li><p>a newly formed copy is sorted, leaving the original intact; and</p></li>
 
<li><p>the expression returns the new sorted copy</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; L = [9,7,8,3,2,4,1,6,5]
+
<syntaxhighlight lang="python3">>>> L = [9,7,8,3,2,4,1,6,5]
&gt;&gt;&gt; [10+i for i in sorted(L)]      # usable in a list comprehension
+
>>> [10+i for i in sorted(L)]      # usable in a list comprehension
 
[11, 12, 13, 14, 15, 16, 17, 18, 19]
 
[11, 12, 13, 14, 15, 16, 17, 18, 19]
&gt;&gt;&gt; L                              # original is left unchanged
+
>>> L                              # original is left unchanged
 
[9,7,8,3,2,4,1,6,5]
 
[9,7,8,3,2,4,1,6,5]
&gt;&gt;&gt; sorted('Monty Python')          # any iterable may be an input
+
>>> sorted('Monty Python')          # any iterable may be an input
 
[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']
 
[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']
  
&gt;&gt;&gt; # List the contents of a dict sorted by key values
+
>>> # List the contents of a dict sorted by key values
&gt;&gt;&gt; colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
+
>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
&gt;&gt;&gt; for k, v in sorted(colormap.iteritems()):
+
>>> for k, v in sorted(colormap.iteritems()):
 
...    print k, v
 
...    print k, v
 
...
 
...
第1,100行: 第879行:
 
green 3
 
green 3
 
red 1
 
red 1
yellow 5</pre>
+
yellow 5</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>(Contributed by Raymond Hettinger.)</p></li>
+
<p>(雷蒙德·赫廷格供稿。)</p></li>
<li><p>Integer operations will no longer trigger an <code>OverflowWarning</code>. The
+
<li><p>整数运算将不再触发 <code>OverflowWarning</code><code>OverflowWarning</code> 警告将在 Python 2.5 中消失。</p></li>
<code>OverflowWarning</code> warning will disappear in Python 2.5.</p></li>
+
<li><p>解释器获得了一个新的开关,[[../../using/cmdline#cmdoption-m|-m]],它接受一个名称,在 <code>sys.path</code> 上搜索相应的模块,并将该模块作为脚本运行。 例如,您现在可以使用 <code>python -m profile</code> 运行 Python 分析器。 (由尼克·科格兰提供。)</p></li>
<li><p>The interpreter gained a new switch, [[../../using/cmdline#cmdoption-m|<code>-m</code>]], that takes a name, searches
+
<li><p><code>eval(expr, globals, locals)</code> <code>execfile(filename, globals, locals)</code> 函数以及 <code>exec</code> 语句现在接受 ''locals'' 参数的任何映射类型。 以前这必须是一个普通的 Python 字典。 (雷蒙德·赫廷格供稿。)</p></li>
for the corresponding module on <code>sys.path</code>, and runs the module as a script.
+
<li><p>[[../../library/functions#zip|zip()]] 内置函数和 <code>itertools.izip()</code> 现在在不带参数调用时返回一个空列表。 以前他们提出了 [[../../library/exceptions#TypeError|TypeError]] 异常。 这使它们更适合与可变长度参数列表一起使用:</p>
For example, you can now run the Python profiler with <code>python -m profile</code>.
 
(Contributed by Nick Coghlan.)</p></li>
 
<li><p>The <code>eval(expr, globals, locals)</code> and <code>execfile(filename, globals, locals)</code> functions and the <code>exec</code> statement now accept any mapping type
 
for the ''locals'' parameter. Previously this had to be a regular Python
 
dictionary. (Contributed by Raymond Hettinger.)</p></li>
 
<li><p>The [[../../library/functions#zip|<code>zip()</code>]] built-in function and <code>itertools.izip()</code> now return an
 
empty list if called with no arguments. Previously they raised a
 
[[../../library/exceptions#TypeError|<code>TypeError</code>]] exception. This makes them more suitable for use with variable
 
length argument lists:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; def transpose(array):
+
<syntaxhighlight lang="python3">>>> def transpose(array):
 
...    return zip(*array)
 
...    return zip(*array)
 
...
 
...
&gt;&gt;&gt; transpose([(1,2,3), (4,5,6)])
+
>>> transpose([(1,2,3), (4,5,6)])
 
[(1, 4), (2, 5), (3, 6)]
 
[(1, 4), (2, 5), (3, 6)]
&gt;&gt;&gt; transpose([])
+
>>> transpose([])
[]</pre>
+
[]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>(Contributed by Raymond Hettinger.)</p></li>
+
<p>(雷蒙德·赫廷格供稿。)</p></li>
<li><p>Encountering a failure while importing a module no longer leaves a partially-initialized
+
<li><p>导入模块时遇到失败不再在 <code>sys.modules</code> 中留下部分初始化的模块对象。 留下的不完整模块对象会欺骗相同模块的进一步导入,从而导致混淆错误。 (由蒂姆·彼得斯修正。)</p></li>
module object in <code>sys.modules</code>. The incomplete module object left
+
<li><p>[[../../library/constants#None|None]] 现在是一个常数; 将新值绑定到名称 <code>None</code> 的代码现在是一个语法错误。 (雷蒙德·赫廷格供稿。)</p></li></ul>
behind would fool further imports of the same module into succeeding, leading to
 
confusing errors. (Fixed by Tim Peters.)</p></li>
 
<li><p>[[../../library/constants#None|<code>None</code>]] is now a constant; code that binds a new value to the name
 
<code>None</code> is now a syntax error. (Contributed by Raymond Hettinger.)</p></li></ul>
 
  
 
<div id="optimizations" class="section">
 
<div id="optimizations" class="section">
  
=== Optimizations ===
+
=== 优化 ===
  
* The inner loops for list and tuple slicing were optimized and now run about one-third faster. The inner loops for dictionaries were also optimized, resulting in performance boosts for <code>keys()</code>, <code>values()</code>, <code>items()</code>, <code>iterkeys()</code>, <code>itervalues()</code>, and <code>iteritems()</code>. (Contributed by Raymond Hettinger.)
+
* 列表和元组切片的内部循环得到了优化,现在运行速度提高了大约三分之一。 字典的内部循环也得到了优化,从而提高了 <code>keys()</code><code>values()</code><code>items()</code><code>iterkeys()</code><code>itervalues()</code> <code>iteritems()</code>。 (雷蒙德·赫廷格供稿。)
* The machinery for growing and shrinking lists was optimized for speed and for space efficiency. Appending and popping from lists now runs faster due to more efficient code paths and less frequent use of the underlying system <code>realloc()</code>. List comprehensions also benefit. <code>list.extend()</code> was also optimized and no longer converts its argument into a temporary list before extending the base list. (Contributed by Raymond Hettinger.)
+
* 增长和缩小列表的机制针对速度和空间效率进行了优化。 由于更高效的代码路径和更少使用底层系统 <code>realloc()</code>,从列表中追加和弹出现在运行得更快。 列表理解也有好处。 <code>list.extend()</code> 也进行了优化,在扩展基本列表之前不再将其参数转换为临时列表。 (雷蒙德·赫廷格供稿。)
* [[../../library/stdtypes#list|<code>list()</code>]], [[../../library/stdtypes#tuple|<code>tuple()</code>]], [[../../library/functions#map|<code>map()</code>]], [[../../library/functions#filter|<code>filter()</code>]], and [[../../library/functions#zip|<code>zip()</code>]] now run several times faster with non-sequence arguments that supply a <code>__len__()</code> method. (Contributed by Raymond Hettinger.)
+
* [[../../library/stdtypes#list|list()]][[../../library/stdtypes#tuple|tuple()]][[../../library/functions#map|map()]][[../../library/functions#filter|filter()]][[../../library/functions#zip|zip()]]现在使用提供 <code>__len__()</code> 方法的非序列参数运行速度提高数倍。 (雷蒙德·赫廷格供稿。)
* The methods <code>list.__getitem__()</code>, <code>dict.__getitem__()</code>, and <code>dict.__contains__()</code> are now implemented as <code>method_descriptor</code> objects rather than <code>wrapper_descriptor</code> objects. This form of access doubles their performance and makes them more suitable for use as arguments to functionals: <code>map(mydict.__getitem__, keylist)</code>. (Contributed by Raymond Hettinger.)
+
* 方法 <code>list.__getitem__()</code><code>dict.__getitem__()</code> <code>dict.__contains__()</code> 现在被实现为 <code>method_descriptor</code> 对象而不是 <code>wrapper_descriptor</code> 对象。 这种访问形式使它们的性能翻倍,并使它们更适合用作函数的参数:<code>map(mydict.__getitem__, keylist)</code>。 (雷蒙德·赫廷格供稿。)
* Added a new opcode, <code>LIST_APPEND</code>, that simplifies the generated bytecode for list comprehensions and speeds them up by about a third. (Contributed by Raymond Hettinger.)
+
* 添加了一个新的操作码 <code>LIST_APPEND</code>,它简化了列表推导式生成的字节码,并将它们的速度提高了大约三分之一。 (雷蒙德·赫廷格供稿。)
* The peephole bytecode optimizer has been improved to produce shorter, faster bytecode; remarkably, the resulting bytecode is more readable. (Enhanced by Raymond Hettinger.)
+
* 窥视孔字节码优化器已得到改进,以生成更短、更快的字节码; 值得注意的是,生成的字节码更具可读性。 (由 Raymond Hettinger 增强。)
* String concatenations in statements of the form <code>s = s + &quot;abc&quot;</code> and <code>s += &quot;abc&quot;</code> are now performed more efficiently in certain circumstances. This optimization won't be present in other Python implementations such as Jython, so you shouldn't rely on it; using the <code>join()</code> method of strings is still recommended when you want to efficiently glue a large number of strings together. (Contributed by Armin Rigo.)
+
* 在某些情况下,现在可以更有效地执行 <code>s = s + &quot;abc&quot;</code> <code>s += &quot;abc&quot;</code> 形式的语句中的字符串连接。 这种优化不会出现在其他 Python 实现(例如 Jython)中,因此您不应依赖它; 当您想有效地将大量字符串粘合在一起时,仍然建议使用字符串的 <code>join()</code> 方法。 (由 Armin Rigo 提供。)
  
The net result of the 2.4 optimizations is that Python 2.4 runs the pystone
+
2.4 优化的最终结果是 Python 2.4 运行的 pystone 基准测试比 Python 2.3 高 5% faster,比 Python 2.2 高 35% faster。 (pystone 不是一个特别好的基准,但它是 Python 性能最常用的衡量标准。 您自己的应用程序可能会从 Python 2.4 中显示出或多或少的好处。)
benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2.
 
(pystone is not a particularly good benchmark, but it's the most commonly used
 
measurement of Python's performance. Your own applications may show greater or
 
smaller benefits from Python 2.4.)
 
  
  
第1,166行: 第928行:
 
<div id="new-improved-and-deprecated-modules" class="section">
 
<div id="new-improved-and-deprecated-modules" class="section">
  
== New, Improved, and Deprecated Modules ==
+
== 新的、改进的和弃用的模块 ==
  
As usual, Python's standard library received a number of enhancements and bug
+
像往常一样,Python 的标准库得到了许多增强和错误修复。 这是最显着更改的部分列表,按模块名称的字母顺序排序。 请查阅源代码树中的 <code>Misc/NEWS</code> 文件以获取更完整的更改列表,或查看 CVS 日志以获取所有详细信息。
fixes. Here's a partial list of the most notable changes, sorted alphabetically
 
by module name. Consult the <code>Misc/NEWS</code> file in the source tree for a more
 
complete list of changes, or look through the CVS logs for all the details.
 
  
 
<ul>
 
<ul>
<li><p>The [[../../library/asyncore#module-asyncore|<code>asyncore</code>]] module's <code>loop()</code> function now has a ''count'' parameter
+
<li><p>[[../../library/asyncore#module-asyncore|asyncore]] 模块的 <code>loop()</code> 函数现在具有 ''count'' 参数,可让您通过轮询循环执行有限次数的传递。 默认仍然是永远循环。</p></li>
that lets you perform a limited number of passes through the polling loop. The
+
<li><p>[[../../library/base64#module-base64|base64]] 模块现在有更完整的 <span id="index-18" class="target"></span>[https://tools.ietf.org/html/rfc3548.html RFC 3548] 支持 Base64、Base32 和 Base16 编码和解码,包括可选的大小写折叠和可选的替代字母表。 (由巴里华沙提供。)</p></li>
default is still to loop forever.</p></li>
+
<li><p>[[../../library/bisect#module-bisect|bisect]] 模块现在具有底层 C 实现以提高性能。 (德米特里·瓦西里耶夫供稿。)</p></li>
<li><p>The [[../../library/base64#module-base64|<code>base64</code>]] module now has more complete <span id="index-18" class="target"></span>[https://tools.ietf.org/html/rfc3548.html '''RFC 3548'''] support for Base64,
+
<li><p>Hye-Shik Chang 维护的东亚编解码器的 CJKCodecs 集合已集成到 2.4 中。 新的编码是:</p></li>
Base32, and Base16 encoding and decoding, including optional case folding and
+
<li><p>中文(中国):gb2312、gbk、gb18030、big5hkscs、hz</p></li>
optional alternative alphabets. (Contributed by Barry Warsaw.)</p></li>
+
<li><p>中文 (ROC): big5, cp950</p></li>
<li><p>The [[../../library/bisect#module-bisect|<code>bisect</code>]] module now has an underlying C implementation for improved
 
performance. (Contributed by Dmitry Vasiliev.)</p></li>
 
<li><p>The CJKCodecs collections of East Asian codecs, maintained by Hye-Shik Chang,
 
was integrated into 2.4. The new encodings are:</p></li>
 
<li><p>Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz</p></li>
 
<li><p>Chinese (ROC): big5, cp950</p></li>
 
 
<li><dl>
 
<li><dl>
<dt>Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,</dt>
+
<dt>日语:cp932、euc-jis-2004、euc-jp、euc-jisx0213、iso-2022-jp、</dt>
<dd><p>iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
+
<dd><p>iso-2022-jp-1、iso-2022-jp-2、iso-2022-jp-3、iso-2022-jp-ext、iso-2022-jp-2004、shift-jis、shift-jisx0213、shift- jis-2004</p></dd></dl>
shift-jis, shift-jisx0213, shift-jis-2004</p></dd></dl>
 
 
</li>
 
</li>
<li><p>Korean: cp949, euc-kr, johab, iso-2022-kr</p></li>
+
<li><p>韩语:cp949、euc-kr、johab、iso-2022-kr</p></li>
<li><p>Some other new encodings were added: HP Roman8, ISO_8859-11, ISO_8859-16,
+
<li><p>添加了其他一些新编码:HP Roman8、ISO_8859-11、ISO_8859-16、PCTP-154 TIS-620。</p></li>
PCTP-154, and TIS-620.</p></li>
+
<li><p>UTF-8 UTF-16 编解码器现在可以更好地接收部分输入。 以前,<code>StreamReader</code> 类会尝试读取更多数据,从而无法从流中恢复解码。 <code>read()</code> 方法现在将返回尽可能多的数据,并且未来的调用将在前一个中断的地方继续解码。 (由 Walter Dörwald 实施。)</p></li>
<li><p>The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
+
<li><p>有一个新的 [[../../library/collections#module-collections|collections]] 模块用于各种专门的集合数据类型。 目前它只包含一种类型,<code>deque</code>,一个双端队列,支持从任一端有效地添加和删除元素:</p>
Previously the <code>StreamReader</code> class would try to read more data, making
 
it impossible to resume decoding from the stream. The <code>read()</code> method will
 
now return as much data as it can and future calls will resume decoding where
 
previous ones left off. (Implemented by Walter Dörwald.)</p></li>
 
<li><p>There is a new [[../../library/collections#module-collections|<code>collections</code>]] module for various specialized collection
 
datatypes. Currently it contains just one type, <code>deque</code>, a double-ended
 
queue that supports efficiently adding and removing elements from either
 
end:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; from collections import deque
+
<syntaxhighlight lang="python3">>>> from collections import deque
&gt;&gt;&gt; d = deque('ghi')        # make a new deque with three items
+
>>> d = deque('ghi')        # make a new deque with three items
&gt;&gt;&gt; d.append('j')          # add a new entry to the right side
+
>>> d.append('j')          # add a new entry to the right side
&gt;&gt;&gt; d.appendleft('f')      # add a new entry to the left side
+
>>> d.appendleft('f')      # add a new entry to the left side
&gt;&gt;&gt; d                      # show the representation of the deque
+
>>> d                      # show the representation of the deque
 
deque(['f', 'g', 'h', 'i', 'j'])
 
deque(['f', 'g', 'h', 'i', 'j'])
&gt;&gt;&gt; d.pop()                # return and remove the rightmost item
+
>>> d.pop()                # return and remove the rightmost item
 
'j'
 
'j'
&gt;&gt;&gt; d.popleft()            # return and remove the leftmost item
+
>>> d.popleft()            # return and remove the leftmost item
 
'f'
 
'f'
&gt;&gt;&gt; list(d)                # list the contents of the deque
+
>>> list(d)                # list the contents of the deque
 
['g', 'h', 'i']
 
['g', 'h', 'i']
&gt;&gt;&gt; 'h' in d                # search the deque
+
>>> 'h' in d                # search the deque
True</pre>
+
True</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Several modules, such as the <code>Queue</code> and [[../../library/threading#module-threading|<code>threading</code>]] modules, now take
+
<p>几个模块,例如 <code>Queue</code> [[../../library/threading#module-threading|threading]] 模块,现在利用 [[../../library/collections#collections|collections.deque]] 来提高性能。 (雷蒙德·赫廷格供稿。)</p></li>
advantage of [[../../library/collections#collections|<code>collections.deque</code>]] for improved performance. (Contributed
+
<li><p><code>ConfigParser</code> 类已略有增强。 <code>read()</code> 方法现在返回已成功解析的文件列表,如果传递 ''值'' ,[[../../library/stdtypes#set|set()]] 方法会引发 [[../../library/exceptions#TypeError|TypeError]]不是字符串的参数。 (由约翰贝尔蒙特和大卫古德提供。)</p></li>
by Raymond Hettinger.)</p></li>
+
<li><p>[[../../library/curses#module-curses|curses]] 模块现在支持 ncurses 扩展 <code>use_default_colors()</code>。 在终端支持透明的平台上,这使得使用透明背景成为可能。 (约尔格·莱曼供稿。)</p></li>
<li><p>The <code>ConfigParser</code> classes have been enhanced slightly. The <code>read()</code>
+
<li><p>[[../../library/difflib#module-difflib|difflib]] 模块现在包含一个 <code>HtmlDiff</code> 类,该类创建一个 HTML 表格,显示文本的两个版本的并排比较。 (丹·加斯供稿。)</p></li>
method now returns a list of the files that were successfully parsed, and the
+
<li><p>[[../../library/email#module-email|email]] 包已更新到 3.0 版,它删除了各种已弃用的 API,并取消了对 2.3 之前的 Python 版本的支持。 该包的 3.0 版本使用新的 MIME 消息增量解析器,可在 <code>email.FeedParser</code> 模块中使用。 新的解析器不需要将整个消息读入内存,并且如果消息格式错误也不会引发异常; 相反,它会在消息的 <code>defect</code> 属性中记录任何问题。 (由 Anthony Baxter、Barry Warsaw、Thomas Wouters 等开发。)</p></li>
[[../../library/stdtypes#set|<code>set()</code>]] method raises [[../../library/exceptions#TypeError|<code>TypeError</code>]] if passed a ''value'' argument that
+
<li><p>[[../../library/heapq#module-heapq|heapq]] 模块已转换为 C。 由此带来的十倍速度提升使该模块适用于处理大量数据。 此外,该模块还有两个新函数 <code>nlargest()</code> <code>nsmallest()</code>,它们使用堆来查找数据集中的 N 个最大值或最小值,而无需进行完整排序。 (雷蒙德·赫廷格供稿。)</p></li>
isn't a string. (Contributed by John Belmonte and David Goodger.)</p></li>
+
<li><p><code>httplib</code> 模块现在包含在各种与 HTTP 相关的 RFC 文档中定义的 HTTP 状态代码的常量。 常量的名称有 <code>OK</code><code>CREATED</code><code>CONTINUE</code> <code>MOVED_PERMANENTLY</code>; 使用 pydoc 获取完整列表。 (由安德鲁·埃兰提供。)</p></li>
<li><p>The [[../../library/curses#module-curses|<code>curses</code>]] module now supports the ncurses extension
+
<li><p>[[../../library/imaplib#module-imaplib|imaplib]] 模块现在支持 IMAP THREAD 命令(由 Yves Dionne 提供)和新的 <code>deleteacl()</code> <code>myrights()</code> 方法(由 Arnaud Mazin 提供)。</p></li>
<code>use_default_colors()</code>. On platforms where the terminal supports
+
<li><p>[[../../library/itertools#module-itertools|itertools]] 模块获得了 <code>groupby(iterable[, *func*])</code> 功能。 ''iterable'' 是可以迭代返回元素流的东西,可选的 ''func'' 参数是一个函数,它接受一个元素并返回一个键值; 如果省略,键就是元素本身。 <code>groupby()</code> 然后将元素分组为具有匹配键值的子序列,并返回一系列包含键值和子序列迭代器的 2 元组。</p>
transparency, this makes it possible to use a transparent background.
+
<p>这是一个更清楚的例子。 ''key'' 函数只返回一个数字是偶数还是奇数,所以 <code>groupby()</code> 的结果是返回连续运行的奇数或偶数。</p>
(Contributed by Jörg Lehmann.)</p></li>
 
<li><p>The [[../../library/difflib#module-difflib|<code>difflib</code>]] module now includes an <code>HtmlDiff</code> class that creates
 
an HTML table showing a side by side comparison of two versions of a text.
 
(Contributed by Dan Gass.)</p></li>
 
<li><p>The [[../../library/email#module-email|<code>email</code>]] package was updated to version 3.0, which dropped various
 
deprecated APIs and removes support for Python versions earlier than 2.3. The
 
3.0 version of the package uses a new incremental parser for MIME messages,
 
available in the <code>email.FeedParser</code> module. The new parser doesn't require
 
reading the entire message into memory, and doesn't raise exceptions if a
 
message is malformed; instead it records any problems in the <code>defect</code>
 
attribute of the message. (Developed by Anthony Baxter, Barry Warsaw, Thomas
 
Wouters, and others.)</p></li>
 
<li><p>The [[../../library/heapq#module-heapq|<code>heapq</code>]] module has been converted to C. The resulting tenfold
 
improvement in speed makes the module suitable for handling high volumes of
 
data. In addition, the module has two new functions <code>nlargest()</code> and
 
<code>nsmallest()</code> that use heaps to find the N largest or smallest values in a
 
dataset without the expense of a full sort. (Contributed by Raymond Hettinger.)</p></li>
 
<li><p>The <code>httplib</code> module now contains constants for HTTP status codes defined
 
in various HTTP-related RFC documents. Constants have names such as
 
<code>OK</code>, <code>CREATED</code>, <code>CONTINUE</code>, and
 
<code>MOVED_PERMANENTLY</code>; use pydoc to get a full list. (Contributed by
 
Andrew Eland.)</p></li>
 
<li><p>The [[../../library/imaplib#module-imaplib|<code>imaplib</code>]] module now supports IMAP's THREAD command (contributed by
 
Yves Dionne) and new <code>deleteacl()</code> and <code>myrights()</code> methods (contributed
 
by Arnaud Mazin).</p></li>
 
<li><p>The [[../../library/itertools#module-itertools|<code>itertools</code>]] module gained a <code>groupby(iterable[, *func*])</code>
 
function. ''iterable'' is something that can be iterated over to return a stream
 
of elements, and the optional ''func'' parameter is a function that takes an
 
element and returns a key value; if omitted, the key is simply the element
 
itself. <code>groupby()</code> then groups the elements into subsequences which have
 
matching values of the key, and returns a series of 2-tuples containing the key
 
value and an iterator over the subsequence.</p>
 
<p>Here's an example to make this clearer. The ''key'' function simply returns
 
whether a number is even or odd, so the result of <code>groupby()</code> is to return
 
consecutive runs of odd or even numbers.</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import itertools
+
<syntaxhighlight lang="python3">>>> import itertools
&gt;&gt;&gt; L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
+
>>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
&gt;&gt;&gt; for key_val, it in itertools.groupby(L, lambda x: x % 2):
+
>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
 
...    print key_val, list(it)
 
...    print key_val, list(it)
 
...
 
...
第1,284行: 第993行:
 
1 [9, 11]
 
1 [9, 11]
 
0 [12, 14]
 
0 [12, 14]
&gt;&gt;&gt;</pre>
+
>>></syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p><code>groupby()</code> is typically used with sorted input. The logic for
+
<p><code>groupby()</code> 通常与排序输入一起使用。 <code>groupby()</code> 的逻辑类似于 Unix <code>uniq</code> 过滤器,这使得它可以方便地消除、计数或识别重复元素:</p>
<code>groupby()</code> is similar to the Unix <code>uniq</code> filter which makes it handy for
 
eliminating, counting, or identifying duplicate elements:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; word = 'abracadabra'
+
<syntaxhighlight lang="python3">>>> word = 'abracadabra'
&gt;&gt;&gt; letters = sorted(word)  # Turn string into a sorted list of letters
+
>>> letters = sorted(word)  # Turn string into a sorted list of letters
&gt;&gt;&gt; letters
+
>>> letters
 
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
 
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
&gt;&gt;&gt; for k, g in itertools.groupby(letters):
+
>>> for k, g in itertools.groupby(letters):
 
...    print k, list(g)
 
...    print k, list(g)
 
...
 
...
第1,308行: 第1,015行:
 
d ['d']
 
d ['d']
 
r ['r', 'r']
 
r ['r', 'r']
&gt;&gt;&gt; # List unique letters
+
>>> # List unique letters
&gt;&gt;&gt; [k for k, g in groupby(letters)]
+
>>> [k for k, g in groupby(letters)]
 
['a', 'b', 'c', 'd', 'r']
 
['a', 'b', 'c', 'd', 'r']
&gt;&gt;&gt; # Count letter occurrences
+
>>> # Count letter occurrences
&gt;&gt;&gt; [(k, len(list(g))) for k, g in groupby(letters)]
+
>>> [(k, len(list(g))) for k, g in groupby(letters)]
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]</pre>
+
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>(Contributed by Hye-Shik Chang.)</p></li>
+
<p>(由 Hye-Shik Chang 提供。)</p></li>
<li><p>[[../../library/itertools#module-itertools|<code>itertools</code>]] also gained a function named <code>tee(iterator, N)</code> that
+
<li><p>[[../../library/itertools#module-itertools|itertools]] 还获得了一个名为 <code>tee(iterator, N)</code> 的函数,该函数返回复制 ''iterator'' ''N'' 独立迭代器。 如果省略 ''N'',则默认为 2。</p>
returns ''N'' independent iterators that replicate ''iterator''. If ''N'' is omitted,
 
the default is 2.</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; L = [1,2,3]
+
<syntaxhighlight lang="python3">>>> L = [1,2,3]
&gt;&gt;&gt; i1, i2 = itertools.tee(L)
+
>>> i1, i2 = itertools.tee(L)
&gt;&gt;&gt; i1,i2
+
>>> i1,i2
(&lt;itertools.tee object at 0x402c2080&gt;, &lt;itertools.tee object at 0x402c2090&gt;)
+
(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
&gt;&gt;&gt; list(i1)              # Run the first iterator to exhaustion
+
>>> list(i1)              # Run the first iterator to exhaustion
 
[1, 2, 3]
 
[1, 2, 3]
&gt;&gt;&gt; list(i2)              # Run the second iterator to exhaustion
+
>>> list(i2)              # Run the second iterator to exhaustion
[1, 2, 3]</pre>
+
[1, 2, 3]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Note that <code>tee()</code> has to keep copies of the values returned by the
+
<p>请注意, <code>tee()</code> 必须保留迭代器返回值的副本; 在最坏的情况下,它可能需要保留所有这些。 因此,如果前导迭代器可以在长输入流中远远领先于尾随迭代器,则应谨慎使用此方法。 如果间隔很大,那么您不妨使用 [[../../library/stdtypes#list|list()]] 代替。 当迭代器彼此紧密跟踪时,<code>tee()</code> 是理想的。 可能的应用包括书签、窗口化或前瞻迭代器。 (雷蒙德·赫廷格供稿。)</p></li>
iterator; in the worst case, it may need to keep all of them. This should
+
<li><p>许多函数被添加到 [[../../library/locale#module-locale|locale]] 模块,例如 <code>bind_textdomain_codeset()</code> 指定特定编码和一系列 <code>l*gettext()</code> 函数,以所选编码返回消息。 (古斯塔沃·尼迈耶供稿。)</p></li>
therefore be used carefully if the leading iterator can run far ahead of the
+
<li><p>[[../../library/logging#module-logging|logging]] 包的 <code>basicConfig()</code> 函数中添加了一些关键字参数以简化日志配置。 默认行为是将消息记录到标准错误,但可以指定各种关键字参数以记录到特定文件、更改日志记录格式或设置日志记录级别。 例如:</p>
trailing iterator in a long stream of inputs. If the separation is large, then
 
you might as well use [[../../library/stdtypes#list|<code>list()</code>]] instead. When the iterators track closely
 
with one another, <code>tee()</code> is ideal. Possible applications include
 
bookmarking, windowing, or lookahead iterators. (Contributed by Raymond
 
Hettinger.)</p></li>
 
<li><p>A number of functions were added to the [[../../library/locale#module-locale|<code>locale</code>]] module, such as
 
<code>bind_textdomain_codeset()</code> to specify a particular encoding and a family of
 
<code>l*gettext()</code> functions that return messages in the chosen encoding.
 
(Contributed by Gustavo Niemeyer.)</p></li>
 
<li><p>Some keyword arguments were added to the [[../../library/logging#module-logging|<code>logging</code>]] package's
 
<code>basicConfig()</code> function to simplify log configuration. The default
 
behavior is to log messages to standard error, but various keyword arguments can
 
be specified to log to a particular file, change the logging format, or set the
 
logging level. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import logging
+
<syntaxhighlight lang="python3">import logging
 
logging.basicConfig(filename='/var/log/application.log',
 
logging.basicConfig(filename='/var/log/application.log',
 
     level=0,  # Log all messages
 
     level=0,  # Log all messages
     format='%(levelname):%(process):%(thread):%(message)')</pre>
+
     format='%(levelname):%(process):%(thread):%(message)')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Other additions to the [[../../library/logging#module-logging|<code>logging</code>]] package include a <code>log(level, msg)</code>
+
<p>[[../../library/logging#module-logging|logging]] 包的其他新增功能包括 <code>log(level, msg)</code> 便利方法,以及按时间间隔轮换其日志文件的 <code>TimedRotatingFileHandler</code> 类。 该模块已经有 <code>RotatingFileHandler</code>,一旦文件超过一定大小,它就会轮换日志。 这两个类都源自一个新的 <code>BaseRotatingHandler</code> 类,该类可用于实现其他旋转处理程序。</p>
convenience method, as well as a <code>TimedRotatingFileHandler</code> class that
+
<p>(由 Vinay Sajip 实施的更改。)</p></li>
rotates its log files at a timed interval. The module already had
+
<li><p>[[../../library/marshal#module-marshal|marshal]] 模块现在在解包数据结构时共享内部字符串。 这可能会缩小某些 pickle 字符串的大小,但主要效果是使 <code>.pyc</code> 文件明显更小。 (由 Martin von Löwis 提供。)</p></li>
<code>RotatingFileHandler</code>, which rotated logs once the file exceeded a
+
<li><p>[[../../library/nntplib#module-nntplib|nntplib]] 模块的 <code>NNTP</code> 类获得了 <code>description()</code> <code>descriptions()</code> 方法来检索单个组或一系列组的新闻组描述。 (由 Jürgen A. 艾哈德。)</p></li>
certain size. Both classes derive from a new <code>BaseRotatingHandler</code> class
+
<li><p>[[../../library/operator#module-operator|operator]]模块增加了两个新功能,<code>attrgetter(attr)</code><code>itemgetter(index)</code>。 这两个函数都返回带有单个参数并返回相应属性或项目的可调用对象; 当与 [[../../library/functions#map|map()]] [[../../library/functions#sorted|sorted()]] 一起使用时,这些可调用函数成为出色的数据提取器。 例如:</p>
that can be used to implement other rotating handlers.</p>
 
<p>(Changes implemented by Vinay Sajip.)</p></li>
 
<li><p>The [[../../library/marshal#module-marshal|<code>marshal</code>]] module now shares interned strings on unpacking a data
 
structure. This may shrink the size of certain pickle strings, but the primary
 
effect is to make <code>.pyc</code> files significantly smaller. (Contributed by
 
Martin von Löwis.)</p></li>
 
<li><p>The [[../../library/nntplib#module-nntplib|<code>nntplib</code>]] module's <code>NNTP</code> class gained <code>description()</code> and
 
<code>descriptions()</code> methods to retrieve newsgroup descriptions for a single
 
group or for a range of groups. (Contributed by Jürgen A. Erhard.)</p></li>
 
<li><p>Two new functions were added to the [[../../library/operator#module-operator|<code>operator</code>]] module,
 
<code>attrgetter(attr)</code> and <code>itemgetter(index)</code>. Both functions return
 
callables that take a single argument and return the corresponding attribute or
 
item; these callables make excellent data extractors when used with [[../../library/functions#map|<code>map()</code>]]
 
or [[../../library/functions#sorted|<code>sorted()</code>]]. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
+
<syntaxhighlight lang="python3">>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
&gt;&gt;&gt; map(operator.itemgetter(0), L)
+
>>> map(operator.itemgetter(0), L)
 
['c', 'd', 'a', 'b']
 
['c', 'd', 'a', 'b']
&gt;&gt;&gt; map(operator.itemgetter(1), L)
+
>>> map(operator.itemgetter(1), L)
 
[2, 1, 4, 3]
 
[2, 1, 4, 3]
&gt;&gt;&gt; sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
+
>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]</pre>
+
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>(Contributed by Raymond Hettinger.)</p></li>
+
<p>(雷蒙德·赫廷格供稿。)</p></li>
<li><p>The [[../../library/optparse#module-optparse|<code>optparse</code>]] module was updated in various ways. The module now passes
+
<li><p>[[../../library/optparse#module-optparse|optparse]] 模块以各种方式更新。 该模块现在通过 [[../../library/gettext#gettext|gettext.gettext()]] 传递其消息,从而可以国际化 Optik 的帮助和错误消息。 选项的帮助消息现在可以包含字符串 <code>'%default'</code>,它将被选项的默认值替换。 (由格雷格·沃德提供。)</p></li>
its messages through [[../../library/gettext#gettext|<code>gettext.gettext()</code>]], making it possible to
+
<li><p>长期计划是在未来的 Python 版本中弃用 <code>rfc822</code> 模块,以支持 [[../../library/email#module-email|email]] 包。 为此,<code>email.Utils.formatdate()</code> 功能已更改,使其可用作 <code>rfc822.formatdate()</code> 的替代品。 考虑到这一点,您可能希望编写新的电子邮件处理代码。 (由 Anthony Baxter 实施的更改。)</p></li>
internationalize Optik's help and error messages. Help messages for options can
+
<li><p>一个新的 <code>urandom(n)</code> 函数被添加到 [[../../library/os#module-os|os]] 模块,返回一个包含 ''n'' 字节随机数据的字符串。 此函数提供对特定于平台的随机源的访问,例如 Linux 上的 <code>/dev/urandom</code> Windows CryptoAPI。 (由特雷弗·佩林提供。)</p></li>
now include the string <code>'%default'</code>, which will be replaced by the option's
+
<li><p>另一个新函数:如果 ''path'' 指定的文件存在,<code>os.path.lexists(path)</code> 返回 true,无论它是否是符号链接。 这与现有的 <code>os.path.exists(path)</code> 函数不同,如果 ''path'' 是指向不存在的目标的符号链接,则该函数返回 false。 (贝尼·切尔尼亚夫斯基供稿。)</p></li>
default value. (Contributed by Greg Ward.)</p></li>
+
<li><p>一个新的 <code>getsid()</code> 函数被添加到 [[../../library/os#module-os|os]] 模块下的 [[../../library/posix#module-posix|posix]] 模块中。 (由 J. 雷诺。)</p></li>
<li><p>The long-term plan is to deprecate the <code>rfc822</code> module in some future
+
<li><p>[[../../library/poplib#module-poplib|poplib]] 模块现在支持 POP over SSL。 (由赫克托·乌尔图比亚提供。)</p></li>
Python release in favor of the [[../../library/email#module-email|<code>email</code>]] package. To this end, the
+
<li><p>[[../../library/profile#module-profile|profile]] 模块现在可以分析 C 扩展函数。 (由尼克巴斯汀提供。)</p></li>
<code>email.Utils.formatdate()</code> function has been changed to make it usable as a
+
<li><p>[[../../library/random#module-random|random]] 模块有一个名为 <code>getrandbits(N)</code> 的新方法,它返回一个长度为 ''N'' 位的长整数。 现有的 <code>randrange()</code> 方法现在在适当的地方使用 <code>getrandbits()</code>,从而使任意大的随机数的生成更加高效。 (雷蒙德·赫廷格供稿。)</p></li>
replacement for <code>rfc822.formatdate()</code>. You may want to write new e-mail
+
<li><p>[[../../library/re#module-re|re]] 模块接受的正则表达式语言被扩展为简单的条件表达式,写为 <code>(?(group)A|B)</code>''group'' 是数字组 ID 或在表达式前面用 <code>(?P&lt;group&gt;...)</code> 定义的组名称。 如果指定的组匹配,则将针对字符串测试正则表达式模式 ''A''; 如果组不匹配,则将使用模式 ''B''。 (古斯塔沃·尼迈耶供稿。)</p></li>
processing code with this in mind. (Change implemented by Anthony Baxter.)</p></li>
+
<li><p>由于 Gustavo Niemeyer 的大量工作,[[../../library/re#module-re|re]] 模块也不再是递归的。 在递归正则表达式引擎中,某些模式会导致消耗大量 C 堆栈空间,并且可能会溢出堆栈。 例如,如果将 <code>a</code> 字符的 30000 字节字符串与表达式 <code>(a|b)+</code> 进行匹配,则每个字符消耗一个堆栈帧。 Python 2.3 尝试检查堆栈溢出并引发 [[../../library/exceptions#RuntimeError|RuntimeError]] 异常,但某些模式可能会回避检查,如果您不走运,Python 可能会出现段错误。 Python 2.4 的正则表达式引擎可以毫无问题地匹配这种模式。</p></li>
<li><p>A new <code>urandom(n)</code> function was added to the [[../../library/os#module-os|<code>os</code>]] module, returning
+
<li><p>[[../../library/signal#module-signal|signal]] 模块现在对 [[../../library/signal#signal|signal.signal()]] 函数的参数执行更严格的错误检查。 例如,您不能在 <code>SIGKILL</code> 信号上设置处理程序; 以前版本的 Python 会悄悄地接受这一点,但 2.4 会引发 [[../../library/exceptions#RuntimeError|RuntimeError]] 异常。</p></li>
a string containing ''n'' bytes of random data. This function provides access to
+
<li><p>[[../../library/socket#module-socket|socket]] 模块中添加了两个新函数。 <code>socketpair()</code> 返回一对连接的套接字,<code>getservbyport(port)</code> 查找给定端口号的服务名称。 (由 Dave Cole Barry Warsaw 提供。)</p></li>
platform-specific sources of randomness such as <code>/dev/urandom</code> on Linux or
+
<li><p><code>sys.exitfunc()</code> 函数已被弃用。 代码应该使用现有的 [[../../library/atexit#module-atexit|atexit]] 模块,它可以正确处理调用多个退出函数。 最终 <code>sys.exitfunc()</code> 将成为纯粹的内部接口,只能通过 [[../../library/atexit#module-atexit|atexit]] 访问。</p></li>
the Windows CryptoAPI. (Contributed by Trevor Perrin.)</p></li>
+
<li><p>[[../../library/tarfile#module-tarfile|tarfile]] 模块现在默认生成 GNU 格式的 tar 文件。 (拉尔斯·古斯塔贝尔供稿。)</p></li>
<li><p>Another new function: <code>os.path.lexists(path)</code> returns true if the file
+
<li><p>[[../../library/threading#module-threading|threading]] 模块现在有一种优雅简单的方法来支持线程本地数据。 该模块包含一个 <code>local</code> 类,其属性值对于不同的线程是本地的。</p>
specified by ''path'' exists, whether or not it's a symbolic link. This differs
 
from the existing <code>os.path.exists(path)</code> function, which returns false if
 
''path'' is a symlink that points to a destination that doesn't exist.
 
(Contributed by Beni Cherniavsky.)</p></li>
 
<li><p>A new <code>getsid()</code> function was added to the [[../../library/posix#module-posix|<code>posix</code>]] module that
 
underlies the [[../../library/os#module-os|<code>os</code>]] module. (Contributed by J. Raynor.)</p></li>
 
<li><p>The [[../../library/poplib#module-poplib|<code>poplib</code>]] module now supports POP over SSL. (Contributed by Hector
 
Urtubia.)</p></li>
 
<li><p>The [[../../library/profile#module-profile|<code>profile</code>]] module can now profile C extension functions. (Contributed
 
by Nick Bastin.)</p></li>
 
<li><p>The [[../../library/random#module-random|<code>random</code>]] module has a new method called <code>getrandbits(N)</code> that
 
returns a long integer ''N'' bits in length. The existing <code>randrange()</code>
 
method now uses <code>getrandbits()</code> where appropriate, making generation of
 
arbitrarily large random numbers more efficient. (Contributed by Raymond
 
Hettinger.)</p></li>
 
<li><p>The regular expression language accepted by the [[../../library/re#module-re|<code>re</code>]] module was extended
 
with simple conditional expressions, written as <code>(?(group)A|B)</code>. ''group'' is
 
either a numeric group ID or a group name defined with <code>(?P&lt;group&gt;...)</code>
 
earlier in the expression. If the specified group matched, the regular
 
expression pattern ''A'' will be tested against the string; if the group didn't
 
match, the pattern ''B'' will be used instead. (Contributed by Gustavo Niemeyer.)</p></li>
 
<li><p>The [[../../library/re#module-re|<code>re</code>]] module is also no longer recursive, thanks to a massive amount
 
of work by Gustavo Niemeyer. In a recursive regular expression engine, certain
 
patterns result in a large amount of C stack space being consumed, and it was
 
possible to overflow the stack. For example, if you matched a 30000-byte string
 
of <code>a</code> characters against the expression <code>(a|b)+</code>, one stack frame was
 
consumed per character. Python 2.3 tried to check for stack overflow and raise
 
a [[../../library/exceptions#RuntimeError|<code>RuntimeError</code>]] exception, but certain patterns could sidestep the
 
checking and if you were unlucky Python could segfault. Python 2.4's regular
 
expression engine can match this pattern without problems.</p></li>
 
<li><p>The [[../../library/signal#module-signal|<code>signal</code>]] module now performs tighter error-checking on the parameters
 
to the [[../../library/signal#signal|<code>signal.signal()</code>]] function. For example, you can't set a handler on
 
the <code>SIGKILL</code> signal; previous versions of Python would quietly accept
 
this, but 2.4 will raise a [[../../library/exceptions#RuntimeError|<code>RuntimeError</code>]] exception.</p></li>
 
<li><p>Two new functions were added to the [[../../library/socket#module-socket|<code>socket</code>]] module. <code>socketpair()</code>
 
returns a pair of connected sockets and <code>getservbyport(port)</code> looks up the
 
service name for a given port number. (Contributed by Dave Cole and Barry
 
Warsaw.)</p></li>
 
<li><p>The <code>sys.exitfunc()</code> function has been deprecated. Code should be using
 
the existing [[../../library/atexit#module-atexit|<code>atexit</code>]] module, which correctly handles calling multiple exit
 
functions. Eventually <code>sys.exitfunc()</code> will become a purely internal
 
interface, accessed only by [[../../library/atexit#module-atexit|<code>atexit</code>]].</p></li>
 
<li><p>The [[../../library/tarfile#module-tarfile|<code>tarfile</code>]] module now generates GNU-format tar files by default.
 
(Contributed by Lars Gustäbel.)</p></li>
 
<li><p>The [[../../library/threading#module-threading|<code>threading</code>]] module now has an elegantly simple way to support
 
thread-local data. The module contains a <code>local</code> class whose attribute
 
values are local to different threads.</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import threading
+
<syntaxhighlight lang="python3">import threading
  
 
data = threading.local()
 
data = threading.local()
 
data.number = 42
 
data.number = 42
data.url = ('www.python.org', 80)</pre>
+
data.url = ('www.python.org', 80)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Other threads can assign and retrieve their own values for the <code>number</code>
+
<p>其他线程可以为 <code>number</code> <code>url</code> 属性分配和检索它们自己的值。 您可以子类化 <code>local</code> 来初始化属性或添加方法。 (由吉姆富尔顿提供。)</p></li>
and <code>url</code> attributes. You can subclass <code>local</code> to initialize
+
<li><p>[[../../library/timeit#module-timeit|timeit]] 模块现在会在计时循环期间自动禁用定期垃圾收集。 此更改使连续计时更具可比性。 (雷蒙德·赫廷格供稿。)</p></li>
attributes or to add methods. (Contributed by Jim Fulton.)</p></li>
+
<li><p>[[../../library/weakref#module-weakref|weakref]] 模块现在支持更多种类的对象,包括 Python 函数、类实例、集合、冻结集、双端队列、数组、文件、套接字和正则表达式模式对象。 (雷蒙德·赫廷格供稿。)</p></li>
<li><p>The [[../../library/timeit#module-timeit|<code>timeit</code>]] module now automatically disables periodic garbage
+
<li><p><code>xmlrpclib</code> 模块现在支持多调用扩展,用于在单个 HTTP 操作中传输多个 XML-RPC 调用。 (由布赖恩昆兰提供。)</p></li>
collection during the timing loop. This change makes consecutive timings more
+
<li><p><code>mpz</code><code>rotor</code> <code>xreadlines</code> 模块已被移除。</p></li></ul>
comparable. (Contributed by Raymond Hettinger.)</p></li>
 
<li><p>The [[../../library/weakref#module-weakref|<code>weakref</code>]] module now supports a wider variety of objects including
 
Python functions, class instances, sets, frozensets, deques, arrays, files,
 
sockets, and regular expression pattern objects. (Contributed by Raymond
 
Hettinger.)</p></li>
 
<li><p>The <code>xmlrpclib</code> module now supports a multi-call extension for
 
transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by
 
Brian Quinlan.)</p></li>
 
<li><p>The <code>mpz</code>, <code>rotor</code>, and <code>xreadlines</code> modules have been
 
removed.</p></li></ul>
 
  
 
<div id="cookielib" class="section">
 
<div id="cookielib" class="section">
  
=== cookielib ===
+
=== 曲奇库 ===
  
The <code>cookielib</code> library supports client-side handling for HTTP cookies,
+
<code>cookielib</code> 库支持 HTTP cookie 的客户端处理,镜像 <code>Cookie</code> 模块的服务器端 cookie 支持。 Cookie 存储在 Cookie 罐中; 该库将 Web 服务器提供的 cookie 透明地存储在 cookie jar 中,并在连接到服务器时从 jar 中获取 cookie。 与 Web 浏览器一样,策略对象控制是否接受 cookie。
mirroring the <code>Cookie</code> module's server-side cookie support. Cookies are
 
stored in cookie jars; the library transparently stores cookies offered by the
 
web server in the cookie jar, and fetches the cookie from the jar when
 
connecting to the server. As in web browsers, policy objects control whether
 
cookies are accepted or not.
 
  
In order to store cookies across sessions, two implementations of cookie jars
+
为了跨会话存储 cookie,提供了两种 cookie jar 实现:一种以 Netscape 格式存储 cookie,以便应用程序可以使用 Mozilla Lynx cookie 文件,另一种以与 Perl libwww 库相同的格式存储 cookie。
are provided: one that stores cookies in the Netscape format so applications can
 
use the Mozilla or Lynx cookie files, and one that stores cookies in the same
 
format as the Perl libwww library.
 
  
<code>urllib2</code> has been changed to interact with <code>cookielib</code>:
+
<code>urllib2</code> 已更改为与 <code>cookielib</code> 交互:<code>HTTPCookieProcessor</code> 管理访问 URL 时使用的 cookie jar。
<code>HTTPCookieProcessor</code> manages a cookie jar that is used when accessing
 
URLs.
 
  
This module was contributed by John J. Lee.
+
该模块由 John J. 李。
  
  
第1,519行: 第1,129行:
 
<div id="doctest" class="section">
 
<div id="doctest" class="section">
  
=== doctest ===
+
=== 文档测试 ===
  
The [[../../library/doctest#module-doctest|<code>doctest</code>]] module underwent considerable refactoring thanks to Edward
+
[[../../library/doctest#module-doctest|doctest]] 模块在 Edward Loper Tim Peters 的帮助下进行了大量重构。 测试仍然可以像运行 [[../../library/doctest#doctest|doctest.testmod()]] 一样简单,但重构允许以各种方式自定义模块的操作
Loper and Tim Peters. Testing can still be as simple as running
 
[[../../library/doctest#doctest|<code>doctest.testmod()</code>]], but the refactorings allow customizing the module's
 
operation in various ways
 
  
The new <code>DocTestFinder</code> class extracts the tests from a given object's
+
新的 <code>DocTestFinder</code> 类从给定对象的文档字符串中提取测试:
docstrings:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,533行: 第1,139行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def f (x, y):
+
<syntaxhighlight lang="python3">def f (x, y):
     &quot;&quot;&quot;&gt;&gt;&gt; f(2,2)
+
     """>>> f(2,2)
 
4
 
4
&gt;&gt;&gt; f(3,2)
+
>>> f(3,2)
 
6
 
6
     &quot;&quot;&quot;
+
     """
 
     return x*y
 
     return x*y
  
第1,544行: 第1,150行:
  
 
# Get list of DocTest instances
 
# Get list of DocTest instances
tests = finder.find(f)</pre>
+
tests = finder.find(f)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The new <code>DocTestRunner</code> class then runs individual tests and can produce
+
新的 <code>DocTestRunner</code> 类然后运行单独的测试并可以生成结果摘要:
a summary of the results:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,556行: 第1,161行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>runner = doctest.DocTestRunner()
+
<syntaxhighlight lang="python3">runner = doctest.DocTestRunner()
 
for t in tests:
 
for t in tests:
 
     tried, failed = runner.run(t)
 
     tried, failed = runner.run(t)
  
runner.summarize(verbose=1)</pre>
+
runner.summarize(verbose=1)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The above example produces the following output:
+
上面的示例产生以下输出:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,571行: 第1,176行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>1 items passed all tests:
+
<syntaxhighlight lang="python3">1 items passed all tests:
 
   2 tests in f
 
   2 tests in f
 
2 tests in 1 items.
 
2 tests in 1 items.
 
2 passed and 0 failed.
 
2 passed and 0 failed.
Test passed.</pre>
+
Test passed.</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>DocTestRunner</code> uses an instance of the <code>OutputChecker</code> class to
+
<code>DocTestRunner</code> 使用 <code>OutputChecker</code> 类的实例将预期输出与实际输出进行比较。 此类采用许多不同的标志来自定义其行为; 雄心勃勃的用户还可以编写一个全新的 <code>OutputChecker</code> 子类。
compare the expected output with the actual output. This class takes a number
 
of different flags that customize its behaviour; ambitious users can also write
 
a completely new subclass of <code>OutputChecker</code>.
 
  
The default output checker provides a number of handy features. For example,
+
默认输出检查器提供了许多方便的功能。 例如,使用 [[../../library/doctest#doctest|doctest.ELLIPSIS]] 选项标志,预期输出中的省略号 (<code>...</code>) 匹配任何子字符串,从而更容易适应以次要方式变化的输出:
with the [[../../library/doctest#doctest|<code>doctest.ELLIPSIS</code>]] option flag, an ellipsis (<code>...</code>) in the
 
expected output matches any substring, making it easier to accommodate outputs
 
that vary in minor ways:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,594行: 第1,193行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def o (n):
+
<syntaxhighlight lang="python3">def o (n):
     &quot;&quot;&quot;&gt;&gt;&gt; o(1)
+
     """>>> o(1)
&lt;__main__.C instance at 0x...&gt;
+
<__main__.C instance at 0x...>
&gt;&gt;&gt;
+
>>>
&quot;&quot;&quot;</pre>
+
"""</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Another special string, <code>&lt;BLANKLINE&gt;</code>, matches a blank line:
+
另一个特殊字符串 <code>&lt;BLANKLINE&gt;</code> 匹配空行:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,609行: 第1,208行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def p (n):
+
<syntaxhighlight lang="python3">def p (n):
     &quot;&quot;&quot;&gt;&gt;&gt; p(1)
+
     """>>> p(1)
&lt;BLANKLINE&gt;
+
<BLANKLINE>
&gt;&gt;&gt;
+
>>>
&quot;&quot;&quot;</pre>
+
"""</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Another new capability is producing a diff-style display of the output by
+
另一个新功能是通过指定 [[../../library/doctest#doctest|doctest.REPORT_UDIFF]](统一差异)、[[../../library/doctest#doctest|doctest.REPORT_CDIFF]](上下文差异)或 [[../../library/doctest#doctest|doctest 来生成输出的差异样式显示。 REPORT_NDIFF]] (delta-style) 选项标志。 例如:
specifying the [[../../library/doctest#doctest|<code>doctest.REPORT_UDIFF</code>]] (unified diffs),
 
[[../../library/doctest#doctest|<code>doctest.REPORT_CDIFF</code>]] (context diffs), or [[../../library/doctest#doctest|<code>doctest.REPORT_NDIFF</code>]]
 
(delta-style) option flags. For example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,627行: 第1,223行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def g (n):
+
<syntaxhighlight lang="python3">def g (n):
     &quot;&quot;&quot;&gt;&gt;&gt; g(4)
+
     """>>> g(4)
 
here
 
here
 
is
 
is
 
a
 
a
 
lengthy
 
lengthy
&gt;&gt;&gt;&quot;&quot;&quot;
+
>>>"""
 
     L = 'here is a rather lengthy list of words'.split()
 
     L = 'here is a rather lengthy list of words'.split()
 
     for word in L[:n]:
 
     for word in L[:n]:
         print word</pre>
+
         print word</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Running the above function's tests with [[../../library/doctest#doctest|<code>doctest.REPORT_UDIFF</code>]] specified,
+
使用指定的 [[../../library/doctest#doctest|doctest.REPORT_UDIFF]] 运行上述函数的测试,您会得到以下输出:
you get the following output:
 
  
 
<div class="highlight-none notranslate">
 
<div class="highlight-none notranslate">
第1,648行: 第1,243行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>**********************************************************************
+
<pre class="none">**********************************************************************
 
File &quot;t.py&quot;, line 15, in g
 
File &quot;t.py&quot;, line 15, in g
 
Failed example:
 
Failed example:
第1,669行: 第1,264行:
 
<div id="build-and-c-api-changes" class="section">
 
<div id="build-and-c-api-changes" class="section">
  
== Build and C API Changes ==
+
== 构建和 C API 更改 ==
  
Some of the changes to Python's build process and to the C API are:
+
Python 的构建过程和 C API 的一些更改是:
  
* Three new convenience macros were added for common return values from extension functions: [[../../c-api/none#c|<code>Py_RETURN_NONE</code>]], [[../../c-api/bool#c|<code>Py_RETURN_TRUE</code>]], and [[../../c-api/bool#c|<code>Py_RETURN_FALSE</code>]]. (Contributed by Brett Cannon.)
+
* 为扩展函数的常见返回值添加了三个新的便利宏:[[../../c-api/none#c|Py_RETURN_NONE]][[../../c-api/bool#c|Py_RETURN_TRUE]] [[../../c-api/bool#c|Py_RETURN_FALSE]]。 (由布雷特·坎农提供。)
* Another new macro, <span class="xref c c-texpr">[[../../c-api/refcounting#c|Py_CLEAR]](obj)</span>, decreases the reference count of ''obj'' and sets ''obj'' to the null pointer. (Contributed by Jim Fulton.)
+
* 另一个新宏 <span class="xref c c-texpr">Py_CLEAR(obj)</span> 减少了 ''obj'' 的引用计数并将 ''obj'' 设置为空指针。 (由吉姆富尔顿提供。)
* A new function, <code>PyTuple_Pack(N, obj1, obj2, ..., objN)</code>, constructs tuples from a variable length argument list of Python objects. (Contributed by Raymond Hettinger.)
+
* 一个新函数 <code>PyTuple_Pack(N, obj1, obj2, ..., objN)</code> Python 对象的可变长度参数列表构造元组。 (雷蒙德·赫廷格供稿。)
* A new function, <code>PyDict_Contains(d, k)</code>, implements fast dictionary lookups without masking exceptions raised during the look-up process. (Contributed by Raymond Hettinger.)
+
* 一个新函数 <code>PyDict_Contains(d, k)</code> 实现了快速字典查找,而不会屏蔽查找过程中引发的异常。 (雷蒙德·赫廷格供稿。)
* The <span class="xref c c-texpr">Py_IS_NAN(X)</span> macro returns 1 if its float or double argument ''X'' is a NaN. (Contributed by Tim Peters.)
+
* 如果 <span class="xref c c-texpr">Py_IS_NAN(X)</span> 宏的浮点或双参数 ''X'' 是 NaN,则该宏返回 1。 (由蒂姆·彼得斯提供。)
* C code can avoid unnecessary locking by using the new [[../../c-api/init#c|<code>PyEval_ThreadsInitialized()</code>]] function to tell if any thread operations have been performed. If this function returns false, no lock operations are needed. (Contributed by Nick Coghlan.)
+
* C 代码可以通过使用新的 [[../../c-api/init#c|PyEval_ThreadsInitialized()]] 函数来判断是否执行了任何线程操作,从而避免不必要的锁定。 如果此函数返回 false,则不需要锁定操作。 (由尼克·科格兰提供。)
* A new function, [[../../c-api/arg#c|<code>PyArg_VaParseTupleAndKeywords()</code>]], is the same as [[../../c-api/arg#c|<code>PyArg_ParseTupleAndKeywords()</code>]] but takes a <code>va_list</code> instead of a number of arguments. (Contributed by Greg Chapman.)
+
* 新函数 [[../../c-api/arg#c|PyArg_VaParseTupleAndKeywords()]] [[../../c-api/arg#c|PyArg_ParseTupleAndKeywords()]] 相同,但采用 <code>va_list</code> 而不是多个参数。 (由格雷格查普曼提供。)
* A new method flag, <code>METH_COEXISTS</code>, allows a function defined in slots to co-exist with a [[../../c-api/structures#c|<code>PyCFunction</code>]] having the same name. This can halve the access time for a method such as <code>set.__contains__()</code>. (Contributed by Raymond Hettinger.)
+
* 新的方法标志 <code>METH_COEXISTS</code> 允许在槽中定义的函数与具有相同名称的 [[../../c-api/structures#c|PyCFunction]] 共存。 这可以将诸如 <code>set.__contains__()</code> 之类的方法的访问时间减半。 (雷蒙德·赫廷格供稿。)
* Python can now be built with additional profiling for the interpreter itself, intended as an aid to people developing the Python core. Providing <code>--enable-profiling</code> to the '''configure''' script will let you profile the interpreter with '''gprof''', and providing the <code>--with-tsc</code> switch enables profiling using the Pentium's Time-Stamp-Counter register. Note that the <code>--with-tsc</code> switch is slightly misnamed, because the profiling feature also works on the PowerPC platform, though that processor architecture doesn't call that register &quot;the TSC register&quot;. (Contributed by Jeremy Hylton.)
+
* 现在可以使用解释器本身的额外分析来构建 Python,旨在帮助开发 Python 核心的人。 为 '''configure''' 脚本提供 <code>--enable-profiling</code> 将使您能够使用 '''gprof''' 对解释器进行分析,并提供 <code>--with-tsc</code> 开关可以使用 Pentium 的时间戳进行分析- 柜台登记。 请注意,<code>--with-tsc</code> 开关的名称略有错误,因为分析功能也适用于 PowerPC 平台,尽管该处理器架构并未将该寄存器称为“TSC 寄存器”。 (由杰里米·希尔顿提供。)
* The <code>tracebackobject</code> type has been renamed to <code>PyTracebackObject</code>.
+
* <code>tracebackobject</code> 类型已重命名为 <code>PyTracebackObject</code>
  
 
<div id="port-specific-changes" class="section">
 
<div id="port-specific-changes" class="section">
  
=== Port-Specific Changes ===
+
=== 特定于端口的更改 ===
  
* The Windows port now builds under MSVC++ 7.1 as well as version 6. (Contributed by Martin von Löwis.)
+
* Windows 端口现在在 MSVC++ 7.1 和版本 6 下构建。 (由 Martin von Löwis 提供。)
  
  
第1,696行: 第1,291行:
 
<div id="porting-to-python-2-4" class="section">
 
<div id="porting-to-python-2-4" class="section">
  
== Porting to Python 2.4 ==
+
== 移植到 Python 2.4 ==
  
This section lists previously described changes that may require changes to your
+
本节列出了可能需要更改代码的先前描述的更改:
code:
 
  
* Left shifts and hexadecimal/octal constants that are too large no longer trigger a [[../../library/exceptions#FutureWarning|<code>FutureWarning</code>]] and return a value limited to 32 or 64 bits; instead they return a long integer.
+
* 过大的左移和十六进制/八进制常量不再触发 [[../../library/exceptions#FutureWarning|FutureWarning]] 并返回限制为 32 64 位的值; 相反,它们返回一个长整数。
* Integer operations will no longer trigger an <code>OverflowWarning</code>. The <code>OverflowWarning</code> warning will disappear in Python 2.5.
+
* 整数运算将不再触发 <code>OverflowWarning</code><code>OverflowWarning</code> 警告将在 Python 2.5 中消失。
* The [[../../library/functions#zip|<code>zip()</code>]] built-in function and <code>itertools.izip()</code> now return an empty list instead of raising a [[../../library/exceptions#TypeError|<code>TypeError</code>]] exception if called with no arguments.
+
* [[../../library/functions#zip|zip()]] 内置函数和 <code>itertools.izip()</code> 现在返回一个空列表,而不是在不带参数调用时引发 [[../../library/exceptions#TypeError|TypeError]] 异常。
* You can no longer compare the <code>date</code> and [[../../library/datetime#datetime|<code>datetime</code>]] instances provided by the [[../../library/datetime#module-datetime|<code>datetime</code>]] module. Two instances of different classes will now always be unequal, and relative comparisons (<code>&lt;</code>, <code>&gt;</code>) will raise a [[../../library/exceptions#TypeError|<code>TypeError</code>]].
+
* 您无法再比较 [[../../library/datetime#module-datetime|datetime]] 模块提供的 <code>date</code> [[../../library/datetime#datetime|datetime]] 实例。 不同类的两个实例现在总是不相等的,相对比较 (<code>&lt;</code>, <code>&gt;</code>) 将引发 [[../../library/exceptions#TypeError|TypeError]]
* <code>dircache.listdir()</code> now passes exceptions to the caller instead of returning empty lists.
+
* <code>dircache.listdir()</code> 现在将异常传递给调用者而不是返回空列表。
* <code>LexicalHandler.startDTD()</code> used to receive the public and system IDs in the wrong order. This has been corrected; applications relying on the wrong order need to be fixed.
+
* <code>LexicalHandler.startDTD()</code> 用于以错误的顺序接收公共和系统 ID。 这已得到纠正; 需要修复依赖错误顺序的应用程序。
* [[../../library/fcntl#fcntl|<code>fcntl.ioctl()</code>]] now warns if the ''mutate'' argument is omitted and relevant.
+
* [[../../library/fcntl#fcntl|fcntl.ioctl()]] 现在警告 ''mutate'' 参数是否被省略和相关。
* The [[../../library/tarfile#module-tarfile|<code>tarfile</code>]] module now generates GNU-format tar files by default.
+
* [[../../library/tarfile#module-tarfile|tarfile]] 模块现在默认生成 GNU 格式的 tar 文件。
* Encountering a failure while importing a module no longer leaves a partially-initialized module object in <code>sys.modules</code>.
+
* 导入模块时遇到失败不再在 <code>sys.modules</code> 中留下部分初始化的模块对象。
* [[../../library/constants#None|<code>None</code>]] is now a constant; code that binds a new value to the name <code>None</code> is now a syntax error.
+
* [[../../library/constants#None|None]] 现在是一个常数; 将新值绑定到名称 <code>None</code> 的代码现在是一个语法错误。
* The <code>signals.signal()</code> function now raises a [[../../library/exceptions#RuntimeError|<code>RuntimeError</code>]] exception for certain illegal values; previously these errors would pass silently. For example, you can no longer set a handler on the <code>SIGKILL</code> signal.
+
* <code>signals.signal()</code> 函数现在针对某些非法值引发 [[../../library/exceptions#RuntimeError|RuntimeError]] 异常; 以前这些错误会默默传递。 例如,您不能再在 <code>SIGKILL</code> 信号上设置处理程序。
  
  
第1,718行: 第1,312行:
  
 
<span id="acks"></span>
 
<span id="acks"></span>
== Acknowledgements ==
+
== 致谢 ==
  
The author would like to thank the following people for offering suggestions,
+
作者要感谢以下人员对本文的各种草稿提供建议、更正和帮助:Koray Can、Hye-Shik Chang、Michael Dyck、Raymond Hettinger、Brian Hurt、Hamish Lawson、Fredrik Lundh、Sean Reifschneider、Sadruddin拒绝。
corrections and assistance with various drafts of this article: Koray Can,
 
Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson,
 
Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.
 
  
  
第1,729行: 第1,320行:
  
 
</div>
 
</div>
 +
<div class="clearer">
  
[[Category:Python 3.9 中文文档]]
+
 
 +
 
 +
</div>
 +
 
 +
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:54的最新版本

Python 2.4 中的新功能

作者
是 库克林

本文介绍了 2005 年 3 月 30 日发布的 Python 2.4.1 中的新功能。

Python 2.4 是一个中等规模的版本。 它没有像激进的 Python 2.2 那样引入那么多的变化,但引入了比保守的 2.3 版本更多的特性。 最重要的新语言特性是函数装饰器和生成器表达式; 大多数其他更改都针对标准库。

根据 CVS 更改日志,在 Python 2.3 和 2.4 之间应用了 481 个补丁并修复了 502 个错误。 这两个数字都可能被低估。

本文并不试图提供每个新功能的完整规范,而是提供对每个功能的简要介绍。 有关完整的详细信息,您应该参考 Python 2.4 的文档,例如 Python 库参考和 Python 参考手册。 通常,您会被称为 PEP 以获得特定的新功能,以解释实现和设计原理。

PEP 218:内置集合对象

Python 2.3 引入了 sets 模块。 集合数据类型的 C 实现现在已作为两个新的内置类型添加到 Python 核心中,set(iterable)frozenset(iterable)。 它们为成员测试、从序列中消除重复项以及诸如并集、交集、差异和对称差异之类的数学运算提供高速运算。

>>> a = set('abracadabra')              # form a set from a string
>>> 'z' in a                            # fast membership testing
False
>>> a                                   # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> ''.join(a)                          # convert back into a string
'arbcd'

>>> b = set('alacazam')                 # form a second set
>>> a - b                               # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                               # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                               # letters in both a and b
set(['a', 'c'])
>>> a ^ b                               # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

>>> a.add('z')                          # add a new element
>>> a.update('wxy')                     # add multiple new elements
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
>>> a.remove('x')                       # take one element out
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])

frozenset() 类型是 set() 的不可变版本。 由于它是不可变和可散列的,因此它可以用作字典键或另一个集合的成员。

sets 模块保留在标准库中,如果您希望对 SetImmutableSet 类进行子类化,它可能很有用。 目前没有计划弃用该模块。

也可以看看

PEP 218 - 添加内置集对象类型
最初由 Greg Wilson 提出,最终由 Raymond Hettinger 实施。


PEP 237:统一长整数和整数

此 PEP 的漫长过渡过程始于 Python 2.2,在 Python 2.4 中又向前迈进了一步。 在 2.3 中,某些整数运算在 int/long 统一触发 FutureWarning 警告并返回限制为 32 或 64 位的值(取决于您的平台)后表现不同。 在 2.4 中,这些表达式不再产生警告,而是产生不同的结果,通常是一个长整数。

有问题的表达式主要是左移和冗长的十六进制和八进制常量。 例如,2 << 32 在 2.3 中导致警告,在 32 位平台上计算为 0。 在 Python 2.4 中,此表达式现在返回正确答案 8589934592。

也可以看看

PEP 237 - 统一长整数和整数
由 Moshe Zadka 和 GvR 编写的原始 PEP。 2.4 的更改由 Kalle Svensson 实施。


PEP 289:生成器表达式

Python 2.2 中引入的迭代器功能和 itertools 模块可以更轻松地编写循环遍历大型数据集的程序,而无需一次将整个数据集保存在内存中。 列表推导式不太适合这张图,因为它们生成了一个包含所有项目的 Python 列表对象。 这不可避免地将所有对象拉入内存,如果您的数据集非常大,这可能是一个问题。 当试图编写一个函数式风格的程序时,很自然地编写如下内容:

links = [link for link in get_all_links() if not link.followed]
for link in links:
    ...

代替

for link in get_all_links():
    if link.followed:
        continue
    ...

第一种形式更简洁,可能更具可读性,但如果您正在处理大量链接对象,则必须编写第二种形式以避免将所有链接对象同时放入内存中。

生成器表达式的工作方式类似于列表推导式,但不会具体化整个列表; 相反,他们创建了一个生成器,它将一个一个地返回元素。 上面的例子可以写成:

links = (link for link in get_all_links() if not link.followed)
for link in links:
    ...

生成器表达式总是必须写在括号内,如上例所示。 表示函数调用的括号也很重要,因此如果您想创建一个将立即传递给函数的迭代器,您可以编写:

print sum(obj.count for obj in list_all_objects())

生成器表达式与列表推导式在各种小方面有所不同。 最值得注意的是,循环变量(上面例子中的 obj)在生成器表达式之外是不可访问的。 列表推导式将变量分配给它的最后一个值; Python 的未来版本将改变这一点,使列表推导式在这方面与生成器表达式相匹配。

也可以看看

PEP 289 - 生成器表达式
由 Raymond Hettinger 提出,由 Jiwon Seo 实施,早期工作由 Hye-Shik Chang 指导。


PEP 292:更简单的字符串替换

标准库中的一些新类提供了将变量替换为字符串的替代机制; 这种替换风格可能更适合未经培训的用户需要编辑模板的应用程序。

按名称替换变量的常用方法是 % 运算符:

>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
'2: The Best of Times'

在编写模板字符串时,很容易忘记右括号后的 is。 如果模板在 Python 模块中,这不是大问题,因为您运行代码,得到“不支持的格式字符”ValueError,然后修复问题。 但是,考虑一个应用程序,例如 Mailman,其中模板字符串或翻译由不了解 Python 语言的用户编辑。 向这些用户解释格式字符串的语法很复杂,如果他们犯了错误,也很难向他们提供有用的反馈。

PEP 292 将 Template 类添加到 string 模块中,该模块使用 $ 来指示替换:

>>> import string
>>> t = string.Template('$page: $title')
>>> t.substitute({'page':2, 'title': 'The Best of Times'})
'2: The Best of Times'

如果字典中缺少键,substitute() 方法将引发 KeyError。 还有一个 safe_substitute() 方法可以忽略丢失的键:

>>> t = string.Template('$page: $title')
>>> t.safe_substitute({'page':3})
'3: $title'

也可以看看

PEP 292 - 更简单的字符串替换
由 Barry Warsaw 编写和实施。


PEP 318:函数和方法的装饰器

Python 2.2 通过添加静态方法和类方法扩展了 Python 的对象模型,但它没有扩展 Python 的语法以提供任何定义静态或类方法的新方法。 相反,您必须以通常的方式编写 def 语句,并将结果方法传递给 staticmethod()classmethod() 函数,该函数将包装将函数作为新类型的方法。 您的代码如下所示:

class C:
   def meth (cls):
       ...

   meth = classmethod(meth)   # Rebind name to wrapped-up class method

如果方法很长,很容易错过或忘记函数体后面的 classmethod() 调用。

其意图始终是添加一些语法以使此类定义更具可读性,但在 2.2 发布时,好的语法并不明显。 今天,一个好的语法 still 并不明显,但用户要求更容易访问该功能; 添加了一个新的语法特性来满足这一需求。

新功能称为“函数装饰器”。 这个名字来源于classmethod()staticmethod()和朋友们在一个函数对象上存储附加信息的想法; 它们是 装饰 功能更多细节。

该符号借用 Java 并使用 '@' 字符作为指示符。 使用新语法,上面的例子将被写成:

class C:

   @classmethod
   def meth (cls):
       ...

@classmethodmeth=classmethod(meth) 赋值的简写。 更一般地说,如果您有以下情况:

@A
@B
@C
def f ():
    ...

它相当于下面的预装饰器代码:

def f(): ...
f = A(B(C(f)))

装饰器必须在函数定义之前,每行一个装饰器,并且不能与 def 语句在同一行,这意味着 @A def f(): ... 是非法的。 您只能在模块级别或类内部装饰函数定义; 你不能装饰类定义。

装饰器只是一个函数,它将要装饰的函数作为参数并返回相同的函数或某个新对象。 装饰器的返回值不需要是可调用的(尽管它通常是),除非将进一步的装饰器应用于结果。 编写自己的装饰器很容易。 下面的简单示例只是在函数对象上设置一个属性:

>>> def deco(func):
...    func.attr = 'decorated'
...    return func
...
>>> @deco
... def f(): pass
...
>>> f
<function f at 0x402ef0d4>
>>> f.attr
'decorated'
>>>

作为一个更现实的例子,以下装饰器检查提供的参数是否为整数:

def require_int (func):
    def wrapper (arg):
        assert isinstance(arg, int)
        return func(arg)

    return wrapper

@require_int
def p1 (arg):
    print arg

@require_int
def p2(arg):
    print arg*2

PEP 318 中的一个例子包含了这个想法的一个更高级的版本,它允许你指定所需的类型并检查返回的类型。

装饰器函数可以带参数。 如果提供了参数,则仅使用这些参数调用装饰器函数,并且必须返回新的装饰器函数; 如前所述,此函数必须采用单个函数并返回一个函数。 换句话说,@A @B @C(args) 变成:

def f(): ...
_deco = C(args)
f = A(B(_deco(f)))

正确地做到这一点可能有点费脑筋,但这并不太难。

一个小的相关更改使函数的 func_name 属性可写。 此属性用于在回溯中显示函数名称,因此装饰器应更改构造和返回的任何新函数的名称。

也可以看看

PEP 318 - 函数、方法和类的装饰器
由凯文 D 撰写 史密斯、吉姆·朱伊特和跳过蒙塔纳罗。 有几个人编写了实现函数装饰器的补丁,但实际签入的是由 Mark Russell 编写的补丁 #979728。
https://wiki.python.org/moin/PythonDecoratorLibrary
此 Wiki 页面包含几个装饰器示例。


PEP 322:反向迭代

一个新的内置函数 reversed(seq) 接受一个序列并返回一个迭代器,该迭代器以相反的顺序循环遍历该序列的元素。

>>> for i in reversed(xrange(1,4)):
...    print i
...
3
2
1

与扩展切片(例如 range(1,4)[::-1])相比,reversed() 更易于阅读,运行速度更快,并且使用的内存要少得多。

请注意, reversed() 只接受序列,而不是任意迭代器。 如果要反转迭代器,请首先使用 list() 将其转换为列表。

>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
...
root:*:0:0:System Administrator:/var/root:/bin/tcsh
  ...

也可以看看

PEP 322 - 反向迭代
由 Raymond Hettinger 编写和实施。


PEP 324:新的子流程模块

标准库提供了多种执行子流程的方法,提供不同的功能和不同级别的复杂性。 os.system(command) 易于使用,但速度慢(它运行执行命令的 shell 进程)且危险(您必须小心转义 shell 的元字符)。 popen2 模块提供了可以从子进程捕获标准输出和标准错误的类,但命名令人困惑。 subprocess 模块对此进行了清理,提供了一个统一的界面,可以提供您可能需要的所有功能。

代替 popen2 的类集合,subprocess 包含一个名为 Popen 的类,其构造函数支持许多不同的关键字参数。

class Popen(args, bufsize=0, executable=None,
            stdin=None, stdout=None, stderr=None,
            preexec_fn=None, close_fds=False, shell=False,
            cwd=None, env=None, universal_newlines=False,
            startupinfo=None, creationflags=0):

args 通常是一个字符串序列,它们将作为作为子进程执行的程序的参数。 (如果 shell 参数为真,args 可以是一个字符串,然后将传递给 shell 进行解释,就像 os.system()做。)

stdinstdoutstderr 指定子进程的输入、输出和错误流将是什么。 您可以提供文件对象或文件描述符,也可以使用常量 subprocess.PIPE 在子进程和父进程之间创建管道。

构造函数有许多方便的选项:

  • close_fds 请求在运行子进程之前关闭所有文件描述符。
  • cwd 指定子进程将在其中执行的工作目录(默认为父进程的任何工作目录)。
  • env 是一个指定环境变量的字典。
  • preexec_fn 是在子进程启动之前调用的函数。
  • universal_newlines 使用 Python 的 universal newlines 功能打开孩子的输入和输出。

一旦你创建了 Popen 实例,你可以调用它的 wait() 方法暂停直到子进程退出,poll() 检查它是否在没有暂停的情况下退出,或者 communicate(data) 将字符串 data 发送到子进程的标准输入。 communicate(data) 然后读取子进程发送到其标准输出或标准错误的任何数据,返回一个元组 (stdout_data, stderr_data)

call() 是一个快捷方式,将其参数传递给 Popen 构造函数,等待命令完成,并返回子进程的状态代码。 它可以作为 os.system() 的更安全的模拟:

sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
if sts == 0:
    # Success
    ...
else:
    # dpkg returned an error
    ...

该命令是在不使用 shell 的情况下调用的。 如果你真的想使用 shell,你可以添加 shell=True 作为关键字参数并提供一个字符串而不是一个序列:

sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)

PEP 采用各种 shell 和 Python 代码示例,并展示了如何将它们转换为使用 子进程 的 Python 代码。 强烈建议阅读 PEP 的这一部分。

也可以看看

PEP 324 - 子流程 - 新流程模块
由 Peter Åstrand 在 Fredrik Lundh 和其他人的协助下编写和实施。


PEP 327:十进制数据类型

Python 一直支持基于底层 C double 类型的浮点 (FP) 数作为数据类型。 然而,虽然大多数编程语言都提供浮点类型,但许多人(甚至程序员)并不知道浮点数不能准确地表示某些小数。 新的 Decimal 类型可以准确地表示这些分数,最高可达用户指定的精度限制。

为什么需要十进制?

限制来自用于浮点数的表示。 FP 数字由三个部分组成:

  • 正负号。
  • 尾数,它是一位二进制数,后跟小数部分。 例如,以 2 进制表示的 1.011 + 0/2 + 1/4,或十进制表示法中的 1.25。
  • 指数,它告诉小数点在所表示的数字中的位置。

例如,数字 1.25 为正号,尾数值为 1.01(二进制),指数为 0(小数点不需要移动)。 数字 5 具有相同的符号和尾数,但指数为 2,因为尾数乘以 4(2 的指数 2 次方); 1.25 * 4 等于 5。

现代系统通常提供符合 IEEE 754 标准的浮点支持。 C 的 double 类型通常实现为 64 位 IEEE 754 数字,它使用 52 位空间作为尾数。 这意味着数字只能指定为 52 位精度。 如果您试图表示无限重复扩展的数字,则扩展会在 52 位后被切断。 不幸的是,大多数软件需要产生以 10 为基数的输出,而以 10 为基数的常见分数通常是重复二进制的十进制数。 例如1.1十进制就是二进制1.0001100110011 ...; .1 = 1/16 + 1/32 + 1/256 加上无限数量的附加项。 IEEE 754 必须在 52 位数字后去掉无限重复的小数,因此表示有点不准确。

有时您会在打印数字时看到这种不准确:

>>> 1.1
1.1000000000000001

当您打印数字时,不准确并不总是可见的,因为 FP 到十进制字符串的转换是由 C 库提供的,并且大多数 C 库都试图产生合理的输出。 然而,即使它不显示,不准确仍然存在,后续操作可能会放大错误。

对于许多应用程序,这无关紧要。 如果我正在绘制点并将它们显示在我的监视器上,1.1 和 1.10000000000000001 之间的差异太小而无法看到。 报告通常将输出限制为一定数量的小数位,如果将数字四舍五入到两位、三位甚至八位小数,则错误永远不会明显。 但是,对于重要的应用程序,实现您自己的自定义算术例程需要大量工作。

因此,创建了 Decimal 类型。


Decimal型

Python 的标准库中添加了一个新模块 decimal。 它包含两个类,DecimalContextDecimal 实例代表数字,Context 实例用于包装精度和默认舍入模式等各种设置。

Decimal 实例是不可变的,就像常规的 Python 整数和 FP 数一样; 一旦它被创建,你就不能改变一个实例代表的值。 Decimal 实例可以从整数或字符串创建:

>>> import decimal
>>> decimal.Decimal(1972)
Decimal("1972")
>>> decimal.Decimal("1.1")
Decimal("1.1")

您还可以提供包含符号、表示为十进制数字元组的尾数和指数的元组:

>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
Decimal("-14.75")

注意事项:符号位是布尔值,因此 0 为正,1 为负。

从浮点数转换会带来一些问题:代表 1.1 的 FP 数是否应该变成十进制数正好是 1.1,还是 1.1 加上引入的任何不准确之处? 决定是为了避免这个问题并将这样的转换排除在 API 之外。 相反,您应该使用所需的精度将浮点数转换为字符串,并将该字符串传递给 Decimal 构造函数:

>>> f = 1.1
>>> decimal.Decimal(str(f))
Decimal("1.1")
>>> decimal.Decimal('%.12f' % f)
Decimal("1.100000000000")

一旦您拥有 Decimal 实例,您就可以对它们执行通常的数学运算。 一个限制:求幂需要一个整数指数:

>>> a = decimal.Decimal('35.72')
>>> b = decimal.Decimal('1.73')
>>> a+b
Decimal("37.45")
>>> a-b
Decimal("33.99")
>>> a*b
Decimal("61.7956")
>>> a/b
Decimal("20.64739884393063583815028902")
>>> a ** 2
Decimal("1275.9184")
>>> a**b
Traceback (most recent call last):
  ...
decimal.InvalidOperation: x ** (non-integer)

您可以将 Decimal 实例与整数组合,但不能与浮点数组合:

>>> a + 4
Decimal("39.72")
>>> a + 4.5
Traceback (most recent call last):
  ...
TypeError: You can interact Decimal only with int, long or Decimal data types.
>>>

Decimal 数可以与 mathcmath 模块一起使用,但请注意,在执行运算之前,它们会立即转换为浮点数,结果可能会损失精度和准确度。 您还将得到一个常规的浮点数,而不是 Decimal

>>> import math, cmath
>>> d = decimal.Decimal('123456789012.345')
>>> math.sqrt(d)
351364.18288201344
>>> cmath.sqrt(-d)
351364.18288201344j

Decimal 实例有一个 sqrt() 方法,该方法返回一个 Decimal,但是如果您需要其他东西,例如三角函数,则必须实现它们。

>>> d.sqrt()
Decimal("351364.1828820134592177245001")

Context型

Context 类的实例封装了十进制运算的几个设置:

  • prec为精度,小数位数。
  • rounding 指定舍入模式。 decimal 模块具有用于各种可能性的常量:ROUND_DOWNROUND_CEILINGROUND_HALF_EVEN 和各种其他。
  • traps 是一个字典,指定在遇到某些错误条件时会发生什么:引发异常或返回值。 错误条件的一些示例是被零除、精度损失和溢出。

通过调用 getcontext() 可以使用线程本地默认上下文; 您可以更改此上下文的属性以更改默认精度、舍入或陷阱处理。 以下示例显示了更改默认上下文精度的效果:

>>> decimal.getcontext().prec
28
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.1428571428571428571428571429")
>>> decimal.getcontext().prec = 9
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.142857143")

错误条件的默认操作是可选的; 该模块可以返回一个特殊值,例如无穷大或非数字,或者可以引发异常:

>>> decimal.Decimal(1) / decimal.Decimal(0)
Traceback (most recent call last):
  ...
decimal.DivisionByZero: x / 0
>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
>>> decimal.Decimal(1) / decimal.Decimal(0)
Decimal("Infinity")
>>>

Context 实例也有多种格式化数字的方法,例如 to_eng_string()to_sci_string()

有关详细信息,请参阅 decimal 模块的文档,其中包括快速入门教程和参考。

也可以看看

PEP 327 - 十进制数据类型
由 Facundo Batista 编写,由 Facundo Batista、Eric Price、Raymond Hettinger、Aahz 和 Tim Peters 实施。
http://www.lahey.com/float.htm
本文使用 Fortran 代码来说明浮点不准确可能导致的许多问题。
http://speleotrove.com/decimal/
基于十进制表示的描述。 这种表示被提议作为标准,并且是新的 Python 十进制类型的基础。 这些材料的大部分是由 Rexx 语言的设计者 Mike Cowlishaw 编写的。


PEP 328:多行导入

一种语言更改是一个小的语法调整,旨在使从模块中导入许多名称变得更加容易。 在 from module import names 语句中,names 是由逗号分隔的名称序列。 如果序列很长,您可以从同一个模块中编写多个导入,或者您可以使用反斜杠来转义行结尾,如下所示:

from SimpleXMLRPCServer import SimpleXMLRPCServer,\
            SimpleXMLRPCRequestHandler,\
            CGIXMLRPCRequestHandler,\
            resolve_dotted_attribute

Python 2.4 中的语法更改只是允许将名称放在括号内。 Python 忽略括号表达式中的换行符,因此不再需要反斜杠:

from SimpleXMLRPCServer import (SimpleXMLRPCServer,
                                SimpleXMLRPCRequestHandler,
                                CGIXMLRPCRequestHandler,
                                resolve_dotted_attribute)

PEP 还建议所有 import 语句都是绝对导入,前导 . 字符表示相对导入。 PEP 的这部分不是为 Python 2.4 实现的,而是为 Python 2.5 完成的。

也可以看看

PEP 328 - 进口:多线和绝对/相对
阿兹写的。 多行导入由 Dima Dorfman 实现。


PEP 331:与语言环境无关的浮点/字符串转换

locale 模块允许 Python 软件选择本地化为特定国家或语言的各种转换和显示约定。 但是,该模块小心地不更改数字语言环境,因为 Python 实现中的各种函数要求数字语言环境保持设置为 'C' 语言环境。 这通常是因为代码使用了 C 库的 atof() 函数。

但是,不设置数字语言环境会给使用第三方 C 库的扩展带来麻烦,因为它们没有正确的语言环境设置。 激励示例是 GTK+,其用户界面小部件未在当前语言环境中显示数字。

PEP 中描述的解决方案是向 Python API 添加三个新函数,这些函数执行 ASCII-only 转换,忽略区域设置:

  • PyOS_ascii_strtod(str, ptr)PyOS_ascii_atof(str, ptr) 都将字符串转换为 C double
  • PyOS_ascii_formatd(buffer, buf_len, format, d)double 转换为 ASCII 字符串。

这些函数的代码来自 GLib 库(https://developer.gnome.org/glib/stable/),其开发者好心地将相关函数重新授权并捐赠给了 Python 软件基金会。 locale 模块现在可以更改数字区域设置,让 GTK+ 等扩展产生正确的结果。

也可以看看

PEP 331 - 与语言环境无关的浮点/字符串转换
由克里斯蒂安 R 撰写。 Reis,由 Gustavo Carneiro 实施。


其他语言更改

以下是 Python 2.4 对核心 Python 语言所做的所有更改。

  • 添加了函数和方法的装饰器(PEP 318)。

  • 添加了内置 set()frozenset() 类型(PEP 218)。 其他新的内置函数包括 reversed(seq) 函数(PEP 322)。

  • 添加了生成器表达式(PEP 289)。

  • 某些数值表达式不再返回限制为 32 或 64 位的值(PEP 237)。

  • 您现在可以在 from module import names 语句 (PEP 328) 中的名称列表周围加上括号。

  • dict.update() 方法现在接受与 dict 构造函数相同的参数形式。 这包括任何映射、任何可迭代的键/值对和关键字参数。 (雷蒙德·赫廷格供稿。)

  • 字符串方法 ljust()rjust()center() 现在采用可选参数来指定空格以外的填充字符。 (雷蒙德·赫廷格供稿。)

  • 字符串还获得了 rsplit() 方法,其工作方式类似于 split() 方法,但从字符串的末尾拆分。 (由肖恩·赖夫施奈德提供。)

    >>> 'www.python.org'.split('.', 1)
    ['www', 'python.org']
    'www.python.org'.rsplit('.', 1)
    ['www.python', 'org']
  • 三个关键字参数,cmpkeyreverse,被添加到列表的sort()方法中。 这些参数使 sort() 的一些常见用法变得更简单。 所有这些参数都是可选的。

    对于 cmp 参数,该值应该是一个比较函数,它接受两个参数并根据参数的比较方式返回 -1、0 或 +1。 然后将使用此函数对列表进行排序。 以前,这是唯一可以提供给 sort() 的参数。

    key 应该是一个单参数函数,它接受一个列表元素并返回该元素的比较键。 然后使用比较键对列表进行排序。 以下示例不区分大小写地对列表进行排序:

    >>> L = ['A', 'b', 'c', 'D']
    >>> L.sort()                 # Case-sensitive sort
    >>> L
    ['A', 'D', 'b', 'c']
    >>> # Using 'key' parameter to sort list
    >>> L.sort(key=lambda x: x.lower())
    >>> L
    ['A', 'b', 'c', 'D']
    >>> # Old-fashioned way
    >>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
    >>> L
    ['A', 'b', 'c', 'D']

    最后一个示例使用 cmp 参数,是执行不区分大小写排序的旧方法。 它可以工作,但比使用 key 参数慢。 使用 key 为列表中的每个元素调用一次 lower() 方法,而使用 cmp 将在每次比较时调用它两次,因此使用 key 节省在调用 lower() 方法时。

    对于简单的键函数和比较函数,通常可以通过使用未绑定的方法来避免 lambda 表达式。 例如,上面不区分大小写的排序最好写成:

    >>> L.sort(key=str.lower)
    >>> L
    ['A', 'b', 'c', 'D']

    最后,reverse 参数采用布尔值。 如果值为 true,则列表将按相反顺序排序。 您现在可以编写 L.sort(reverse=True),而不是 L.sort(); L.reverse()

    现在保证排序的结果是稳定的。 这意味着具有相同键的两个条目将按照与输入相同的顺序返回。 例如,您可以按姓名对人员列表进行排序,然后按年龄对列表进行排序,从而得到按年龄排序的列表,其中年龄相同的人员按姓名排序。

    (对 sort() 的所有更改均由 Raymond Hettinger 提供。)

  • 有一个新的内置函数 sorted(iterable),其工作方式类似于就地 list.sort() 方法,但可以在表达式中使用。 区别在于:

  • 输入可以是任何可迭代的;

  • 对新形成的副本进行排序,原件完好无损; 和

  • 表达式返回新的排序副本

    >>> L = [9,7,8,3,2,4,1,6,5]
    >>> [10+i for i in sorted(L)]       # usable in a list comprehension
    [11, 12, 13, 14, 15, 16, 17, 18, 19]
    >>> L                               # original is left unchanged
    [9,7,8,3,2,4,1,6,5]
    >>> sorted('Monty Python')          # any iterable may be an input
    [' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']
    
    >>> # List the contents of a dict sorted by key values
    >>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
    >>> for k, v in sorted(colormap.iteritems()):
    ...     print k, v
    ...
    black 4
    blue 2
    green 3
    red 1
    yellow 5

    (雷蒙德·赫廷格供稿。)

  • 整数运算将不再触发 OverflowWarningOverflowWarning 警告将在 Python 2.5 中消失。

  • 解释器获得了一个新的开关,-m,它接受一个名称,在 sys.path 上搜索相应的模块,并将该模块作为脚本运行。 例如,您现在可以使用 python -m profile 运行 Python 分析器。 (由尼克·科格兰提供。)

  • eval(expr, globals, locals)execfile(filename, globals, locals) 函数以及 exec 语句现在接受 locals 参数的任何映射类型。 以前这必须是一个普通的 Python 字典。 (雷蒙德·赫廷格供稿。)

  • zip() 内置函数和 itertools.izip() 现在在不带参数调用时返回一个空列表。 以前他们提出了 TypeError 异常。 这使它们更适合与可变长度参数列表一起使用:

    >>> def transpose(array):
    ...    return zip(*array)
    ...
    >>> transpose([(1,2,3), (4,5,6)])
    [(1, 4), (2, 5), (3, 6)]
    >>> transpose([])
    []

    (雷蒙德·赫廷格供稿。)

  • 导入模块时遇到失败不再在 sys.modules 中留下部分初始化的模块对象。 留下的不完整模块对象会欺骗相同模块的进一步导入,从而导致混淆错误。 (由蒂姆·彼得斯修正。)

  • None 现在是一个常数; 将新值绑定到名称 None 的代码现在是一个语法错误。 (雷蒙德·赫廷格供稿。)

优化

  • 列表和元组切片的内部循环得到了优化,现在运行速度提高了大约三分之一。 字典的内部循环也得到了优化,从而提高了 keys()values()items()iterkeys()itervalues()iteritems()。 (雷蒙德·赫廷格供稿。)
  • 增长和缩小列表的机制针对速度和空间效率进行了优化。 由于更高效的代码路径和更少使用底层系统 realloc(),从列表中追加和弹出现在运行得更快。 列表理解也有好处。 list.extend() 也进行了优化,在扩展基本列表之前不再将其参数转换为临时列表。 (雷蒙德·赫廷格供稿。)
  • list()tuple()map()filter()zip()现在使用提供 __len__() 方法的非序列参数运行速度提高数倍。 (雷蒙德·赫廷格供稿。)
  • 方法 list.__getitem__()dict.__getitem__()dict.__contains__() 现在被实现为 method_descriptor 对象而不是 wrapper_descriptor 对象。 这种访问形式使它们的性能翻倍,并使它们更适合用作函数的参数:map(mydict.__getitem__, keylist)。 (雷蒙德·赫廷格供稿。)
  • 添加了一个新的操作码 LIST_APPEND,它简化了列表推导式生成的字节码,并将它们的速度提高了大约三分之一。 (雷蒙德·赫廷格供稿。)
  • 窥视孔字节码优化器已得到改进,以生成更短、更快的字节码; 值得注意的是,生成的字节码更具可读性。 (由 Raymond Hettinger 增强。)
  • 在某些情况下,现在可以更有效地执行 s = s + "abc"s += "abc" 形式的语句中的字符串连接。 这种优化不会出现在其他 Python 实现(例如 Jython)中,因此您不应依赖它; 当您想有效地将大量字符串粘合在一起时,仍然建议使用字符串的 join() 方法。 (由 Armin Rigo 提供。)

2.4 优化的最终结果是 Python 2.4 运行的 pystone 基准测试比 Python 2.3 高 5% faster,比 Python 2.2 高 35% faster。 (pystone 不是一个特别好的基准,但它是 Python 性能最常用的衡量标准。 您自己的应用程序可能会从 Python 2.4 中显示出或多或少的好处。)


新的、改进的和弃用的模块

像往常一样,Python 的标准库得到了许多增强和错误修复。 这是最显着更改的部分列表,按模块名称的字母顺序排序。 请查阅源代码树中的 Misc/NEWS 文件以获取更完整的更改列表,或查看 CVS 日志以获取所有详细信息。

  • asyncore 模块的 loop() 函数现在具有 count 参数,可让您通过轮询循环执行有限次数的传递。 默认仍然是永远循环。

  • base64 模块现在有更完整的 RFC 3548 支持 Base64、Base32 和 Base16 编码和解码,包括可选的大小写折叠和可选的替代字母表。 (由巴里华沙提供。)

  • bisect 模块现在具有底层 C 实现以提高性能。 (德米特里·瓦西里耶夫供稿。)

  • 由 Hye-Shik Chang 维护的东亚编解码器的 CJKCodecs 集合已集成到 2.4 中。 新的编码是:

  • 中文(中国):gb2312、gbk、gb18030、big5hkscs、hz

  • 中文 (ROC): big5, cp950

  • 日语:cp932、euc-jis-2004、euc-jp、euc-jisx0213、iso-2022-jp、

    iso-2022-jp-1、iso-2022-jp-2、iso-2022-jp-3、iso-2022-jp-ext、iso-2022-jp-2004、shift-jis、shift-jisx0213、shift- jis-2004

  • 韩语:cp949、euc-kr、johab、iso-2022-kr

  • 添加了其他一些新编码:HP Roman8、ISO_8859-11、ISO_8859-16、PCTP-154 和 TIS-620。

  • UTF-8 和 UTF-16 编解码器现在可以更好地接收部分输入。 以前,StreamReader 类会尝试读取更多数据,从而无法从流中恢复解码。 read() 方法现在将返回尽可能多的数据,并且未来的调用将在前一个中断的地方继续解码。 (由 Walter Dörwald 实施。)

  • 有一个新的 collections 模块用于各种专门的集合数据类型。 目前它只包含一种类型,deque,一个双端队列,支持从任一端有效地添加和删除元素:

    >>> from collections import deque
    >>> d = deque('ghi')        # make a new deque with three items
    >>> d.append('j')           # add a new entry to the right side
    >>> d.appendleft('f')       # add a new entry to the left side
    >>> d                       # show the representation of the deque
    deque(['f', 'g', 'h', 'i', 'j'])
    >>> d.pop()                 # return and remove the rightmost item
    'j'
    >>> d.popleft()             # return and remove the leftmost item
    'f'
    >>> list(d)                 # list the contents of the deque
    ['g', 'h', 'i']
    >>> 'h' in d                # search the deque
    True

    几个模块,例如 Queuethreading 模块,现在利用 collections.deque 来提高性能。 (雷蒙德·赫廷格供稿。)

  • ConfigParser 类已略有增强。 read() 方法现在返回已成功解析的文件列表,如果传递 set() 方法会引发 TypeError不是字符串的参数。 (由约翰贝尔蒙特和大卫古德提供。)

  • curses 模块现在支持 ncurses 扩展 use_default_colors()。 在终端支持透明的平台上,这使得使用透明背景成为可能。 (约尔格·莱曼供稿。)

  • difflib 模块现在包含一个 HtmlDiff 类,该类创建一个 HTML 表格,显示文本的两个版本的并排比较。 (丹·加斯供稿。)

  • email 包已更新到 3.0 版,它删除了各种已弃用的 API,并取消了对 2.3 之前的 Python 版本的支持。 该包的 3.0 版本使用新的 MIME 消息增量解析器,可在 email.FeedParser 模块中使用。 新的解析器不需要将整个消息读入内存,并且如果消息格式错误也不会引发异常; 相反,它会在消息的 defect 属性中记录任何问题。 (由 Anthony Baxter、Barry Warsaw、Thomas Wouters 等开发。)

  • heapq 模块已转换为 C。 由此带来的十倍速度提升使该模块适用于处理大量数据。 此外,该模块还有两个新函数 nlargest()nsmallest(),它们使用堆来查找数据集中的 N 个最大值或最小值,而无需进行完整排序。 (雷蒙德·赫廷格供稿。)

  • httplib 模块现在包含在各种与 HTTP 相关的 RFC 文档中定义的 HTTP 状态代码的常量。 常量的名称有 OKCREATEDCONTINUEMOVED_PERMANENTLY; 使用 pydoc 获取完整列表。 (由安德鲁·埃兰提供。)

  • imaplib 模块现在支持 IMAP 的 THREAD 命令(由 Yves Dionne 提供)和新的 deleteacl()myrights() 方法(由 Arnaud Mazin 提供)。

  • itertools 模块获得了 groupby(iterable[, *func*]) 功能。 iterable 是可以迭代返回元素流的东西,可选的 func 参数是一个函数,它接受一个元素并返回一个键值; 如果省略,键就是元素本身。 groupby() 然后将元素分组为具有匹配键值的子序列,并返回一系列包含键值和子序列迭代器的 2 元组。

    这是一个更清楚的例子。 key 函数只返回一个数字是偶数还是奇数,所以 groupby() 的结果是返回连续运行的奇数或偶数。

    >>> import itertools
    >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
    >>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
    ...    print key_val, list(it)
    ...
    0 [2, 4, 6]
    1 [7]
    0 [8]
    1 [9, 11]
    0 [12, 14]
    >>>

    groupby() 通常与排序输入一起使用。 groupby() 的逻辑类似于 Unix uniq 过滤器,这使得它可以方便地消除、计数或识别重复元素:

    >>> word = 'abracadabra'
    >>> letters = sorted(word)   # Turn string into a sorted list of letters
    >>> letters
    ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
    >>> for k, g in itertools.groupby(letters):
    ...    print k, list(g)
    ...
    a ['a', 'a', 'a', 'a', 'a']
    b ['b', 'b']
    c ['c']
    d ['d']
    r ['r', 'r']
    >>> # List unique letters
    >>> [k for k, g in groupby(letters)]
    ['a', 'b', 'c', 'd', 'r']
    >>> # Count letter occurrences
    >>> [(k, len(list(g))) for k, g in groupby(letters)]
    [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]

    (由 Hye-Shik Chang 提供。)

  • itertools 还获得了一个名为 tee(iterator, N) 的函数,该函数返回复制 iteratorN 独立迭代器。 如果省略 N,则默认为 2。

    >>> L = [1,2,3]
    >>> i1, i2 = itertools.tee(L)
    >>> i1,i2
    (<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
    >>> list(i1)               # Run the first iterator to exhaustion
    [1, 2, 3]
    >>> list(i2)               # Run the second iterator to exhaustion
    [1, 2, 3]

    请注意, tee() 必须保留迭代器返回值的副本; 在最坏的情况下,它可能需要保留所有这些。 因此,如果前导迭代器可以在长输入流中远远领先于尾随迭代器,则应谨慎使用此方法。 如果间隔很大,那么您不妨使用 list() 代替。 当迭代器彼此紧密跟踪时,tee() 是理想的。 可能的应用包括书签、窗口化或前瞻迭代器。 (雷蒙德·赫廷格供稿。)

  • 许多函数被添加到 locale 模块,例如 bind_textdomain_codeset() 指定特定编码和一系列 l*gettext() 函数,以所选编码返回消息。 (古斯塔沃·尼迈耶供稿。)

  • logging 包的 basicConfig() 函数中添加了一些关键字参数以简化日志配置。 默认行为是将消息记录到标准错误,但可以指定各种关键字参数以记录到特定文件、更改日志记录格式或设置日志记录级别。 例如:

    import logging
    logging.basicConfig(filename='/var/log/application.log',
        level=0,  # Log all messages
        format='%(levelname):%(process):%(thread):%(message)')

    logging 包的其他新增功能包括 log(level, msg) 便利方法,以及按时间间隔轮换其日志文件的 TimedRotatingFileHandler 类。 该模块已经有 RotatingFileHandler,一旦文件超过一定大小,它就会轮换日志。 这两个类都源自一个新的 BaseRotatingHandler 类,该类可用于实现其他旋转处理程序。

    (由 Vinay Sajip 实施的更改。)

  • marshal 模块现在在解包数据结构时共享内部字符串。 这可能会缩小某些 pickle 字符串的大小,但主要效果是使 .pyc 文件明显更小。 (由 Martin von Löwis 提供。)

  • nntplib 模块的 NNTP 类获得了 description()descriptions() 方法来检索单个组或一系列组的新闻组描述。 (由 Jürgen A. 艾哈德。)

  • operator模块增加了两个新功能,attrgetter(attr)itemgetter(index)。 这两个函数都返回带有单个参数并返回相应属性或项目的可调用对象; 当与 map()sorted() 一起使用时,这些可调用函数成为出色的数据提取器。 例如:

    >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
    >>> map(operator.itemgetter(0), L)
    ['c', 'd', 'a', 'b']
    >>> map(operator.itemgetter(1), L)
    [2, 1, 4, 3]
    >>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
    [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

    (雷蒙德·赫廷格供稿。)

  • optparse 模块以各种方式更新。 该模块现在通过 gettext.gettext() 传递其消息,从而可以国际化 Optik 的帮助和错误消息。 选项的帮助消息现在可以包含字符串 '%default',它将被选项的默认值替换。 (由格雷格·沃德提供。)

  • 长期计划是在未来的 Python 版本中弃用 rfc822 模块,以支持 email 包。 为此,email.Utils.formatdate() 功能已更改,使其可用作 rfc822.formatdate() 的替代品。 考虑到这一点,您可能希望编写新的电子邮件处理代码。 (由 Anthony Baxter 实施的更改。)

  • 一个新的 urandom(n) 函数被添加到 os 模块,返回一个包含 n 字节随机数据的字符串。 此函数提供对特定于平台的随机源的访问,例如 Linux 上的 /dev/urandom 或 Windows CryptoAPI。 (由特雷弗·佩林提供。)

  • 另一个新函数:如果 path 指定的文件存在,os.path.lexists(path) 返回 true,无论它是否是符号链接。 这与现有的 os.path.exists(path) 函数不同,如果 path 是指向不存在的目标的符号链接,则该函数返回 false。 (贝尼·切尔尼亚夫斯基供稿。)

  • 一个新的 getsid() 函数被添加到 os 模块下的 posix 模块中。 (由 J. 雷诺。)

  • poplib 模块现在支持 POP over SSL。 (由赫克托·乌尔图比亚提供。)

  • profile 模块现在可以分析 C 扩展函数。 (由尼克巴斯汀提供。)

  • random 模块有一个名为 getrandbits(N) 的新方法,它返回一个长度为 N 位的长整数。 现有的 randrange() 方法现在在适当的地方使用 getrandbits(),从而使任意大的随机数的生成更加高效。 (雷蒙德·赫廷格供稿。)

  • re 模块接受的正则表达式语言被扩展为简单的条件表达式,写为 (?(group)A|B)group 是数字组 ID 或在表达式前面用 (?P<group>...) 定义的组名称。 如果指定的组匹配,则将针对字符串测试正则表达式模式 A; 如果组不匹配,则将使用模式 B。 (古斯塔沃·尼迈耶供稿。)

  • 由于 Gustavo Niemeyer 的大量工作,re 模块也不再是递归的。 在递归正则表达式引擎中,某些模式会导致消耗大量 C 堆栈空间,并且可能会溢出堆栈。 例如,如果将 a 字符的 30000 字节字符串与表达式 (a|b)+ 进行匹配,则每个字符消耗一个堆栈帧。 Python 2.3 尝试检查堆栈溢出并引发 RuntimeError 异常,但某些模式可能会回避检查,如果您不走运,Python 可能会出现段错误。 Python 2.4 的正则表达式引擎可以毫无问题地匹配这种模式。

  • signal 模块现在对 signal.signal() 函数的参数执行更严格的错误检查。 例如,您不能在 SIGKILL 信号上设置处理程序; 以前版本的 Python 会悄悄地接受这一点,但 2.4 会引发 RuntimeError 异常。

  • socket 模块中添加了两个新函数。 socketpair() 返回一对连接的套接字,getservbyport(port) 查找给定端口号的服务名称。 (由 Dave Cole 和 Barry Warsaw 提供。)

  • sys.exitfunc() 函数已被弃用。 代码应该使用现有的 atexit 模块,它可以正确处理调用多个退出函数。 最终 sys.exitfunc() 将成为纯粹的内部接口,只能通过 atexit 访问。

  • tarfile 模块现在默认生成 GNU 格式的 tar 文件。 (拉尔斯·古斯塔贝尔供稿。)

  • threading 模块现在有一种优雅简单的方法来支持线程本地数据。 该模块包含一个 local 类,其属性值对于不同的线程是本地的。

    import threading
    
    data = threading.local()
    data.number = 42
    data.url = ('www.python.org', 80)

    其他线程可以为 numberurl 属性分配和检索它们自己的值。 您可以子类化 local 来初始化属性或添加方法。 (由吉姆富尔顿提供。)

  • timeit 模块现在会在计时循环期间自动禁用定期垃圾收集。 此更改使连续计时更具可比性。 (雷蒙德·赫廷格供稿。)

  • weakref 模块现在支持更多种类的对象,包括 Python 函数、类实例、集合、冻结集、双端队列、数组、文件、套接字和正则表达式模式对象。 (雷蒙德·赫廷格供稿。)

  • xmlrpclib 模块现在支持多调用扩展,用于在单个 HTTP 操作中传输多个 XML-RPC 调用。 (由布赖恩昆兰提供。)

  • mpzrotorxreadlines 模块已被移除。

曲奇库

cookielib 库支持 HTTP cookie 的客户端处理,镜像 Cookie 模块的服务器端 cookie 支持。 Cookie 存储在 Cookie 罐中; 该库将 Web 服务器提供的 cookie 透明地存储在 cookie jar 中,并在连接到服务器时从 jar 中获取 cookie。 与 Web 浏览器一样,策略对象控制是否接受 cookie。

为了跨会话存储 cookie,提供了两种 cookie jar 实现:一种以 Netscape 格式存储 cookie,以便应用程序可以使用 Mozilla 或 Lynx cookie 文件,另一种以与 Perl libwww 库相同的格式存储 cookie。

urllib2 已更改为与 cookielib 交互:HTTPCookieProcessor 管理访问 URL 时使用的 cookie jar。

该模块由 John J. 李。


文档测试

doctest 模块在 Edward Loper 和 Tim Peters 的帮助下进行了大量重构。 测试仍然可以像运行 doctest.testmod() 一样简单,但重构允许以各种方式自定义模块的操作

新的 DocTestFinder 类从给定对象的文档字符串中提取测试:

def f (x, y):
    """>>> f(2,2)
4
>>> f(3,2)
6
    """
    return x*y

finder = doctest.DocTestFinder()

# Get list of DocTest instances
tests = finder.find(f)

新的 DocTestRunner 类然后运行单独的测试并可以生成结果摘要:

runner = doctest.DocTestRunner()
for t in tests:
    tried, failed = runner.run(t)

runner.summarize(verbose=1)

上面的示例产生以下输出:

1 items passed all tests:
   2 tests in f
2 tests in 1 items.
2 passed and 0 failed.
Test passed.

DocTestRunner 使用 OutputChecker 类的实例将预期输出与实际输出进行比较。 此类采用许多不同的标志来自定义其行为; 雄心勃勃的用户还可以编写一个全新的 OutputChecker 子类。

默认输出检查器提供了许多方便的功能。 例如,使用 doctest.ELLIPSIS 选项标志,预期输出中的省略号 (...) 匹配任何子字符串,从而更容易适应以次要方式变化的输出:

def o (n):
    """>>> o(1)
<__main__.C instance at 0x...>
>>>
"""

另一个特殊字符串 <BLANKLINE> 匹配空行:

def p (n):
    """>>> p(1)
<BLANKLINE>
>>>
"""

另一个新功能是通过指定 doctest.REPORT_UDIFF(统一差异)、doctest.REPORT_CDIFF(上下文差异)或 doctest 来生成输出的差异样式显示。 REPORT_NDIFF (delta-style) 选项标志。 例如:

def g (n):
    """>>> g(4)
here
is
a
lengthy
>>>"""
    L = 'here is a rather lengthy list of words'.split()
    for word in L[:n]:
        print word

使用指定的 doctest.REPORT_UDIFF 运行上述函数的测试,您会得到以下输出:

**********************************************************************
File "t.py", line 15, in g
Failed example:
    g(4)
Differences (unified diff with -expected +actual):
    @@ -2,3 +2,3 @@
     is
     a
    -lengthy
    +rather
**********************************************************************

构建和 C API 更改

Python 的构建过程和 C API 的一些更改是:

  • 为扩展函数的常见返回值添加了三个新的便利宏:Py_RETURN_NONEPy_RETURN_TRUEPy_RETURN_FALSE。 (由布雷特·坎农提供。)
  • 另一个新宏 Py_CLEAR(obj) 减少了 obj 的引用计数并将 obj 设置为空指针。 (由吉姆富尔顿提供。)
  • 一个新函数 PyTuple_Pack(N, obj1, obj2, ..., objN) 从 Python 对象的可变长度参数列表构造元组。 (雷蒙德·赫廷格供稿。)
  • 一个新函数 PyDict_Contains(d, k) 实现了快速字典查找,而不会屏蔽查找过程中引发的异常。 (雷蒙德·赫廷格供稿。)
  • 如果 Py_IS_NAN(X) 宏的浮点或双参数 X 是 NaN,则该宏返回 1。 (由蒂姆·彼得斯提供。)
  • C 代码可以通过使用新的 PyEval_ThreadsInitialized() 函数来判断是否执行了任何线程操作,从而避免不必要的锁定。 如果此函数返回 false,则不需要锁定操作。 (由尼克·科格兰提供。)
  • 新函数 PyArg_VaParseTupleAndKeywords()PyArg_ParseTupleAndKeywords() 相同,但采用 va_list 而不是多个参数。 (由格雷格查普曼提供。)
  • 新的方法标志 METH_COEXISTS 允许在槽中定义的函数与具有相同名称的 PyCFunction 共存。 这可以将诸如 set.__contains__() 之类的方法的访问时间减半。 (雷蒙德·赫廷格供稿。)
  • 现在可以使用解释器本身的额外分析来构建 Python,旨在帮助开发 Python 核心的人。 为 configure 脚本提供 --enable-profiling 将使您能够使用 gprof 对解释器进行分析,并提供 --with-tsc 开关可以使用 Pentium 的时间戳进行分析- 柜台登记。 请注意,--with-tsc 开关的名称略有错误,因为分析功能也适用于 PowerPC 平台,尽管该处理器架构并未将该寄存器称为“TSC 寄存器”。 (由杰里米·希尔顿提供。)
  • tracebackobject 类型已重命名为 PyTracebackObject

特定于端口的更改

  • Windows 端口现在在 MSVC++ 7.1 和版本 6 下构建。 (由 Martin von Löwis 提供。)


移植到 Python 2.4

本节列出了可能需要更改代码的先前描述的更改:

  • 过大的左移和十六进制/八进制常量不再触发 FutureWarning 并返回限制为 32 或 64 位的值; 相反,它们返回一个长整数。
  • 整数运算将不再触发 OverflowWarningOverflowWarning 警告将在 Python 2.5 中消失。
  • zip() 内置函数和 itertools.izip() 现在返回一个空列表,而不是在不带参数调用时引发 TypeError 异常。
  • 您无法再比较 datetime 模块提供的 datedatetime 实例。 不同类的两个实例现在总是不相等的,相对比较 (<, >) 将引发 TypeError
  • dircache.listdir() 现在将异常传递给调用者而不是返回空列表。
  • LexicalHandler.startDTD() 用于以错误的顺序接收公共和系统 ID。 这已得到纠正; 需要修复依赖错误顺序的应用程序。
  • fcntl.ioctl() 现在警告 mutate 参数是否被省略和相关。
  • tarfile 模块现在默认生成 GNU 格式的 tar 文件。
  • 导入模块时遇到失败不再在 sys.modules 中留下部分初始化的模块对象。
  • None 现在是一个常数; 将新值绑定到名称 None 的代码现在是一个语法错误。
  • signals.signal() 函数现在针对某些非法值引发 RuntimeError 异常; 以前这些错误会默默传递。 例如,您不能再在 SIGKILL 信号上设置处理程序。


致谢

作者要感谢以下人员对本文的各种草稿提供建议、更正和帮助:Koray Can、Hye-Shik Chang、Michael Dyck、Raymond Hettinger、Brian Hurt、Hamish Lawson、Fredrik Lundh、Sean Reifschneider、Sadruddin拒绝。