Differences between revisions 5 and 6
Revision 5 as of 2007-06-19 15:08:58
Size: 19319
Editor: ZoomQuiet
Comment:
Revision 6 as of 2007-06-19 18:08:40
Size: 19593
Editor: HuangYi
Comment:
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:
#pragma section-numbers on
'''
[http://www.artima.com/weblogs/viewpost.jsp?thread=208549 Python 3000 状态汇报 (长版!)]
'''
::-- ZoomQuiet [[[DateTime(2007-06-19T15:02:49Z)]]]
[[TableOfContents]]
## 默许导航,请保留
[[Include(CPUGnav)]]
{{{
by Guido van Rossum
June 19, 2007
}}}

  Summary:: Here's a long-awaited update on where the Python 3000 project stands. We're looking at a modest two months of schedule slip, and many exciting new features. I'll be presenting this in person several times over the next two months.


= Project Overview =

== Early History ==

The first time I came up with the idea of Python 3000 was probably at a Python conference in the year 2000. The name was a take on Windows 2000. For a long time there wasn't much more than a list of regrets and flaws that were impossible to fix without breaking backwards compatibility. The idea was that Python 3000 would be the first Python release to give up backwards compatibility in favor of making it the best language going forward.

== Recent History ==

Maybe a year and a half ago (not coincidentally around the time I started working for Google, which gave me more time for work on Python than I had had in a long time) I decided it was time to start designing and planning Python 3000 for real. Together with the Python developer and user community I came up with a Plan. We created a new series of PEPs (Python Enhancement Proposals) whose numbers started with 3000. There was a PEP 3000 already, maintained by others in the community, which was mostly a laundry list of ideas that had been brought up as suitable for implementation in Python 3000. This was renamed to PEP 3100; PEP 3000 became the document describing the philosophy and schedule of the project.

Since then, we have, well, perhaps not moved mountains, but certainly a lot of water has flowed under the bridge of the python-dev mailing list, and later the separate python-3000 mailing list.

== Tentative Schedule ==

A schedule was first published around a year ago; we were aiming for a first 3.0 alpha release by the end of the first half of 2007, with a final 3.0 release a year later. (Python 3.0 will be the version when it is released; "Python 3000" or "Py3k" is the project's code name.)

This schedule has slipped a bit; we're now looking at a first alpha by the end of August, and the final release is moved up by the same amount. (The schedule slip is largely due to the amount of work resulting from the transition to all-Unicode text strings and mutable raw bytes arrays. Perhaps I also haven't delegated enough of the work to other developers; a mistake I am frantically trying to correct.)

== Python 2.6 ==

There will be a "companion" release of Python 2.6, scheduled to be released a few months before 3.0, with an alpha release about 4 months before then (i.e., well after the first 3.0 alpha). The next two sections explain its role. If you're not interested in living on the bleeding edge, 2.6 is going to be next version of Python you'll be using, and it will not be very different from 2.5.

= Compatibility and Transition =

== Compatibility ==

Python 3.0 will break backwards compatibility. Totally. We're not even aiming for a specific common subset. (Of course there will be a common subset, probably quite large, but we're not aiming to make it convenient or even possible to write significant programs in this subset. It is merely the set of features that happen to be unchanged from 2.6 to 3.0.)

Python 2.6, on the other hand, will maintain full backwards compatibility with Python 2.5 (and previous versions to the extent possible), but it will also support forward compatibility, in the following ways:

    * Python 2.6 will support a "Py3k warnings mode" which will warn dynamically (i.e. at runtime) about features that will stop working in Python 3.0, e.g. assuming that range() returns a list.
    * Python 2.6 will contain backported versions of many Py3k features, either enabled through __future__ statements or simply by allowing old and new syntax to be used side-by-side (if the new syntax would be a syntax error in 2.x).
    * Complementary to the forward compatibility features in 2.6, there will be a separate source code conversion tool. This tool can do a context-free source-to-source translation. As a (very simply) example, it can translate apply(f, args) into f(*args). However, the tool cannot do data flow analysis or type inferencing, so it simply assumes that apply in this example refers to the old built-in function.

== Transitional Development ==

The recommended development model for a project that needs to support Python 2.6 and 3.0 simultaneously is as follows:

   0. Start with excellent unit tests, ideally close to full coverage.
   1. Port the project to Python 2.6.
   2. Turn on the Py3k warnings mode.
   3. Test and edit until no warnings remain.
   4. Use the 2to3 tool to convert this source code to 3.0 syntax. Do not manually edit the output!
   5. Test the converted source code under 3.0.
   6. If problems are found, make corrections to the 2.6 version of the source code and go back to step 3.
   7. When it's time to release, release separate 2.6 and 3.0 tarballs (or whatever archive form you use for releases).

The conversion tool produces high-quality source code, that in many cases is indistinguishable from manually converted code. Still, it is strongly recommended not to start editing the 3.0 source code until you are ready to reduce 2.6 support to pure maintenance (i.e. the moment when you would normally move the 2.6 code to a maintenance branch anyway).

Step (1) is expected to take the usual amount of effort of porting any project to a new Python version. We're trying to make the transition from 2.5 to 2.6 as smooth as possible.

If the conversion tool and the forward compatibility features in Python 2.6 work out as expected, steps (2) through (6) should not take much more effort than the typical transition from Python 2.x to 2.(x+1).

== Status of Individual Features ==

There are too many changes to list them all here; instead, I will refer to the PEPs. However, I'd like to highlight a number of features that I find to be significant or expect to be of particular interest or controversial.
Unicode, Codecs and I/O

We're switching to a model known from Java: (immutable) text strings are Unicode, and binary data is represented by a separate mutable "bytes" data type. In addition, the parser will be more Unicode-friendly: the default source encoding will be UTF-8, and non-ASCII letters can be used in identifiers. There is some debate still about normalization, specific alphabets, and whether we can reasonably support right-to-left scripts. However, the standard library will continue to use ASCII only for identifiers, and limit the use of non-ASCII in comments and string literals to unit tests for some of the Unicode features, and author names.

We will use "..." or '...' interchangeably for Unicode literals, and b"..." or b'...' for bytes literals. For example, b'abc' is equivalent to creating a bytes object using the expression bytes([97, 98, 99]).

We are adopting a slightly different approach to codecs: while in Python 2, codecs can accept either Unicode or 8-bits as input and produce either as output, in Py3k, encoding is always a translation from a Unicode (text) string to an array of bytes, and decoding always goes the opposite direction. This means that we had to drop a few codecs that don't fit in this model, for example rot13, base64 and bz2 (those conversions are still supported, just not through the encode/decode API).

=== New I/O Library ===

The I/O library is also changing in response to these changes. I wanted to rewrite it anyway, to remove the dependency on the C stdio library. The new distinction between bytes and text strings required a (subtle) change in API, and the two projects were undertake hand in hand. In the new library, there is a clear distinction between binary streams (opened with a mode like "rb" or "wb") and text streams (opened with a mode not containing "b"). Text streams have a new attribute, the encoding, which can be set explicitly when the stream is opened; if no encoding is specified, a system-specific default is used (which might use guessing when an existing file is being opened).

Read operations on binary streams return bytes arrays, while read operations on text streams return (Unicode) text strings; and similar for write operations. Writing a text string to a binary stream or a bytes array to a text stream will raise an exception.

Otherwise, the API is kept pretty compatible. While there is still a built-in open() function, the full definition of the new I/O library is available from the new io module. This module also contains abstract base classes (see below) for the various stream types, a new implementation of StringIO, and a new, similar class BytesIO, which is like StringIO but implements a binary stream, hence reading and writing bytes arrays.

=== Printing and Formatting ===

Two more I/O-related features: the venerable print statement now becomes a print() function, and the quirky % string formatting operator will be replaced with a new format()` method on string objects.

Turning print into a function usually makes some eyes roll. However, there are several advantages: it's a lot easier to refactor code using print() functions to use e.g. the logging package instead; and the print syntax was always a bit controversial, with its >>file and unique semantics for a trailing comma. Keyword arguments take over these roles, and all is well.

Similarly, the new format() method avoids some of the pitfalls of the old % operator, especially the surprising behavior of "%s" % x when x is a tuple, and the oft-lamented common mistake of accidentally leaving off the final 's' in %(name)s. The new format strings use {0}, {1}, {2}, ... to reference positional arguments to the format() method, and {a}, {b}, ... to reference keyword arguments. Other features include {a.b.c} for attribute references and even {a[b]} for mapping or sequence access. Field lengths can be specified like this: {a:8}; this notation also supports passing on other formatting options.

The format() method is extensible in a variety of dimensions: by defining a __format__() special method, data types can override how they are formatted, and how the formatting parameters are interpreted; you can also create custom formatting classes, which can be used e.g. to automatically provide local variables as parameters to the formatting operations.

== Changes to the Class and Type System ==

You might have guessed that "classic classes" finally bite the dust. The built-in class object is the default base class for new classes. This makes room for a variety of new features.

    *{{{

      Class decorators. These work just like function decorators:

      @art_deco
      class C:
          ...
}}}
    *

      Function and method signatures may now be "annotated". The core language assigns no meaning to these annotations (other than making them available for introspection), but some standard library modules may do so; for example, generic functions (see below) can use these. The syntax is easy to read:
{{{
      def foobar(a: Integer, b: Sequence) -> String:
          ...
}}}
    *

      New metaclass syntax. Instead of setting a variable __metaclass__ in the body of a class, you must now specify the metaclass using a keyword parameter in the class heading, e.g.:
{{{
      class C(bases, metaclass=MyMeta):
          ...
}}}
    *

      Custom class dictionaries. if the metaclass defines a __prepare__() method, it will be called before entering the class body, and whatever it returns will be used instead of a standard dictionary as the namespace in which the class body is executed. This can be used, amongst others, to implement a "struct" type where the order in which elements are defined is significant.
    *
{{{
      You can specify the bases dynamically, e.g.:

      bases = (B1, B2)

      class C(*bases):
          ...
}}}
    *

      Other keyword parameters are also allowed in the class heading; these are passed to the metaclass' __new__ method.
    *

      You can override the isinstance() and issubclass() tests, by defining class methods named __instancecheck__() or __subclasscheck()__, respectively. When these are defined, isinstance(x, C) is equivalent to C.__instancecheck__(x), and issubclass(D, C) to C.__subclasscheck__(D).
    *

      Voluntary Abstract Base Classes (ABCs). If you want to define a class whose instances behaves like a mapping (for example), you can voluntarily inherit from the class abc.Mapping. On the one hand, this class provides useful mix-in behavior, replacing most of the functionality of the old UserDict and DictMixin classes. On the other hand, systematic use of such ABCs can help large frameworks do the right thing with less guesswork: in Python 2, it's not always easy to tell whether an object is supposed to be a sequence or a mapping when it defines a __getitem__() method. The following standard ABCs are provided: Hashable, Iterable, Iterator, Sized, Container, Callable; Set, MutableSet; Mapping, MutableMapping; Sequence, MutableSequence; Number, Complex, Real, Rational, Integer. The io module also defines a number of ABCs, so for the first time in Python's history we will have a specification for the previously nebulous concept file-like. The power of the ABC framework lies in the ability (borrowed from Zope interfaces) to "register" a concrete class X as "virtually inheriting from" an ABC Y, where X and Y are written by different authors and appear in different packages. (To clarify, when virtual inheritance is used, the mix-in behavior of class Y is not made available to class X; the only effect is that issubclass(X, Y) will return True.)
    *

      To support the definition of ABCs which requires that concrete classes actually implement the full interface, the decorator @abc.abstractmethod can be used to declare abstract methods (only in classes whose metaclass is or derives from abc.ABCMeta).
    *

      Generic Functions. The inclusion of this feature, described in PEP 3124, is somewhat uncertain, as work on the PEP seems to have slowed down to a standstill. Hopefully the pace will pick up again. It supports function dispatch based on the type of all the arguments, rather than the more conventional dispatch based on the class of the target object (self) only.

= Other Significant Changes =

Just the highlights.

== Exception Reform ==

    * String exceptions are gone (of course).
    * All exceptions must derive from BaseException and preferably from Exception.
    * We're dropping StandardException.
    * Exceptions no longer act as sequences. Instead, they have an attribute args which is the sequence of arguments passed to the constructor.
    * The except E, e: syntax changes to except E as e; this avoids the occasional confusion by except E1, E2:.
    * The variable named after as in the except clause is forcefully deleted upon exit from the except clause.
    * sys.exc_info() becomes redundant (or may disappear): instead, e.__class__ is the exception type, and e.__traceback__ is the traceback.
    * Additional optional attributes __context__ is set to the "previous" exception when an exception occurs in an except or finally clause; __cause__ can be set explicitly when re-raising an exception, using raise E1 from E2.
    * The old raise syntax variants raise E, e and raise E, e, tb are gone.

== Integer Reform ==

    * There will be only one built-in integer type, named 'int', whose behavior is that of 'long' in Python 2. The 'L' literal suffix disappears.
    * 1/2 will return 0.5, not 0. (Use 1//2 for that.)
    * Octal literal syntax changes to 0o777, to avoid confusing younger developers.
    * Binary literals: 0b101 == 5, bin(5) == '0b101'.

Iterators or Iterables instead of Lists

    * dict.keys() and dict.items() return sets (views, really); dict.values() returns an iterable container view. The iter*() variants disappear.
    * range() returns the kind of object that xrange() used to return; xrange() disappears.
    * zip(), map(), filter() return iterables (like their counterparts in itertools already do).

== Miscellaneous ==

    * The nonlocal statement lets you assign to variables in outer (non-global) scopes.
    * Set literals: {1, 2, 3} and even set comprehensions: {x for x in y if P(x)}. Note that the empty set is set(), since {} is an empty dict!
    * reduce() is gone. This doesn't mean I don't like higher-order functions; it simply reflects that almost all code that uses reduce() becomes more readable when rewritten using a plain old for-loop. (Example.)
    * lambda, however, lives.
    * The backtick syntax, often hard to read, is gone (use repr()), and so is the <> operator (use !=; it was too flagrant a violation of TOOWTDI).

= Library Reform =

I don't want to say too much about the changes to the standard library, as this is a project that will only get under way for real after 3.0a1 is released, and I will not personally be overseeing it (the core language is all I can handle). It is clear already that we're removing a lot of unsupported or simply outdated cruft (e.g. many modules only applicable under SGI IRIX), and we're trying to rename modules with CapWords names like StringIO or UserDict.

== And Finally ==

Did I mention that lambda lives? I still get the occasional request to preserve it, so I figured I'd mention it twice. Don't worry, that request has been granted for over a year now.

= Speaking Engagements =

I'll be presenting this (and more) in person at several events in the near future:

    * USENIX, June 20, 11am, Santa Clara, CA (a Q&A format) http://www.usenix.org/events/usenix07/
    * Google's Phoenix, AZ office, June 21, 7pm (open to the public!)
    * O'Reilly foo camp, June 23, Sebastopol, CA (get me drunk first :-) http://foocamp.crowdvine.com
    * CWI, Amsterdam, July 5, 3pm (Python's cradle!) http://www.cwi.nl
    * EuroPython, Vilnius, Lithuania, July 10 (keynote) http://www.europython.org/sections/tracks_and_talks/draft-timetable
    * OSCON, Portland, OR, July 26, 2:35pm (Python track) http://conferences.oreillynet.com/cs/os2007/view/e_sess/12753



= About the Blogger =

||http://www.artima.com/images/guido.jpg|| Guido van Rossum is the creator of Python, one of the major programming languages on and off the web. The Python community refers to him as the BDFL (Benevolent Dictator For Life), a title straight from a Monty Python skit. He moved from the Netherlands to the USA in 1995, where he met his wife. Until July 2003 they lived in the northern Virginia suburbs of Washington, DC with their son Orlijn, who was born in 2001. They then moved to Silicon Valley where Guido now works for Google (spending 50% of his time on Python!).||


This weblog entry is Copyright © 2007 Guido van Rossum. All rights reserved.


= 反馈 =
[[PageComment2]]
#format rst

:原文: http://www.artima.com/weblogs/viewpost.jsp?thread=208549
:作者: Guido van Rossum
:译者: HuangYi

.. contents::

================================
Python 3000 进度报告(有点长!)
================================

摘要
======

这是大家期待已久的对Python3000项目最新进展的报告。在过去两个月的进度中,产生了许多激动人心的新特性。
在接下来的两个月中,我会分几次亲自来向大家展示这些东西。

项目简介
==========

早期历史
----------

最开始冒出 Python 3000 这个想法貌似还是在 2000 年 Python 大会上。
取 Python 3000 这个名字是从 Windows 2000 这个名字中得来的灵感。
很长一段时间以来,Python 已经积累了许多让我后悔的设计和瑕疵,如果不破坏向后兼容性,根本没办法修正它们。
于是我想为了 Python 日后能够继续轻装上阵,让 Python 3000 成为第一个不考虑向后兼容性的版本。

近期历史
-----------

大概一年半以前(并非巧合,因为那个时候我已经在Google工作了,这让我可以把比以前多得多的时间花在
Python 上面。)
我觉得是时候要开始实际地设计和规划 Python 3000 了。
我与 Python 开发者及用户社区一起整了一个计划出来。
我们建了一个新的 `PEP <http://python.org/dev/peps/>`__ (Python Enhancement Proposals) 系列,
他们的序号从 3000 开始。
那个时候我们已经有了一个 PEP 3000 了,由社区里面其他一些人维护的,那上面已经记录了
许多适合在 Python 3000 中实现的想法清单。
这个 PEP 现在已经更名为 `PEP 3100 <http://python.org/dev/peps/pep-3100/>`__ 。
而 `PEP 3000 <http://python.org/dev/peps/pep-3000/>`__ 现在用来描述整个项目的设计
哲学和时间表了。

从那时候起我们不敢说是撼动了一座大山,
但是在邮件列表 `python-dev <http://mail.python.org/pipermail/python-dev/>`__ 及其后的
`python-3000 <http://mail.python.org/pipermail/python-3000/>`__
的桥洞下面却着实是有着一股巨流在涌动。

暂定时间表
-----------

大约一年前公布了第一份时间表,那时候我们希望能在2007上半年的末尾发布第一个3.0 alpha版本,
然后在一年后发布 3.0 正式版。(Python 3.0 才是发布的版本号,"Python 3000" 和
"Py3K" 只是项目的 code name )

这个时间表已经向后推迟了一些;我们现在希望能在8月份结束的时候发布第一个 alpha
版本。最终版的发布时间自然也要向后顺延了。(这次时间表的推迟主要是因为过渡到全 Unicode 字符串和
可变的字节数组需要做大量的工作。另外也是因为我“放权”不够,没有把更多的工作交给其他
开发人员来做;这个错误我一直在疯狂地弥补。)

Python 2.6
-----------

我们计划在 3.0 发布前的几个月发布一个 Python 2.6 的姐妹版,发布这个版本的 4
个月前会先发布一个 alpha 版本(也就是在第一个 3.0 alpha 版发布之后)。
下面两节会解释这个版本所肩负的任务。
如果你没兴趣跟踪最新的变化(living on the bleeding edge),
那你完全可以使用 Python 2.6 ,它和 2.5 区别并不大。

兼容性和过渡
=============

兼容性
------

Python 3.0 会完全地破坏向后兼容性。
我们甚至不期望某个兼容的子集(当然肯定会有这么一个子集,
只不过我们不打算支持在这个子集中编写重要程序。它
只不过是从 2.6 到 3.0 恰巧没变的那些特性的集合罢了)。

Python 2.6 则会完全保持与 Python 2.5 的向后兼容性
(并尽可能保持与更早版本的向后兼容性),而且它还会
以下面几种方式支持某种意义上的向前兼容性:

* Python 2.6 会支持一个“Py3k 警告模式”,它会在运行时对那些在
  Python 3.0 下无法工作的特性发出警告,比如说把 ``range()`` 函数返回
  的东西当列表用。

* Python 2.6 会包含 Py3k 中许多特性的“向后移植版”,可能是通过 ``__future__`` 语句
  激活这些特性,或者是允许新旧语法同时存在(只要这个新语法在 2.4 中不是个语法错误)。

* 作为 2.6 版向前兼容的补充,到时候还会有一个独立的 `代码转换工具 <http://svn.python.org/view/sandbox/trunk/2to3/>`__
  。这个工具可以做上下文无关的代码转换。举个(非常简单的)例子,它能把
  ``apply(f, args)`` 转换成 ``f(*args)`` 。
  不过这个工具并不能做数据流分析和类型推导,所以它会简单地直接把 ``apply`` 当做
  旧版本中的一个内置函数来处理。

过渡期开发
-------------

对于需要同时支持 Python2.6 和 Python3.0 的项目,我们推荐以下开发模式:

#. 从卓越的单元测试开始,最好是能几乎覆盖整个项目。
#. 然后将项目移植到 Python 2.6。
#. 开启 Py3k 警告模式。
#. 测试、修改循环直到消除所有警告。
#. 使用 2to3(译注:上面提到过的代码转换工具)工具将代码转换到 3.0 的语法。
   **不要手动编辑输出的代码!**
#. 在 3.0 下测试转换后的代码。
#. 如果发现问题,在针对 Python 2.6 的代码中做修改,然后跳到第 4 步继续。
#. 发布的时候,分别发布 2.6 和 3.0 的 tarball (或任何其他你们使用的打包格式)。

转换工具能够产生高质量的代码,而且在许多场合同手动转换的代码没有什么区别。
不过,我们还是 **强烈** 建议不要编辑 3.0 的代码,除非你打算以后对 2.6
版本的代码只会进行维护而不加入新功能(也就是通常你把 2.6 的代码移到一个维护分支的时候)。

完成第二步需要花费的功夫和通常迁移到一个新的 Python
版本所需要的差不多。我们正在努力
让 2.5 到 2.6 的过渡尽可能地流畅。

如果代码转换工具和 Python 2.6 的向前兼容特性能够符合预期目标的话,从第三步到第七步应该不会比
以前一个小版本号的迁移(从Python 2.x 到 2.(x+1))更麻烦。

新特性介绍
============

如果把新特性全部列在这里,那就太多了;所以我建议你去看相关的 PEP。
不过,我还是要强调一些我发现很重要也是很多人感兴趣和比较有争议的一些特性。

Unicode,编解码器和 I/O
-------------------------

我们正在迁移到 Java 处理 Unicode 的模型,那就是:(不可变的)文本字符串就是
Unicode ,而二进制数据则由另一个(可变的)“字节数组”的类型来表达。
另外词法分析器也对 Unicode 更加友好了:默认的源代码的编码将会是 UTF-8,
而且非 ASCII
字母也可以用在标识符里面了,现在还在进行一些这方面讨论,主要集中在标准化、明确非 ASCII 字母表、
是否应该某种程度地支持自右向左的程序几个问题上。不过标准库自然还是会一如既往地只使用
ASCII 字符做标识符,并且限制在注释和字面字符串(string literals)中使用非 ASCII
字母,在单元测试中测试一些 Unicode 特性或者是作者名字的情形除外。

我们将会使用 ``"..."`` 或 ``'...'`` 来表达字面 Unicode 字符串,而 ``b"..."`` 和
``b'...'`` 用来表达字面字节数组。比如, ``b'abc'`` 等价于使用表达式
``bytes([97, 98, 99])`` 创建的字节数组。

我们采用一种和以前稍微不同的编解码器:在 Python 2 中,编解码器既可以接受
Unicode 也可以接受8位字节数组作为输入,同样也可以输出这两种对象的任何一种,而在
Py3k 中编码过程总是从 Unicode 字符串到字节数组的转换,而解码过程则总是相反的方向。
这意味着我们必须丢弃一些不符合这个模型的编解码器,比如 rot13,base64 和 bz2
(当然我们仍然支持这些转换操作,只不过不通过 encode/decode API 了)。

新的 I/O 库
`````````````

针对上面的这些变化 I/O 库自然要做相应的变化了。正好我也早有重写这个库的意思,
以前我就想要除掉它对 C stdio 库的依赖。而现在字节数组和字符串的区别也需要
它的 API 有一个(细微的)变化,the two projects were undertake hand in hand。
在这个新库中,打开二进制流(使用模式 "rb" 或 "wb" 打开)和文本流
(模式名中不包含 "b" )之间将会有明显的区别。文本流有一个新属性,encoding,你可以在
打开流的时候显式地当参数传给它;如果没有指定编码,就会使用系统默认的编码(
打开一个存在的文件时也可以猜它的编码)。

对二进制流的读操作返回的是字节数组,而对文本流的读操作返回(Unicode)字符串;
写操作也类似。给二进制流写入字符串或者给文本流写入字节数组都会抛出异常。

除此以外,API 基本还是和以前差不多。同样会有一个内置的 ``open()`` 函数,
新的 I/O 库在 ``io`` 模块中。这个模块还包含不同类型流的抽象基类
(抽象基类见下文),一个 StringIO 的新实现,还有一个类似 StringIO 的
BytesIO,它实现了一个二进制流,因此也就只能读写字节数组。

print 和 格式化
````````````````

还有两个和 I/O 有关的新特性:古老的 ``print`` 语句变成了 ``print()`` 函数,
而诡异的字符串格式化操作符 ``%`` 也被字符串对象的新方法 ``format()`` 取代。

把 print 变成函数常常让人大吃一惊(makes some eyes roll)。但是它确实还是有一些
好处的,比如:这样可以方便地将使用 ``print`` 的代码重构成(比如说)使用 ``logging``
模块; 并且 ``print`` 的语法一直以来也都存在一些争议,比如 ``>>file`` 和末尾跟一个逗号的独特
语义。现在由关键字参数来完成这些任务,大家都满意了。

同样,新的 ``format()`` 方法也避免了一些 ``%`` 操作符的缺陷,特别是语句 ``"%s" % x`` 当
``x`` 是个元组时让人意外的结果,和许多人经常犯的忘记敲 %(name)s 最后的这个
's' 的失误。新的格式化字符串使用 {0},{1},{2}, ... 来引用传给 ``format()`` 方法位置参数,
用 {a}, {b}, ... 来引用关键字参数。还有其他一些特性如用 {a.b.c} 来访问对象属性,甚至可以用 {a[b]}
访问字典和序列。可以用 {a:8} 来指定转换字符串的长度,使用这个语法也可以传递其他格式化选项。

``format()`` 方法还可以不同的维度进行扩展:通过定义 ``__format__()`` 方法,任何类型可以定义
他们自己格式化的方式和解释格式化参数的方式;你还可以创建自定义的格式化 class ,它可以用来
(比如)自动将局部名字空间当作格式化的参数。

对 class 和类型系统的改变
---------------------------

你可能已经猜到了,"classic classes" 终于退出了历史舞台。内置类型 ``object``
成为新 class 的默认基类。这使得一系列新特性得以实现:

* 类装饰器。他们和函数装饰器非常像:::
  
    @art_deco
    class C:
        ...

* 函数和方法的定义可以加上“签名(annotated)”,语言核心本身并不给这些签名赋予
  特殊的含义(只是在内省时会提供这些元数据),不过一些标准库却可以;比如,
  generic function (见下文)可以使用这些元数据。这个新语法可读性非常好:::

    def foobar(a: Integer, b: Sequence) -> String:
        ...

* 新的 metaclass 语法。以前是在 class 定义体中设置一个变量 ``__metaclass__`` ,
  现在你得在 class 定义头中指定一个关键字参数,比如:::

    class C(bases, metaclass=MyMeta):
        ...

* 自定义 class 字典。如果 metaclass 定义了 __prepare__() 方法,那么在进入 class
  定义体之前会调用它,用它返回的对象取代标准的字典,而 class
  定义体中的属性就用这个对象进行存储。比如说,你可以用这个特性来实现一个
  "struct" 类型,因为对于 "struct" 来说属性定义的
  顺序是非常关键的。

* 你可以动态地指定基类,比如:::
  
    bases = (B1, B2)
    class C(*bases):
        ...

* 在 class 定义头中还可以使用其他的关键字参数;这些参数都被传给 metaclass 的
  ``__new__`` 方法。

* 你可以通过定义 ``__instancecheck__()`` 或 ``__subclasscheck__()`` 方法
  重载相应的 ``__isinstance__()`` 、 ``__issubclass__()`` 语义。
  如果定义了这两个方法, ``isinstance(x, C)`` 等价于 ``C.__instancecheck__(x)``
  ,而 ``issubclass(D, C)`` 等价于 ``C.__subclasscheck__(D)`` 。

* 抽象基类(Abstract Base Classes, ABC)。如果你想要定义一个 class ,它的实例
  的行为类似 mapping (举个例子),你就可以继承 class ``abc.Mapping`` 。
  一方面,这个 class 提供 mix-in 的行为,可以提供大部分 ``UserDict`` 和
  ``DictMixin`` 的功能。另一方面,系统地使用这种 ABC 能够帮助大型框架减少猜测
  并获得正确的行为:在 Python 2 中,要判断一个实现了
  ``__getitem__()``
  方法的对象究竟是序列(sequence)还是映射(mapping),还真不是那么简单的事情。
  我们提供了下面这些ABC:Hashable, Iterable, Iterator, Sized, Container,
  Callable; Set, MutableSet; Mapping, MutableMapping; Sequence,
  MutableSequence; Number, Complex, Real, Rational, Integer。 ``io`` 模块
  也定义了许多ABC,所以在 python 历史上,终于对以前定义模糊的“file-like”这个概念
  第一次有了明确的规范。ABC 框架的强大能力来源于(从 zope interface 中学来的)能够
  注册某一个 class X ,让它“虚拟地继承于”一个 ABC Y,而 X 和 Y 可以由不同的作者编写
  ,也可以出现在不同的包中。(需要澄清的是:如果使用的是虚拟继承,class Y 的 mix-in 行为并不会
  作用在 class X 上;唯一的效果只是 ``issubclass(X, Y)`` 返回 ``True`` )

* 抽象基类(ABC)需要确保子类实现了完整的接口,为了支持抽象基类的定义,
  我们引入装饰器 ``@abc.abstractmethod`` 来定义抽象方法(只能用在 metaclass
  为 ``abc.ABCMeta`` 或其子类的 class 中)。

* Generic Functions。是否包含这一特性(PEP 3124 中有描述),其实还不是很确定
  ,因为这个 PEP 的进展越来越慢现在几乎停滞了。希望它的步伐能够重新恢复过来。
  它支持基于所有参数类型的函数分派(译注:简单地说就是静态语言中的重载的动态语言版本),
  而不仅仅是通常的只基于目标对象( ``self`` )的分派。

其他重要变化
--------------

一些精选!

异常
``````

* 字符串异常去掉了。

* 所有异常必须继承自 ``BaseException`` ,最好是直接继承 ``Exception`` 。

* 去掉 ``StandardException`` 。

* 异常不再拥有序列(sequence)的行为。不过现在他们有了一个属性 ``args`` ,
  它就是由传给异常构造函数的参数所组成的序列。

* 语法: ``except E, e:`` 变成 ``except E as e:`` ,这使得语句 ``except E1, E2``
  不再导致混淆。

* ``except`` 子句中 ``as`` 后面的名字在退出 ``except`` 子句时会被强制移除。

* ``sys.exc_info()`` 变得多余了(也许会被去掉):取而代之的是 ``e.__class__`` 是异常
  类型, ``e.__traceback__`` 是 traceback 。

* 如果在 ``except`` 或 ``finally`` 子句中发生异常,会添加另一个可选的属性
  ``__context__`` ,其值为前一个异常对象。重抛出异常时,使用 ``raise E1 from E2``
  可以明确地设置属性 ``__cause__`` 的值。

* 以前的 ``raise`` 语法变种 ``raise E, e`` 和 ``raise E, e, tb`` 已经去掉了。


整数
``````

* 只会有一个内置的整数类型,它就是 ``int`` ,它的行为就和 Python 2 中的
  ``long`` 一样。后缀 'L' 消失。

* 1/2 会返回 0.5 ,而不像以前那样返回 0 。(使用 1//2 来返回 0)

* 表达 16 进制字面量的语法改成了 ``0o777`` ,以免年轻程序员搞糊涂。

* 二进制字面量:0b101 == 5, bin(5) == '0b101'

使用迭代器(Iterator)或可迭代对象(Iterable)而非列表(list)
```````````````````````````````````````````````````````````

* ``dict.keys()`` 和 ``dict.items()`` 返回集合(其实是视图); ``dict.values()``
  返回一个可迭代的容器视图。 ``iter*()`` 系列消失。

* ``range()`` 返回以前的 ``xrange()`` 返回的对象;而 ``xrange()`` 消失。

* ``zip()``, ``map()``, ``filter()`` 返回可迭代对象(和他们在 ``itertools`` 中
  对应的副本目前的行为一样)。

其他
``````

* ``nonlocal`` 语句让你可以重绑定外部(非全局)名字空间中的名字。

* 集合字面量: {1, 2, 3} ,甚至还有 set comprehensions:
  ``{x for x in y if P(x)}`` 。注意空集合是 ``set()`` ,因为
  ``{}`` 是空字典!

* ``reduct()`` 没了。这并不意味着我不喜欢高端函数(higher-order functions);
  只不过是好像所有使用 ``reduct()`` 的代码使用原始的 for 循环重写后都便得
  更可读了。(`例子 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061>`__)

* 不过 ``lambda`` 继续存在。

* ``\``` 语法,通常可读性都不好,去掉了(直接使用 ``repr()`` 吧),同样 ``<>`` 操作符也
  去掉了。(使用 ``!=`` ,这是对 `TOOWIDI <http://www.python.org/dev/peps/pep-0020/>`__
  原则一个臭名昭著的违反!)

标准库的革命
--------------

关于对标准库的变化我不想说太多,因为这部分要到 3.0a1 发布之后才会开始实际的工作。
而且我本人也不会去管它(语言核心就够我弄的了)。显然的是我们会除掉许多不支持了的或者
过时了的垃圾模块(比如许多模块只适用于 SGI IRIX),另外我们还在努力重命名那些以 CapWords
风格命名的模块名字,像 StringIO 或者 UserDict。

最后
------

我前面提到过 lambda 将继续存活吗?我仍然不断收到希望保留 lambda 的请求,
所以我想我得再强调一次。别担心,这个请求我在一年多前就已经同意了。

演讲计划
===========

在最近的几个会议上,我会亲自讲解这些(还有更多的)东西:

* USENIX, June 20, 11am, Santa Clara, CA (a Q&A format) http://www.usenix.org/events/usenix07/
* Google's Phoenix, AZ office, June 21, 7pm (open to the public!)
* O'Reilly foo camp, June 23, Sebastopol, CA (get me drunk first :-) http://foocamp.crowdvine.com
* CWI, Amsterdam, July 5, 3pm (Python's cradle!) http://www.cwi.nl
* EuroPython, Vilnius, Lithuania, July 10 (keynote) http://www.europython.org/sections/tracks_and_talks/draft-timetable
* OSCON, Portland, OR, July 26, 2:35pm (Python track) http://conferences.oreillynet.com/cs/os2007/view/e_sess/12753

.. macro:: [[PageComment2(nosmiley=1, notify=1)]]
Rendering of reStructured text is not possible, please install Docutils.

:原文: http://www.artima.com/weblogs/viewpost.jsp?thread=208549
:作者: Guido van Rossum
:译者: HuangYi

.. contents::

================================
Python 3000 进度报告(有点长!)
================================

摘要
======

这是大家期待已久的对Python3000项目最新进展的报告。在过去两个月的进度中,产生了许多激动人心的新特性。
在接下来的两个月中,我会分几次亲自来向大家展示这些东西。

项目简介
==========

早期历史
----------

最开始冒出 Python 3000 这个想法貌似还是在 2000 年 Python 大会上。
取 Python 3000 这个名字是从 Windows 2000 这个名字中得来的灵感。
很长一段时间以来,Python 已经积累了许多让我后悔的设计和瑕疵,如果不破坏向后兼容性,根本没办法修正它们。
于是我想为了 Python 日后能够继续轻装上阵,让 Python 3000 成为第一个不考虑向后兼容性的版本。

近期历史
-----------

大概一年半以前(并非巧合,因为那个时候我已经在Google工作了,这让我可以把比以前多得多的时间花在
Python 上面。)
我觉得是时候要开始实际地设计和规划 Python 3000 了。
我与 Python 开发者及用户社区一起整了一个计划出来。
我们建了一个新的 `PEP <http://python.org/dev/peps/>`__ (Python Enhancement Proposals) 系列,
他们的序号从 3000 开始。
那个时候我们已经有了一个 PEP 3000 了,由社区里面其他一些人维护的,那上面已经记录了
许多适合在 Python 3000 中实现的想法清单。
这个 PEP 现在已经更名为 `PEP 3100 <http://python.org/dev/peps/pep-3100/>`__ 。
而 `PEP 3000 <http://python.org/dev/peps/pep-3000/>`__ 现在用来描述整个项目的设计
哲学和时间表了。

从那时候起我们不敢说是撼动了一座大山,
但是在邮件列表 `python-dev <http://mail.python.org/pipermail/python-dev/>`__ 及其后的
`python-3000 <http://mail.python.org/pipermail/python-3000/>`__
的桥洞下面却着实是有着一股巨流在涌动。

暂定时间表
-----------

大约一年前公布了第一份时间表,那时候我们希望能在2007上半年的末尾发布第一个3.0 alpha版本,
然后在一年后发布 3.0 正式版。(Python 3.0 才是发布的版本号,"Python 3000" 和
"Py3K" 只是项目的 code name )

这个时间表已经向后推迟了一些;我们现在希望能在8月份结束的时候发布第一个 alpha
版本。最终版的发布时间自然也要向后顺延了。(这次时间表的推迟主要是因为过渡到全 Unicode 字符串和
可变的字节数组需要做大量的工作。另外也是因为我“放权”不够,没有把更多的工作交给其他
开发人员来做;这个错误我一直在疯狂地弥补。)

Python 2.6
-----------

我们计划在 3.0 发布前的几个月发布一个 Python 2.6 的姐妹版,发布这个版本的 4
个月前会先发布一个 alpha 版本(也就是在第一个 3.0 alpha 版发布之后)。
下面两节会解释这个版本所肩负的任务。
如果你没兴趣跟踪最新的变化(living on the bleeding edge),
那你完全可以使用 Python 2.6 ,它和 2.5 区别并不大。

兼容性和过渡
=============

兼容性
------

Python 3.0 会完全地破坏向后兼容性。
我们甚至不期望某个兼容的子集(当然肯定会有这么一个子集,
只不过我们不打算支持在这个子集中编写重要程序。它
只不过是从 2.6 到 3.0 恰巧没变的那些特性的集合罢了)。

Python 2.6 则会完全保持与 Python 2.5 的向后兼容性
(并尽可能保持与更早版本的向后兼容性),而且它还会
以下面几种方式支持某种意义上的向前兼容性:

* Python 2.6 会支持一个“Py3k 警告模式”,它会在运行时对那些在 
  Python 3.0 下无法工作的特性发出警告,比如说把 ``range()`` 函数返回
  的东西当列表用。

* Python 2.6 会包含 Py3k 中许多特性的“向后移植版”,可能是通过 ``__future__`` 语句
  激活这些特性,或者是允许新旧语法同时存在(只要这个新语法在 2.4 中不是个语法错误)。

* 作为 2.6 版向前兼容的补充,到时候还会有一个独立的 `代码转换工具 <http://svn.python.org/view/sandbox/trunk/2to3/>`__ 
  。这个工具可以做上下文无关的代码转换。举个(非常简单的)例子,它能把
  ``apply(f, args)`` 转换成 ``f(*args)`` 。
  不过这个工具并不能做数据流分析和类型推导,所以它会简单地直接把 ``apply`` 当做
  旧版本中的一个内置函数来处理。

过渡期开发
-------------

对于需要同时支持 Python2.6 和 Python3.0 的项目,我们推荐以下开发模式:

#. 从卓越的单元测试开始,最好是能几乎覆盖整个项目。
#. 然后将项目移植到 Python 2.6。
#. 开启 Py3k 警告模式。
#. 测试、修改循环直到消除所有警告。
#. 使用 2to3(译注:上面提到过的代码转换工具)工具将代码转换到 3.0 的语法。
   **不要手动编辑输出的代码!**
#. 在 3.0 下测试转换后的代码。
#. 如果发现问题,在针对 Python 2.6 的代码中做修改,然后跳到第 4 步继续。
#. 发布的时候,分别发布 2.6 和 3.0 的 tarball (或任何其他你们使用的打包格式)。

转换工具能够产生高质量的代码,而且在许多场合同手动转换的代码没有什么区别。
不过,我们还是 **强烈** 建议不要编辑 3.0 的代码,除非你打算以后对 2.6
版本的代码只会进行维护而不加入新功能(也就是通常你把 2.6 的代码移到一个维护分支的时候)。

完成第二步需要花费的功夫和通常迁移到一个新的 Python
版本所需要的差不多。我们正在努力
让 2.5 到 2.6 的过渡尽可能地流畅。

如果代码转换工具和 Python 2.6 的向前兼容特性能够符合预期目标的话,从第三步到第七步应该不会比
以前一个小版本号的迁移(从Python 2.x 到 2.(x+1))更麻烦。

新特性介绍
============

如果把新特性全部列在这里,那就太多了;所以我建议你去看相关的 PEP。
不过,我还是要强调一些我发现很重要也是很多人感兴趣和比较有争议的一些特性。

Unicode,编解码器和 I/O
-------------------------

我们正在迁移到 Java 处理 Unicode 的模型,那就是:(不可变的)文本字符串就是
Unicode ,而二进制数据则由另一个(可变的)“字节数组”的类型来表达。
另外词法分析器也对 Unicode 更加友好了:默认的源代码的编码将会是 UTF-8,
而且非 ASCII
字母也可以用在标识符里面了,现在还在进行一些这方面讨论,主要集中在标准化、明确非 ASCII 字母表、
是否应该某种程度地支持自右向左的程序几个问题上。不过标准库自然还是会一如既往地只使用
ASCII 字符做标识符,并且限制在注释和字面字符串(string literals)中使用非 ASCII
字母,在单元测试中测试一些 Unicode 特性或者是作者名字的情形除外。

我们将会使用 ``"..."`` 或 ``'...'`` 来表达字面 Unicode 字符串,而 ``b"..."`` 和
``b'...'`` 用来表达字面字节数组。比如, ``b'abc'`` 等价于使用表达式
``bytes([97, 98, 99])`` 创建的字节数组。

我们采用一种和以前稍微不同的编解码器:在 Python 2 中,编解码器既可以接受
Unicode 也可以接受8位字节数组作为输入,同样也可以输出这两种对象的任何一种,而在
Py3k 中编码过程总是从 Unicode 字符串到字节数组的转换,而解码过程则总是相反的方向。
这意味着我们必须丢弃一些不符合这个模型的编解码器,比如 rot13,base64 和 bz2 
(当然我们仍然支持这些转换操作,只不过不通过 encode/decode API 了)。

新的 I/O 库
`````````````

针对上面的这些变化 I/O 库自然要做相应的变化了。正好我也早有重写这个库的意思,
以前我就想要除掉它对 C stdio 库的依赖。而现在字节数组和字符串的区别也需要
它的 API 有一个(细微的)变化,the two projects were undertake hand in hand。
在这个新库中,打开二进制流(使用模式 "rb" 或 "wb" 打开)和文本流
(模式名中不包含 "b" )之间将会有明显的区别。文本流有一个新属性,encoding,你可以在
打开流的时候显式地当参数传给它;如果没有指定编码,就会使用系统默认的编码(
打开一个存在的文件时也可以猜它的编码)。

对二进制流的读操作返回的是字节数组,而对文本流的读操作返回(Unicode)字符串;
写操作也类似。给二进制流写入字符串或者给文本流写入字节数组都会抛出异常。

除此以外,API 基本还是和以前差不多。同样会有一个内置的 ``open()`` 函数,
新的 I/O 库在 ``io`` 模块中。这个模块还包含不同类型流的抽象基类
(抽象基类见下文),一个 StringIO 的新实现,还有一个类似 StringIO 的
BytesIO,它实现了一个二进制流,因此也就只能读写字节数组。

print 和 格式化
````````````````

还有两个和 I/O 有关的新特性:古老的 ``print`` 语句变成了 ``print()`` 函数,
而诡异的字符串格式化操作符 ``%`` 也被字符串对象的新方法 ``format()`` 取代。

把 print 变成函数常常让人大吃一惊(makes some eyes roll)。但是它确实还是有一些
好处的,比如:这样可以方便地将使用 ``print`` 的代码重构成(比如说)使用 ``logging``
模块; 并且 ``print`` 的语法一直以来也都存在一些争议,比如 ``>>file`` 和末尾跟一个逗号的独特
语义。现在由关键字参数来完成这些任务,大家都满意了。

同样,新的 ``format()`` 方法也避免了一些 ``%`` 操作符的缺陷,特别是语句 ``"%s" % x`` 当
``x`` 是个元组时让人意外的结果,和许多人经常犯的忘记敲 %(name)s 最后的这个
's' 的失误。新的格式化字符串使用 {0},{1},{2}, ... 来引用传给 ``format()`` 方法位置参数,
用 {a}, {b}, ... 来引用关键字参数。还有其他一些特性如用 {a.b.c} 来访问对象属性,甚至可以用 {a[b]}
访问字典和序列。可以用 {a:8} 来指定转换字符串的长度,使用这个语法也可以传递其他格式化选项。

``format()`` 方法还可以不同的维度进行扩展:通过定义 ``__format__()`` 方法,任何类型可以定义
他们自己格式化的方式和解释格式化参数的方式;你还可以创建自定义的格式化 class ,它可以用来
(比如)自动将局部名字空间当作格式化的参数。

对 class 和类型系统的改变
---------------------------

你可能已经猜到了,"classic classes" 终于退出了历史舞台。内置类型 ``object``
成为新 class 的默认基类。这使得一系列新特性得以实现:

* 类装饰器。他们和函数装饰器非常像:::
  
    @art_deco
    class C:
        ...

* 函数和方法的定义可以加上“签名(annotated)”,语言核心本身并不给这些签名赋予
  特殊的含义(只是在内省时会提供这些元数据),不过一些标准库却可以;比如,
  generic function (见下文)可以使用这些元数据。这个新语法可读性非常好:::

    def foobar(a: Integer, b: Sequence) -> String:
        ...

* 新的 metaclass 语法。以前是在 class 定义体中设置一个变量 ``__metaclass__`` ,
  现在你得在 class 定义头中指定一个关键字参数,比如:::

    class C(bases, metaclass=MyMeta):
        ...

* 自定义 class 字典。如果 metaclass 定义了 __prepare__() 方法,那么在进入 class
  定义体之前会调用它,用它返回的对象取代标准的字典,而 class
  定义体中的属性就用这个对象进行存储。比如说,你可以用这个特性来实现一个
  "struct" 类型,因为对于 "struct" 来说属性定义的
  顺序是非常关键的。

* 你可以动态地指定基类,比如:::
  
    bases = (B1, B2)
    class C(*bases):
        ...

* 在 class 定义头中还可以使用其他的关键字参数;这些参数都被传给 metaclass 的
  ``__new__`` 方法。

* 你可以通过定义 ``__instancecheck__()`` 或 ``__subclasscheck__()`` 方法
  重载相应的 ``__isinstance__()`` 、 ``__issubclass__()`` 语义。
  如果定义了这两个方法, ``isinstance(x, C)`` 等价于 ``C.__instancecheck__(x)``
  ,而 ``issubclass(D, C)`` 等价于 ``C.__subclasscheck__(D)`` 。

* 抽象基类(Abstract Base Classes, ABC)。如果你想要定义一个 class ,它的实例
  的行为类似 mapping (举个例子),你就可以继承 class ``abc.Mapping`` 。
  一方面,这个 class 提供 mix-in 的行为,可以提供大部分 ``UserDict`` 和
  ``DictMixin`` 的功能。另一方面,系统地使用这种 ABC 能够帮助大型框架减少猜测
  并获得正确的行为:在 Python 2 中,要判断一个实现了
  ``__getitem__()``
  方法的对象究竟是序列(sequence)还是映射(mapping),还真不是那么简单的事情。
  我们提供了下面这些ABC:Hashable, Iterable, Iterator, Sized, Container,
  Callable; Set, MutableSet; Mapping, MutableMapping; Sequence,
  MutableSequence; Number, Complex, Real, Rational, Integer。 ``io`` 模块
  也定义了许多ABC,所以在 python 历史上,终于对以前定义模糊的“file-like”这个概念
  第一次有了明确的规范。ABC 框架的强大能力来源于(从 zope interface 中学来的)能够
  注册某一个 class X ,让它“虚拟地继承于”一个 ABC Y,而 X 和 Y 可以由不同的作者编写
  ,也可以出现在不同的包中。(需要澄清的是:如果使用的是虚拟继承,class Y 的 mix-in 行为并不会
  作用在 class X 上;唯一的效果只是 ``issubclass(X, Y)`` 返回 ``True`` )

* 抽象基类(ABC)需要确保子类实现了完整的接口,为了支持抽象基类的定义,
  我们引入装饰器 ``@abc.abstractmethod`` 来定义抽象方法(只能用在 metaclass
  为 ``abc.ABCMeta`` 或其子类的 class 中)。

* Generic Functions。是否包含这一特性(PEP 3124 中有描述),其实还不是很确定
  ,因为这个 PEP 的进展越来越慢现在几乎停滞了。希望它的步伐能够重新恢复过来。
  它支持基于所有参数类型的函数分派(译注:简单地说就是静态语言中的重载的动态语言版本),
  而不仅仅是通常的只基于目标对象( ``self`` )的分派。

其他重要变化
--------------

一些精选!

异常
``````

* 字符串异常去掉了。

* 所有异常必须继承自 ``BaseException`` ,最好是直接继承 ``Exception`` 。

* 去掉 ``StandardException`` 。

* 异常不再拥有序列(sequence)的行为。不过现在他们有了一个属性 ``args`` ,
  它就是由传给异常构造函数的参数所组成的序列。

* 语法: ``except E, e:`` 变成 ``except E as e:`` ,这使得语句 ``except E1, E2`` 
  不再导致混淆。

* ``except`` 子句中 ``as`` 后面的名字在退出 ``except`` 子句时会被强制移除。

* ``sys.exc_info()`` 变得多余了(也许会被去掉):取而代之的是 ``e.__class__`` 是异常
  类型, ``e.__traceback__`` 是 traceback 。

* 如果在 ``except`` 或 ``finally`` 子句中发生异常,会添加另一个可选的属性
  ``__context__`` ,其值为前一个异常对象。重抛出异常时,使用 ``raise E1 from E2``
  可以明确地设置属性 ``__cause__`` 的值。

* 以前的 ``raise`` 语法变种 ``raise E, e`` 和 ``raise E, e, tb`` 已经去掉了。


整数
``````

* 只会有一个内置的整数类型,它就是 ``int`` ,它的行为就和 Python 2 中的
  ``long`` 一样。后缀 'L' 消失。

* 1/2 会返回 0.5 ,而不像以前那样返回 0 。(使用 1//2 来返回 0)

* 表达 16 进制字面量的语法改成了 ``0o777`` ,以免年轻程序员搞糊涂。

* 二进制字面量:0b101 == 5, bin(5) == '0b101'

使用迭代器(Iterator)或可迭代对象(Iterable)而非列表(list)
```````````````````````````````````````````````````````````

* ``dict.keys()`` 和 ``dict.items()`` 返回集合(其实是视图); ``dict.values()``
  返回一个可迭代的容器视图。 ``iter*()`` 系列消失。

* ``range()`` 返回以前的 ``xrange()`` 返回的对象;而 ``xrange()`` 消失。

* ``zip()``, ``map()``, ``filter()`` 返回可迭代对象(和他们在 ``itertools`` 中
  对应的副本目前的行为一样)。

其他
``````

* ``nonlocal`` 语句让你可以重绑定外部(非全局)名字空间中的名字。

* 集合字面量: {1, 2, 3} ,甚至还有 set comprehensions:
  ``{x for x in y if P(x)}`` 。注意空集合是 ``set()`` ,因为
  ``{}`` 是空字典!

* ``reduct()`` 没了。这并不意味着我不喜欢高端函数(higher-order functions);
  只不过是好像所有使用 ``reduct()`` 的代码使用原始的 for 循环重写后都便得
  更可读了。(`例子 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061>`__)

* 不过 ``lambda`` 继续存在。

* ``\``` 语法,通常可读性都不好,去掉了(直接使用 ``repr()`` 吧),同样 ``<>`` 操作符也
  去掉了。(使用 ``!=`` ,这是对 `TOOWIDI <http://www.python.org/dev/peps/pep-0020/>`__
  原则一个臭名昭著的违反!)

标准库的革命
--------------

关于对标准库的变化我不想说太多,因为这部分要到 3.0a1 发布之后才会开始实际的工作。
而且我本人也不会去管它(语言核心就够我弄的了)。显然的是我们会除掉许多不支持了的或者
过时了的垃圾模块(比如许多模块只适用于 SGI IRIX),另外我们还在努力重命名那些以 CapWords
风格命名的模块名字,像 StringIO 或者 UserDict。

最后
------

我前面提到过 lambda 将继续存活吗?我仍然不断收到希望保留 lambda 的请求,
所以我想我得再强调一次。别担心,这个请求我在一年多前就已经同意了。

演讲计划
===========

在最近的几个会议上,我会亲自讲解这些(还有更多的)东西:

* USENIX, June 20, 11am, Santa Clara, CA (a Q&A format) http://www.usenix.org/events/usenix07/ 
* Google's Phoenix, AZ office, June 21, 7pm (open to the public!) 
* O'Reilly foo camp, June 23, Sebastopol, CA (get me drunk first :-) http://foocamp.crowdvine.com 
* CWI, Amsterdam, July 5, 3pm (Python's cradle!) http://www.cwi.nl 
* EuroPython, Vilnius, Lithuania, July 10 (keynote) http://www.europython.org/sections/tracks_and_talks/draft-timetable 
* OSCON, Portland, OR, July 26, 2:35pm (Python track) http://conferences.oreillynet.com/cs/os2007/view/e_sess/12753 

.. macro:: [[PageComment2(nosmiley=1, notify=1)]]

Py3000StatusUpdate (last edited 2009-12-25 07:12:50 by localhost)