What's New in Python 2.6
************************

著者:
   A.M. Kuchling (amk at amk.ca)

This article explains the new features in Python 2.6, released on
October 1, 2008.  The release schedule is described in **PEP 361**.

The major theme of Python 2.6 is preparing the migration path to
Python 3.0, a major redesign of the language.  Whenever possible,
Python 2.6 incorporates new features and syntax from 3.0 while
remaining compatible with existing code by not removing older features
or syntax.  When it's not possible to do that, Python 2.6 tries to do
what it can, adding compatibility functions in a "future_builtins"
module and a "-3" switch to warn about usages that will become
unsupported in 3.0.

"multiprocessing" や "json" といった、いくつか重要な新しいパッケージが
標準ライブラリに追加されましたが、Python 3.0 に何らかも関係しない新機
能はあまり多くはありません。

Python 2.6 ではさらに、たくさんの改善とバグフィックスがソースコードの
ありとあらゆる場所に見られます。Python 2.5 から 2.6 の変更ログを手繰っ
てみると、低く見積もっても、適用されたパッチは 259、フィックスされたバ
グは 612 にのぼります。

このドキュメントは新機能の完全な詳細を提供するのではなくて、簡易な概要
を提供することを目的にしています。完全な詳細が知りたければ、 Python
2.6 のドキュメントを参照してください。設計と実装の根拠を理解したい場合
は、新機能に関する PEP を参照してください。可能な限り、 "What’s New in
Python" は各変更の bug や patch に対してリンクしています。


Python 3.0
==========

Python 2.6 と 3.0 の開発サイクルは同期していました。両バージョンのアル
ファ、ベータリリースは同じ日にリリースされています。3.0 の開発は 2.6
の多くの機能に影響を与えました。

Python 3.0 は、2.x シリーズとの互換性を破壊する、広範囲な再設計です。
これは、Python 3.0 で動作させるためには既存のコードに何らかの変換が必
要なことを意味しています。しかしながら、必ずしも全ての 3.0 での変更が
互換性を破壊するわけではありません。新機能が既存のコードの破壊を引き起
こさないケースにおいては、それらは 2.6 にバックポートされました。これ
らについてはこのドキュメントの適切な場所に記載しています。3.0 由来の機
能の一部としては以下があります:

* A "__complex__()" method for converting objects to a complex number.

* 例外の捕捉の、これまでとは別の文法の追加: "except TypeError as exc"
  。

* The addition of "functools.reduce()" as a synonym for the built-in
  "reduce()" function.

Python 3.0 adds several new built-in functions and changes the
semantics of some existing builtins.  Functions that are new in 3.0
such as "bin()" have simply been added to Python 2.6, but existing
builtins haven't been changed; instead, the "future_builtins" module
has versions with the new 3.0 semantics.  Code written to be
compatible with 3.0 can do "from future_builtins import hex, map" as
necessary.

A new command-line switch, "-3", enables warnings about features that
will be removed in Python 3.0.  You can run code with this switch to
see how much work will be necessary to port code to 3.0.  The value of
this switch is available to Python code as the boolean variable
"sys.py3kwarning", and to C extension code as "Py_Py3kWarningFlag".

参考:

  The 3*xxx* series of PEPs, which contains proposals for Python 3.0.
  **PEP 3000** describes the development process for Python 3.0. Start
  with **PEP 3100** that describes the general goals for Python 3.0,
  and then explore the higher-numbered PEPs that propose specific
  features.


開発プロセスに関する変更
========================

2.6 の開発の間で、Python 開発プロセスは 2 つの重要な変更を経験しました
: SourceForge の課題トラッカーから、カスタイマイズした Roundup インス
トレーションに乗り換えました。また、ドキュメントは LaTeX から
reStructuredText に変換しました。


新しい課題トラッカー: Roundup
-----------------------------

もう随分長いこと Python 開発者たちは、SourceForge のバグトラッカーにイ
ライラを高め続けてきました。SourceForge がホストするソリューションには
全くカスタマイズの余地がなく、たとえば課題のライフサイクルをカスタマイ
ズ出来ませんでした。

The infrastructure committee of the Python Software Foundation
therefore posted a call for issue trackers, asking volunteers to set
up different products and import some of the bugs and patches from
SourceForge.  Four different trackers were examined: Jira, Launchpad,
Roundup, and Trac. The committee eventually settled on Jira and
Roundup as the two candidates.  Jira is a commercial product that
offers no-cost hosted instances to free-software projects; Roundup is
an open-source project that requires volunteers to administer it and a
server to host it.

ボランティアへの呼び掛けののち、新しい Roundup インストレーションが
https://bugs.python.org にセットアップされました。Roundup の一つのイン
ストレーションは複数のトラッカーをホスト出来るため、このサーバは今では
Jython と Python ウェブサイトのための課題トラッカーもホストしています
。間違いなく将来はほかのものもホストするでしょう。可能な場所では、
"What's New in Python" のこのエディションでは、それぞれの変更について
のバグ/パッチの Roundup アイテムにリンクします。

Hosting of the Python bug tracker is kindly provided by Upfront
Systems of Stellenbosch, South Africa.  Martin von Löwis put a lot of
effort into importing existing bugs and patches from SourceForge; his
scripts for this import operation are at
"https://svn.python.org/view/tracker/importer/" and may be useful to
other projects wishing to move from SourceForge to Roundup.

参考:

  https://bugs.python.org
     Python のバグトラッカー。

  https://bugs.jython.org:
     Jython のバグトラッカー。

  https://roundup.sourceforge.io/
     Roundup のダウンロードとドキュメント。

  https://svn.python.org/view/tracker/importer/
     Martin von Löwis の変換スクリプト。


新しいドキュメンテーションフォーマット: Sphinx を使っての reStructuredText
--------------------------------------------------------------------------

Python のドキュメンテーションは、そのプロジェクトの開始した 1989 年頃
より LaTeX を使って書かれてきました。1980 年代と 1990 年代初期は、ほと
んどのドキュメンテーションはあとで学習するために印刷されるもので、オン
ラインで見るものではありませんでした。LaTeX はとても魅惑的な印刷をして
くれるものですから、非常に大変広く広く使われていましたが、一方では、学
んだマークアップの基礎的なルールで直裁的に、書いたらそれっきり、という
ものでもありました。

こんにちにおいてもなお、印刷を命題とする出版において LaTeX は健在とい
えど、プログラミングの道具立ての風景は変わりました。わたしたちはもはや
ドキュメンテーションの紙束をプリントアウトはしません。代わりにオンライ
ンでブラウズします。ですから HTML は、サポートすべき最も重要なフォーマ
ットになりました。悲しいかな、 LaTeX から HTML への変換は気が狂うほど
に複雑で、Fred L. Drake Jr.、彼は長らく Python ドキュメンテーションの
エディターを務めていますが、彼はその変換処理の保守に多大な時間を浪費し
ていたのです。ときおり人々はドキュメンテーションを SGML に変換して、そ
れから XML にすればいいでしょ、と持ちかけるのですが、良い変換を達成す
ることにとらわれて、誰一人として仕事を完遂させようと時間を捧げることは
しませんでした。

During the 2.6 development cycle, Georg Brandl put a lot of effort
into building a new toolchain for processing the documentation.  The
resulting package is called Sphinx, and is available from https://www
.sphinx-doc.org/.

Sphinx は HTML 出力に集中し、人を惹きつけるスタイルでモダンな HTML を
生成します。印刷出力は LaTeX への変換を経由することで健在です。入力の
フォーマットは reStructuredText です。これはカスタムな拡張とディレクテ
ィブをサポートしているマークアップ文法で、Python コミュニティでは広く
使われています。

Sphinx は執筆に使えるスタンドアロンのパッケージです。そして 2 ダースに
届かんばかりのプロジェクト (Sphinx ウェブサイトのリスト) が Sphinx を
ドキュメンテーションツールとして採用しました。

参考:

  Documenting Python
     Python ドキュメントの書き方について書いています。

  Sphinx
     Sphinx ツールチェインのドキュメントとコードです。

  Docutils
     縁の下の力持ちになっている reStructuredText のパーサとツールセッ
     トです。


PEP 343: "with" ステートメント
==============================

Python 2.5 では、  '"with"' 文が "from __future__ import
with_statement" ディレクティブで有効に出来るオプションの機能として追加
されました。2.6 では '"with"' 文は特別に有効化する必要なく、もういつで
もそこにあります。このセクションの残りの部分は "What's New in Python
2.5" の対応するセクションからの丸々コピーですので、2.5 で '"with"' 文
に馴染んでいるなら読み飛ばしてもらって結構です。

'"with"' ステートメントは、以前なら後片付けが実行されるのを確実にする
ために "try...finally" ブロックを使ったであろうようなコードを、より単
純明快にします。このセクションでは、このステートメントの普通の使い方を
説明します。続くセクションでは実装の詳細を調べ、このステートメントとと
もに使うためにオブジェクトをどうやって書けば良いかをお見せします。

'"with"' ステートメントは基本構造が以下となる制御フロー構造です:

   with expression [as variable]:
       with-block

The expression is evaluated, and it should result in an object that
supports the context management protocol (that is, has "__enter__()"
and "__exit__()" methods).

The object's "__enter__()" is called before *with-block* is executed
and therefore can run set-up code. It also may return a value that is
bound to the name *variable*, if given.  (Note carefully that
*variable* is *not* assigned the result of *expression*.)

After execution of the *with-block* is finished, the object's
"__exit__()" method is called, even if the block raised an exception,
and can therefore run clean-up code.

いくつかの Python 標準オブジェクトが既にコンテキスト管理プロトコルをサ
ポートしていて、 '"with"' とともに使えます。ファイルオブジェクトがその
一例です:

   with open('/etc/passwd', 'r') as f:
       for line in f:
           print line
           ... more processing code ...

このステートメントが実行し終わったあかつきには、 *f* のファイルオブジ
ェクトは、たとえ "for" ループが道半ばにして例外と成り果てても、自動的
にクローズされます。

注釈:

  In this case, *f* is the same object created by "open()", because
  "__enter__()" returns *self*.

"threading" モジュールのロック・条件変数でも '"with"' ステートメントの
恩恵にあずかれます:

   lock = threading.Lock()
   with lock:
       # Critical section of code
       ...

ブロックが実行される前にロックが獲得されて、ブロックが完了するやいなや
必ず解放されます。

The "localcontext()" function in the "decimal" module makes it easy to
save and restore the current decimal context, which encapsulates the
desired precision and rounding characteristics for computations:

   from decimal import Decimal, Context, localcontext

   # Displays with default precision of 28 digits
   v = Decimal('578')
   print v.sqrt()

   with localcontext(Context(prec=16)):
       # All code in this block uses a precision of 16 digits.
       # The original context is restored on exiting the block.
       print v.sqrt()


コンテキストマネージャを書く
----------------------------

中身を紐解いてみれば、 '"with"' ステートメントはけっこう入り組んでいま
す。ほとんどの人にとっては、既存のオブジェクトを '"with"' とともに使う
だけのことでその詳細を知る必要は無いので、それで良いならこのセクション
の残りの部分は読み飛ばして結構です。新しいオブジェクトの作者は基礎とな
る実装の詳細について知る必要があるので、このまま読み進めるべきです。

コンテキスト管理プロトコルの高度な説明はこんなです:

* The expression is evaluated and should result in an object called a
  "context manager".  The context manager must have "__enter__()" and
  "__exit__()" methods.

* The context manager's "__enter__()" method is called.  The value
  returned is assigned to *VAR*.  If no "as VAR" clause is present,
  the value is simply discarded.

* *BLOCK* 内のコードが実行されます。

* If *BLOCK* raises an exception, the context manager's "__exit__()"
  method is called with three arguments, the exception details ("type,
  value, traceback", the same values returned by "sys.exc_info()",
  which can also be "None" if no exception occurred).  The method's
  return value controls whether an exception is re-raised: any false
  value re-raises the exception, and "True" will result in suppressing
  it.  You'll only rarely want to suppress the exception, because if
  you do the author of the code containing the '"with"' statement will
  never realize anything went wrong.

* If *BLOCK* didn't raise an exception,  the "__exit__()" method is
  still called, but *type*, *value*, and *traceback* are all "None".

例を通じて考えましょう。枝葉末節を含んだ完璧なコードを提示しようとは思
いませんが、データベースのためにトランザクションをサポートするのに必要
となるメソッドの書き方についてスケッチしてみようと思います。

(データベース用語に不慣れな方へ:データベースへの変更のセットは、トラン
ザクションという単位でグループ化されています。トランザクションは「コミ
ット」される、その意味は、全ての変更がデータベースに書き込まれることで
す、もしくは「ロールバック」される、この場合全ての変更が捨てられてデー
タベースが変更されません、この 2 つのいずれかになりえます。詳しくはな
にかデータベースの著述を読んで下さい。)

データベース接続を表現するオブジェクトがあると仮定しましょう。私たちの
目標は、そのオブジェクトのユーザがこのように書けるようになることです:

   db_connection = DatabaseConnection()
   with db_connection as cursor:
       cursor.execute('insert into ...')
       cursor.execute('delete from ...')
       # ... more operations ...

The transaction should be committed if the code in the block runs
flawlessly or rolled back if there's an exception. Here's the basic
interface for "DatabaseConnection" that I'll assume:

   class DatabaseConnection:
       # Database interface
       def cursor(self):
           "Returns a cursor object and starts a new transaction"
       def commit(self):
           "Commits current transaction"
       def rollback(self):
           "Rolls back current transaction"

The "__enter__()" method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would
be a useful result, so the method will return it.  The user can then
add "as cursor" to their '"with"' statement to bind the cursor to a
variable name.

   class DatabaseConnection:
       ...
       def __enter__(self):
           # Code to start a new transaction
           cursor = self.cursor()
           return cursor

The "__exit__()" method is the most complicated because it's where
most of the work has to be done.  The method has to check if an
exception occurred.  If there was no exception, the transaction is
committed.  The transaction is rolled back if there was an exception.

下記のコード内では実行がメソッドの末尾まで落ちていって、なのでデフォル
トの "None" 返却になります。 "None" は偽なので、例外は自動的に再送出さ
れます。望むならもっと明示的に、コメントでマークした部分で "return" 文
を書いてもよろしいです:

   class DatabaseConnection:
       ...
       def __exit__(self, type, value, tb):
           if tb is None:
               # No exception, so commit
               self.commit()
           else:
               # Exception occurred, so rollback.
               self.rollback()
               # return False


contextlib モジュール
---------------------

"contextlib" モジュールは、 '"with"' ステートメントで使えるオブジェク
トを書く際に便利ないくつかの関数とデコレータを提供しています。

The decorator is called "@~contextlib.contextmanager", and lets you
write a single generator function instead of defining a new class.
The generator should yield exactly one value.  The code up to the
"yield" will be executed as the "__enter__()" method, and the value
yielded will be the method's return value that will get bound to the
variable in the '"with"' statement's "as" clause, if any.  The code
after the "yield" will be executed in the "__exit__()" method. Any
exception raised in the block will be raised by the "yield" statement.

このデコレータを使って、前セクションの私たちのデータベースの例はこのよ
うに書けます:

   from contextlib import contextmanager

   @contextmanager
   def db_transaction(connection):
       cursor = connection.cursor()
       try:
           yield cursor
       except:
           connection.rollback()
           raise
       else:
           connection.commit()

   db = DatabaseConnection()
   with db_transaction(db) as cursor:
       ...

"contextlib" モジュールには "nested(mgr1, mgr2, ...)" 関数もあり、この
関数はたくさんのコンテキストマネージャを組み合わせることができて、入れ
子の '"with"' を書く必要性をなくしてくれます。この例では、単一の
'"with"' でデータベーストランザクション開始とスレッドのロック獲得の両
方をやってのけています:

   lock = threading.Lock()
   with nested (db_transaction(db), lock) as (cursor, locked):
       ...

Finally, the "closing()" function returns its argument so that it can
be bound to a variable, and calls the argument's ".close()" method at
the end of the block.

   import urllib, sys
   from contextlib import closing

   with closing(urllib.urlopen('http://www.yahoo.com')) as f:
       for line in f:
           sys.stdout.write(line)

参考:

  **PEP 343** - "with" ステートメント
     PEP は Guido van Rossum と Nick Coghlan によって書かれ、Mike
     Bland、 Guido van Rossum、Neal Norwitz により実装されました。この
     PEP は '"with"' ステートメントによって生成されるコードを見せてく
     れるので、このステートメントがどうやって動作するのかを知るのに役
     立ちます。

  "contextlib" モジュールについてのドキュメント。


PEP 366: メインモジュールからの明示的相対インポート
===================================================

Python のオプション "-m" で、モジュールをスクリプトとして実行出来ます
。パッケージ内のモジュールを実行する際に、相対インポートが正しく動作し
ていませんでした。

The fix for Python 2.6 adds a "module.__package__" attribute. When
this attribute is present, relative imports will be relative to the
value of this attribute instead of the "__name__" attribute.

PEP 302-style importers can then set "__package__" as necessary. The
"runpy" module that implements the "-m" switch now does this, so
relative imports will now work correctly in scripts running from
inside a package.


PEP 370: ユーザごとの "site-packages" ディレクトリ
==================================================

When you run Python, the module search path "sys.path" usually
includes a directory whose path ends in ""site-packages"".  This
directory is intended to hold locally installed packages available to
all users using a machine or a particular site installation.

Python 2.6 ではユーザ固有のサイトディレクトリのための決まりを導入しま
した。ディレクトリはプラットフォームに依存して変わります。

* Unix と Mac OS X: "~/.local/"

* Windows: "%APPDATA%/Python"

このディレクトリ内にはバージョン固有のサブディレクトリが入ります。
Unix/Mac OS では  "lib/python2.6/site-packages"  のように、Windows で
は "Python26/site-packages"  のように。

If you don't like the default directory, it can be overridden by an
environment variable.  "PYTHONUSERBASE" sets the root directory used
for all Python versions supporting this feature.  On Windows, the
directory for application-specific data can be changed by setting the
"APPDATA" environment variable.  You can also modify the "site.py"
file for your Python installation.

この機能は Python 起動時に "-s" オプションを付けるか、環境変数
"PYTHONNOUSERSITE" をセットすることで完全に無効に出来ます。

参考:

  **PEP 370** - ユーザごとの "site-packages" ディレクトリ
     PEP 著と実装 Christian Heimes.


PEP 371: "multiprocessing" パッケージ
=====================================

新しい "multiprocessing" により、Python プログラムが新たなプロセスを作
成して何か計算を実行させて結果を返させることが出来ます。親と子のプロセ
スはキューとパイプを使って通信し、ロックとセマフォを使って同期し、単純
なデータの配列を共有出来ます。

The "multiprocessing" module started out as an exact emulation of the
"threading" module using processes instead of threads.  That goal was
discarded along the path to Python 2.6, but the general approach of
the module is still similar.  The fundamental class is the "Process",
which is passed a callable object and a collection of arguments.  The
"start()" method sets the callable running in a subprocess, after
which you can call the "is_alive()" method to check whether the
subprocess is still running and the "join()" method to wait for the
process to exit.

ここに、サブプロセスが階乗を計算する例を示します。その計算をする関数は
ヘンテコリンに書かれていて、入力が 4 の倍数だととっても時間がかかるよ
うに仕組んであります。

   import time
   from multiprocessing import Process, Queue


   def factorial(queue, N):
       "Compute a factorial."
       # If N is a multiple of 4, this function will take much longer.
       if (N % 4) == 0:
           time.sleep(.05 * N/4)

       # Calculate the result
       fact = 1L
       for i in range(1, N+1):
           fact = fact * i

       # Put the result on the queue
       queue.put(fact)

   if __name__ == '__main__':
       queue = Queue()

       N = 5

       p = Process(target=factorial, args=(queue, N))
       p.start()
       p.join()

       result = queue.get()
       print 'Factorial', N, '=', result

"Queue" が factorial の結果を通信して返すのに使われています。 "Queue"
オブジェクトはグローバル変数に格納されています。子プロセスは、子プロセ
スが作成された時点のその変数の値を使うことになります; "Queue" なので、
親子はそのオブジェクトを通信のために使うことが出来ます。(プロセス作成
後に親がグローバル変数 queue を差し替えても、子の値は左右されませんし
、逆もしかりです。)

Two other classes, "Pool" and "Manager", provide higher-level
interfaces. "Pool" will create a fixed number of worker processes, and
requests can then be distributed to the workers by calling "apply()"
or "apply_async()" to add a single request, and "map()" or
"map_async()" to add a number of requests.  The following code uses a
"Pool" to spread requests across 5 worker processes and retrieve a
list of results:

   from multiprocessing import Pool

   def factorial(N, dictionary):
       "Compute a factorial."
       ...
   p = Pool(5)
   result = p.map(factorial, range(1, 1000, 10))
   for v in result:
       print v

これは以下のような出力をします:

   1
   39916800
   51090942171709440000
   8222838654177922817725562880000000
   33452526613163807108170062053440751665152000000000
   ...

The other high-level interface, the "Manager" class, creates a
separate server process that can hold master copies of Python data
structures.  Other processes can then access and modify these data
structures using proxy objects.  The following example creates a
shared dictionary by calling the "dict()" method; the worker processes
then insert values into the dictionary.  (Locking is not done for you
automatically, which doesn't matter in this example. "Manager"'s
methods also include "Lock()", "RLock()", and "Semaphore()" to create
shared locks.)

   import time
   from multiprocessing import Pool, Manager

   def factorial(N, dictionary):
       "Compute a factorial."
       # Calculate the result
       fact = 1L
       for i in range(1, N+1):
           fact = fact * i

       # Store result in dictionary
       dictionary[N] = fact

   if __name__ == '__main__':
       p = Pool(5)
       mgr = Manager()
       d = mgr.dict()         # Create shared dictionary

       # Run tasks using the pool
       for N in range(1, 1000, 10):
           p.apply_async(factorial, (N, d))

       # Mark pool as closed -- no more tasks can be added.
       p.close()

       # Wait for tasks to exit
       p.join()

       # Output results
       for k, v in sorted(d.items()):
           print k, v

これはこんな出力をするでしょう:

   1 1
   11 39916800
   21 51090942171709440000
   31 8222838654177922817725562880000000
   41 33452526613163807108170062053440751665152000000000
   51 15511187532873822802242430164693032110632597200169861120000...

参考:

  "multiprocessing" モジュールについてのドキュメント。

  **PEP 371** - multiprocessing パッケージの追加
     PEP 著 Jesse Noller と Richard Oudkerk; 実装 Richard Oudkerk と
     Jesse Noller.


**PEP 3101**: 進化版文字列フォーマッティング
============================================

In Python 3.0, the "%" operator is supplemented by a more powerful
string formatting method, "format()".  Support for the "str.format()"
method has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a ".format()" method that
treats the string as a template and takes the arguments to be
formatted. The formatting template uses curly brackets ("{", "}") as
special characters:

   >>> # Substitute positional argument 0 into the string.
   >>> "User ID: {0}".format("root")
   'User ID: root'
   >>> # Use the named keyword arguments
   >>> "User ID: {uid}   Last seen: {last_login}".format(
   ...    uid="root",
   ...    last_login = "5 Mar 2008 07:20")
   'User ID: root   Last seen: 5 Mar 2008 07:20'

波括弧自身は二重に書くことでエスケープ出来ます:

   >>> "Empty dict: {{}}".format()
   "Empty dict: {}"

フィールド名は、位置引数に対応する整数による "{0}", "{1}", …、またはキ
ーワード引数に対応する名前です。属性を読み出したり辞書のキーにアクセス
するような合成フィールド名(compound field names)も与えることが出来ます
:

   >>> import sys
   >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
   Platform: darwin
   Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
   [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'

   >>> import mimetypes
   >>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
   'Content-type: video/mp4'

"[.mp4]" のように辞書スタイルの記法を使う際は文字列の周りを引用符で囲
む必要はありません; ".mp4" をキーに値のルックアップされます。数値で始
まる文字列は整数に変換されます。フォーマット文字列内でこれ以上複雑な表
現は書けません。

ここまでは、結果文字列に置き換えられるフィールドを指定する方法について
見てきました。フォーマッティングではさらに、コロンに続けて書式指定子を
追加することでコントロール可能です。例えば:

   >>> # Field 0: left justify, pad to 15 characters
   >>> # Field 1: right justify, pad to 6 characters
   >>> fmt = '{0:15} ${1:>6}'
   >>> fmt.format('Registration', 35)
   'Registration    $    35'
   >>> fmt.format('Tutorial', 50)
   'Tutorial        $    50'
   >>> fmt.format('Banquet', 125)
   'Banquet         $   125'

書式指定子として、ネストによる他フィールド参照が使えます:

   >>> fmt = '{0:{1}}'
   >>> width = 15
   >>> fmt.format('Invoice #1234', width)
   'Invoice #1234  '
   >>> width = 35
   >>> fmt.format('Invoice #1234', width)
   'Invoice #1234                      '

望みの幅内でのフィールドの整列を指定可能です:

+------------------+----------------------------------------------+
| 文字             | 効果                                         |
|==================|==============================================|
| < (デフォルト)   | 左寄せ                                       |
+------------------+----------------------------------------------+
| >                | 右寄せ                                       |
+------------------+----------------------------------------------+
| ^                | 中央寄せ                                     |
+------------------+----------------------------------------------+
| =                | (数値型についてのみ) 符号のあとにパディング  |
+------------------+----------------------------------------------+

書式指定子には体裁のタイプも含めることが出来ます。値をどのようにフォー
マットするかです。たとえば浮動小数点数は普通の数値に、あるいは指数形式
でフォーマット出来ます:

   >>> '{0:g}'.format(3.75)
   '3.75'
   >>> '{0:e}'.format(3.75)
   '3.750000e+00'

たくさんの体裁のタイプを利用出来ます。2.6 ドキュメントの complete list
を調べてみてください。以下はその一部です:

+-------+--------------------------------------------------------------------------+
| "b"   | 2進数。出力される数値は2を基数とします。                                 |
+-------+--------------------------------------------------------------------------+
| "c"   | 文字。数値を対応するユニコード文字に変換します。                         |
+-------+--------------------------------------------------------------------------+
| "d"   | 10進数。出力される数値は10を基数とします。                               |
+-------+--------------------------------------------------------------------------+
| "o"   | 8進数。出力される数値は8を基数とします。                                 |
+-------+--------------------------------------------------------------------------+
| "x"   | 16進数。出力される数値は16を基数とします。 10進で9を超える数字には小文   |
|       | 字が使われます。                                                         |
+-------+--------------------------------------------------------------------------+
| "e"   | 指数表現です。指数を示す 'e'  を使った科学的記数法で表示します。         |
+-------+--------------------------------------------------------------------------+
| "g"   | 汎用フォーマット。数値が大き過ぎない限りは固定小数点表現をしますが、大   |
|       | きい値では 'e' 指数表現に切り替えます。                                  |
+-------+--------------------------------------------------------------------------+
| "n"   | 数値です。現在のロケールに合わせて、数値分割文字が挿入されることを除き   |
|       | 、 "'g'" (浮動小数点数の場合) または 'd' (整数の場合) と同じです。       |
+-------+--------------------------------------------------------------------------+
| "%"   | パーセンテージです。数値は 100 倍され、固定小数点数フォーマット ("'f'")  |
|       | でパーセント記号付きで表示されます。                                     |
+-------+--------------------------------------------------------------------------+

Classes and types can define a "__format__()" method to control how
they're formatted.  It receives a single argument, the format
specifier:

   def __format__(self, format_spec):
       if isinstance(format_spec, unicode):
           return unicode(str(self))
       else:
           return str(self)

There's also a "format()" builtin that will format a single value.  It
calls the type's "__format__()" method with the provided specifier:

   >>> format(75.6564, '.2f')
   '75.66'

参考:

  Format string syntax
     リファレンスドキュメント。

  **PEP 3101**: 進化版文字列フォーマッティング
     PEP 著 Talin; 実装 Eric Smith。


PEP 3105: "print" を関数にする
==============================

"print" 文は Python 3.0 では "print()" 関数になります。 "print()" が関
数になることで、 "def print(...)" やなにかほかの場所からの新しい関数を
インポートするなどの方法で置き換え可能になります。

Python 2.6 では "__future__" インポートで 言語構文としての "print" を
取り除き、関数形式のものを代わりに使えるように出来ます。たとえば:

   >>> from __future__ import print_function
   >>> print('# of entries', len(dictionary), file=sys.stderr)

この新しい関数のシグネチャは以下の通りです:

   def print(*args, sep=' ', end='\n', file=None)

パラメータは以下のとおりです:

* *args*: 出力される値を指定する位置引数リスト。

* *sep*: 引数リスト *args* を出力するのに使われる区切り文字。

* *end*: 引数リスト *args*  を全て出力したあとに出力するテキスト。

* *file*: 出力が送られるファイルオブジェクト。

参考:

  **PEP 3105** - print を関数にする
     Georg Brandl 著の PEP。


PEP 3110: 例外処理の変更
========================

Python プログラマが時折やらかしてしまう誤りの一つにこんなのがあります:

   try:
       ...
   except TypeError, ValueError:  # Wrong!
       ...

このコードの作者はきっと "TypeError" 例外と "ValueError" 例外の両方と
っつかまえてやろうと思ったのでしょうが、このコードは実際にはちょっと違
ったことをします: "TypeError" を捕捉したらこれを ""ValueError"" という
ローカル名の例外オブジェクトに束縛します…。 "ValueError" 例外は決して
捕捉されません。正しくは、例外のタプルで指定します:

   try:
       ...
   except (TypeError, ValueError):
       ...

こんなことが起こってしまうのは、ここではカンマの使用が曖昧だからです:
それ、解析木内で 2 つのノードを示すのかな、タプルな単一ノードかしら?

Python 3.0 はカンマからワード "as" に置き換えてこの曖昧さをなくします
。例外を捕捉して例外オブジェクトを "exc" に記憶するには、こう書かなけ
ればなりません:

   try:
       ...
   except TypeError as exc:
       ...

Python 3.0 は "as" の使用のみをサポートするようになるので、最初の例は
2 つの異なる例外を捕捉するものとして翻訳されます。Python 2.6 ではカン
マも "as" もサポートするので、既存のコードはそのまま動作します。新たに
2.6 で実行される Python コードを書くならば、 "as" の使用を勧めます。

参考:

  **PEP 3110** - Python 3000 での例外の捕捉
     PEP 著と実装 Collin Winter.


PEP 3112: バイトリテラル
========================

Python 3.0 は Unicode を言語の基本文字列型として採用し、8 ビットリテラ
ルは異なった記法で指示します。それには "b'string'" とするか、 "bytes"
のコンストラクタを用います。前方互換のために、Python 2.6 は "str" 型に
対する別名として "bytes" を追加のうえで、 "b''" 記法もサポートします。

2.6 の "str" 型は 3.0 の "bytes" 型とは色んな意味で違います; 一番顕著
なのは、コンストラクタがまったく異なることです。3.0 での "bytes([65,
66, 67])" は 3 つのバイトで "ABC" を構築しますが、2.6 での "bytes([65,
66, 67])" は引数のリストを "str()" で文字列化した 12 バイト文字列を返
します。

2.6 での "bytes" の主な使いみちはオブジェクトの型のテストに
"isinstance(x, bytes)" とすることでしょう。またこれは、 2.x コードが文
字列として ASCII 文字と 8 ビットバイトのどちらを意図しているのか知るこ
とが出来ない 2to3 コンバータの助けになります; あなたは今や "bytes" と
"str" の区別を、あなたの意図を正確に表現するのに使えます。そして結果の
コードは Python 3.0 で正しいものに修正されるでしょう。

全ての文字列リテラルを Unicode 文字列としてしまう "__future__" インポ
ートもあります。これは Unicode 文字を含むのに "\u" エスケープシーケン
スを使えることを意味します。

   from __future__ import unicode_literals

   s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
        '\u3081\u3000\u751f\u305f\u307e\u3054')

   print len(s)               # 12 Unicode characters

At the C level, Python 3.0 will rename the existing 8-bit string type,
called "PyStringObject" in Python 2.x, to "PyBytesObject".  Python 2.6
uses "#define" to support using the names "PyBytesObject()",
"PyBytes_Check()", "PyBytes_FromStringAndSize()", and all the other
functions and macros used with strings.

"bytes" 型のインスタンスは単に文字列と同じで *immutable* です。
"bytearray" 型が、バイト列を *mutable* シーケンスとして格納するものと
して新しく追加されました:

   >>> bytearray([65, 66, 67])
   bytearray(b'ABC')
   >>> b = bytearray(u'\u21ef\u3244', 'utf-8')
   >>> b
   bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
   >>> b[0] = '\xe3'
   >>> b
   bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
   >>> unicode(str(b), 'utf-8')
   u'\u31ef \u3244'

Byte arrays support most of the methods of string types, such as
"startswith()"/"endswith()", "find()"/"rfind()", and some of the
methods of lists, such as "append()", "pop()",  and "reverse()".

   >>> b = bytearray('ABC')
   >>> b.append('d')
   >>> b.append(ord('e'))
   >>> b
   bytearray(b'ABCde')

対応する C API もあります。 "PyByteArray_FromObject()",
"PyByteArray_FromStringAndSize()" や色々その他関数です。

参考:

  **PEP 3112** - Python 3000 でのバイトリテラル
     PEP 著 Jason Orendorff; 2.6 へのバックポート Christian Heimes.


PEP 3116: 新しい I/O ライブラリ
===============================

Python's built-in file objects support a number of methods, but file-
like objects don't necessarily support all of them.  Objects that
imitate files usually support "read()" and "write()", but they may not
support "readline()", for example.  Python 3.0 introduces a layered
I/O library in the "io" module that separates buffering and text-
handling features from the fundamental read and write operations.

"io" モジュールによって提供される抽象基底クラスには 3 つのレベルがあり
ます:

* "RawIOBase" defines raw I/O operations: "read()", "readinto()",
  "write()", "seek()", "tell()", "truncate()", and "close()". Most of
  the methods of this class will often map to a single system call.
  There are also "readable()", "writable()", and "seekable()" methods
  for determining what operations a given object will allow.

  Python 3.0 はこのクラスのファイルとソケットに対する具象実装を持って
  いますが、Python 2.6 はファイル、ソケットオブジェクトのこの方法での
  再構築はしていません。

* "BufferedIOBase" is an abstract base class that buffers data in
  memory to reduce the number of system calls used, making I/O
  processing more efficient. It supports all of the methods of
  "RawIOBase", and adds a "raw" attribute holding the underlying raw
  object.

  There are five concrete classes implementing this ABC.
  "BufferedWriter" and "BufferedReader" are for objects that support
  write-only or read-only usage that have a "seek()" method for random
  access.  "BufferedRandom" objects support read and write access upon
  the same underlying stream, and "BufferedRWPair" is for objects such
  as TTYs that have both read and write operations acting upon
  unconnected streams of data. The "BytesIO" class supports reading,
  writing, and seeking over an in-memory buffer.

* "TextIOBase": Provides functions for reading and writing strings
  (remember, strings will be Unicode in Python 3.0), and supporting
  *universal newlines*.  "TextIOBase" defines the "readline()" method
  and supports iteration upon objects.

  There are two concrete implementations.  "TextIOWrapper" wraps a
  buffered I/O object, supporting all of the methods for text I/O and
  adding a "buffer" attribute for access to the underlying object.
  "StringIO" simply buffers everything in memory without ever writing
  anything to disk.

  (In Python 2.6, "io.StringIO" is implemented in pure Python, so it's
  pretty slow.   You should therefore stick with the existing
  "StringIO" module or "cStringIO" for now.  At some point Python
  3.0's "io" module will be rewritten into C for speed, and perhaps
  the C implementation will be  backported to the 2.x releases.)

Python 2.6 では根底にある実装が "io" モジュールのクラスの上に組み立て
られるようには再構築されていません (訳注: Python HowTo の移植ガイドに
も触れられている通り、2.7 も同じです)。このモジュールは 3.0 への前方互
換のコードを書くのを容易にするために、また、開発者たちがバッファリング
I/O とテキスト I/O を自身で書く労力を省くために提供されています。

参考:

  **PEP 3116** - 新しい I/O
     PEP 著: Daniel Stutzbach, Mike Verdone, Guido van Rossum. 実装:
     Guido van Rossum, Georg Brandl, Walter Doerwald, Jeremy Hylton,
     Martin von Loewis, Tony Löwis, ほか.


PEP 3118: 改訂版バッファプロトコル
==================================

バッファプロトコルは Python 型にその内部表現へのポインタをやりとりさせ
る、C レベル API です。例えば、メモリマップドファイルは文字のバッファ
として見ることが出来ます。そしてこれは "re" のようなほかのモジュールが
、それを文字列として扱って検索するようなことを許します。

バッファプロトコルの主なユーザは NumPy のような数値演算パッケージで、
それらは呼び出し元がより遅い API を経由することなく直接的に行列にデー
タを書き込むことが出来るように、行列の内部表現を曝しています。この PEP
は NumPy 開発の経験を踏まえてバッファプロトコルを更新するもので、行列
の形状を表明したり、メモリ領域をロックしたりするような多数の新機能を追
加します。

最重要の新規 C API 関数は "PyObject_GetBuffer(PyObject *obj, Py_buffer
*view, int flags)" で、これはオブジェクトを受け取って、フラグをセット
し、 "Py_buffer" 構造体にオブジェクトのメモリ表現についての情報を埋め
ます。オブジェクトはこの操作を、外部の呼び出し元がその内容を修正してい
る間所定のメモリをロックするのに使えます。ですので対応する操作
"PyBuffer_Release(Py_buffer *view)" があり、これで外部呼出し元が処理を
終えたことを表明します。

"PyObject_GetBuffer()" への *flags* 引数は返されるメモリについての制約
条件を指定します。いくつかの例として:

* "PyBUF_WRITABLE" indicates that the memory must be writable.

* "PyBUF_LOCK" requests a read-only or exclusive lock on the memory.

* "PyBUF_C_CONTIGUOUS" and "PyBUF_F_CONTIGUOUS" requests a
  C-contiguous (last dimension varies the fastest) or Fortran-
  contiguous (first dimension varies the fastest) array layout.

"PyArg_ParseTuple()" のための 2 つの新しい書式化コード "s*" と "z*" は
、パラメータとしてロックされたバッファオブジェクトを返します。

参考:

  **PEP 3118** - 改訂版バッファプロトコル
     PEP 著: Travis Oliphant, Carl Banks; 実装: Travis Oliphant.


PEP 3119: 抽象基底クラス
========================

Some object-oriented languages such as Java support interfaces,
declaring that a class has a given set of methods or supports a given
access protocol.  Abstract Base Classes (or ABCs) are an equivalent
feature for Python. The ABC support consists of an "abc" module
containing a metaclass called "ABCMeta", special handling of this
metaclass by the "isinstance()" and "issubclass()" builtins, and a
collection of basic ABCs that the Python developers think will be
widely useful.  Future versions of Python will probably add more ABCs.

Let's say you have a particular class and wish to know whether it
supports dictionary-style access.  The phrase "dictionary-style" is
vague, however. It probably means that accessing items with "obj[1]"
works. Does it imply that setting items with "obj[2] = value" works?
Or that the object will have "keys()", "values()", and "items()"
methods?  What about the iterative variants  such as "iterkeys()"?
"copy`and :meth:()"!update`?  Iterating over the object with "iter()"?

The Python 2.6 "collections" module includes a number of different
ABCs that represent these distinctions.  "Iterable" indicates that a
class defines "__iter__()", and "Container" means the class defines a
"__contains__()" method and therefore supports "x in y" expressions.
The basic dictionary interface of getting items, setting items, and
"keys()", "values()", and "items()", is defined by the
"MutableMapping" ABC.

あなた自身のクラスを特定の ABC から派生して、ABC のインターフェイスを
サポートすることを示せます:

   import collections

   class Storage(collections.MutableMapping):
       ...

Alternatively, you could write the class without deriving from the
desired ABC and instead register the class by calling the ABC's
"register()" method:

   import collections

   class Storage:
       ...

   collections.MutableMapping.register(Storage)

For classes that you write, deriving from the ABC is probably clearer.
The "register()"  method is useful when you've written a new ABC that
can describe an existing type or class, or if you want to declare that
some third-party class implements an ABC. For example, if you defined
a "PrintableType" ABC, it's legal to do:

   # Register Python's types
   PrintableType.register(int)
   PrintableType.register(float)
   PrintableType.register(str)

クラスは ABC が規定するセマンティクスに従うべきですが、Python はそれを
チェックは出来ません；その ABC の要求を理解してコードを適切に実装する
のはクラスの作者任せです。

オブジェクトが特定のインターフェイスをサポートするかどうかをチェックす
るのには、今やこう書けます:

   def func(d):
       if not isinstance(d, collections.MutableMapping):
           raise ValueError("Mapping object expected, not %r" % d)

これからはたくさんのこのようなチェックをしなければならないのだ、この例
のように、などとは思わないように。Python は至極ダックタイピングな流儀
なのであって明示的な型チェックは決してされませんし、コードは単純にオブ
ジェクトのメソッドを、それらメソッドがそこにあるはずで、なければ例外に
なるのを信じて呼ぶだけです。ABC についてのチェックには分別を持ち、それ
が絶対的に必要な場合にだけそうするようにしましょう。

あなた自身の ABCs を書くには、クラス定義内のメタクラスとして
"abc.ABCMeta" を使います:

   from abc import ABCMeta, abstractmethod

   class Drawable():
       __metaclass__ = ABCMeta

       @abstractmethod
       def draw(self, x, y, scale=1.0):
           pass

       def draw_doubled(self, x, y):
           self.draw(x, y, scale=2.0)


   class Square(Drawable):
       def draw(self, x, y, scale):
           ...

In the "Drawable" ABC above, the "draw_doubled()" method renders the
object at twice its size and can be implemented in terms of other
methods described in "Drawable".  Classes implementing this ABC
therefore don't need to provide their own implementation of
"draw_doubled()", though they can do so.  An implementation of
"draw()" is necessary, though; the ABC can't provide a useful generic
implementation.

You can apply the "@~abc.abstractmethod" decorator to methods such as
"draw()" that must be implemented; Python will then raise an exception
for classes that don't define the method. Note that the exception is
only raised when you actually try to create an instance of a subclass
lacking the method:

   >>> class Circle(Drawable):
   ...     pass
   ...
   >>> c = Circle()
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: Can't instantiate abstract class Circle with abstract methods draw
   >>>

抽象データ属性を "@abstractproperty" を使って宣言出来ます:

   from abc import abstractproperty
   ...

   @abstractproperty
   def readonly(self):
      return self._x

Subclasses must then define a "readonly" property.

参考:

  **PEP 3119** - 抽象基底クラスの導入
     PEP は Guido van Rossum と Talin によって著され、Guido van Rossum
     により実装されています。Python 2.6 へのバックポートは Benjamin
     Aranguren と Alex Martelli により行われました。


PEP 3127: 整数リテラルのサポートと文法
======================================

Python 3.0 は octal (基数 8: 8 進数) 整数リテラルの構文を変更し、先行
するゼロの代わりに "0o" または "0O" (「ゼロオー」)としています。また、
binary (基数 2: 2 進数) 整数リテラルのサポートを追加し、これは "0b" ま
たは "0B" で指示します。

Python 2.6 は先行するゼロの形式での 8 進数サポートをやめませんが、
"0o" と "0b" は追加サポートします:

   >>> 0o21, 2*8 + 1
   (17, 17)
   >>> 0b101111
   47

ビルトイン関数 "oct()" はまだ先行ゼロ形式での表現を返します。新しいビ
ルトイン関数 "bin()" は数値の 2 進数表現を返します:

   >>> oct(42)
   '052'
   >>> future_builtins.oct(42)
   '0o52'
   >>> bin(173)
   '0b10101101'

The "int()" and "long()" builtins will now accept the "0o" and "0b"
prefixes when base-8 or base-2 are requested, or when the *base*
argument is zero (signalling that the base used should be determined
from the string):

   >>> int ('0o52', 0)
   42
   >>> int('1101', 2)
   13
   >>> int('0b1101', 2)
   13
   >>> int('0b1101', 0)
   13

参考:

  **PEP 3127** - 整数リテラルのサポートと文法
     PEP 著 Patrick Maupin、2.6 へのバックポートは Eric Smith による。


PEP 3129: クラスデコレータ
==========================

デコレータが拡張されて関数だけでなクラスにも使えるようになりました。今
やこのように書くのは合法です:

   @foo
   @bar
   class A:
     pass

これは次と等価です:

   class A:
     pass

   A = foo(bar(A))

参考:

  **PEP 3129** - クラスデコレータ
     PEP 著 Collin Winter.


PEP 3141: 数値の型階層
======================

Python 3.0 では Scheme の numeric tower に触発された、いくつかの数値型
のための抽象基底クラスを追加しています。これらのクラスは "numbers" モ
ジュール として 2.6 にバックポートされています。

The most general ABC is "Number".  It defines no operations at all,
and only exists to allow checking if an object is a number by doing
"isinstance(obj, Number)".

"Complex" is a subclass of "Number".  Complex numbers can undergo the
basic operations of addition, subtraction, multiplication, division,
and exponentiation, and you can retrieve the real and imaginary parts
and obtain a number's conjugate.  Python's built-in complex type is an
implementation of "Complex".

"Real" further derives from "Complex", and adds operations that only
work on real numbers: "floor()", "trunc()", rounding, taking the
remainder mod N, floor division, and comparisons.

"Rational" numbers derive from "Real", have "numerator" and
"denominator" properties, and can be converted to floats.  Python 2.6
adds a simple rational-number class, "Fraction", in the "fractions"
module.  (It's called "Fraction" instead of "Rational" to avoid a name
clash with "numbers.Rational".)

"Integral" numbers derive from "Rational", and can be shifted left and
right with "<<" and ">>", combined using bitwise operations such as
"&" and "|", and can be used as array indexes and slice boundaries.

In Python 3.0, the PEP slightly redefines the existing builtins
"round()", "math.floor()", "math.ceil()", and adds a new one,
"math.trunc()", that's been backported to Python 2.6. "math.trunc()"
rounds toward zero, returning the closest "Integral" that's between
the function's argument and zero.

参考:

  **PEP 3141** - 数値の型階層
     PEP 著: Jeffrey Yasskin.

  Guile マニュアルの Scheme's numerical tower 。

  Scheme's number datatypes from the R5RS Scheme specification.


"fractions" モジュール
----------------------

数値型階層を埋めるべく、 "fractions" モジュールが有理数クラスを提供し
ています。有理数は分子(numerator)と分母(denominator)で構成される分数と
してその値を格納し、浮動小数点数では近似しか出来ない "2/3" のような数
を正確に表現出来ます。

The "Fraction" constructor takes two "Integral" values that will be
the numerator and denominator of the resulting fraction.

   >>> from fractions import Fraction
   >>> a = Fraction(2, 3)
   >>> b = Fraction(2, 5)
   >>> float(a), float(b)
   (0.66666666666666663, 0.40000000000000002)
   >>> a+b
   Fraction(16, 15)
   >>> a/b
   Fraction(5, 3)

For converting floating-point numbers to rationals, the float type now
has an "as_integer_ratio()" method that returns the numerator and
denominator for a fraction that evaluates to the same floating-point
value:

   >>> (2.5) .as_integer_ratio()
   (5, 2)
   >>> (3.1415) .as_integer_ratio()
   (7074029114692207L, 2251799813685248L)
   >>> (1./3) .as_integer_ratio()
   (6004799503160661L, 18014398509481984L)

1./3 のような浮動小数点数で近似にしかならない値は、近似して単純化され
たりはしないことに注意してください; その分数は浮動小数点数に **正確に
** 合うように試みられます。

"fractions" モジュールは、ずっと長い間 Python の "Demo/classes/" ディ
レクトリにいた Sjoerd Mullender による実装に基いています。この実装が
Jeffrey Yasskin によって大幅に更新されました。


その他の言語変更
================

Python 言語コアに小さな変更がいくつか行われました:

* "__main__.py" を含んだディレクトリ名と zip アーカイブ名をインタプリ
  タに渡して直接実行出来るようになりました。そのディレクトリと zip ア
  ーカイブは自動的に sys.path エントリの先頭に追加されます。
  (Suggestion and initial patch by Andy Chu, subsequently revised by
  Phillip J. Eby and Nick Coghlan; bpo-1739468.)

* The "hasattr()" function was catching and ignoring all errors, under
  the assumption that they meant a "__getattr__()" method was failing
  somehow and the return value of "hasattr()" would therefore be
  "False".  This logic shouldn't be applied to "KeyboardInterrupt" and
  "SystemExit", however; Python 2.6 will no longer discard such
  exceptions when "hasattr()" encounters them.  (Fixed by Benjamin
  Peterson; bpo-2196.)

* "**" 構文を使ってキーワード引数を許容する関数を呼び出すのに、もう
  Python 辞書を使う必要はありません; 任意のマッピングプロトコルをサポ
  ートするオブジェクトで今では動作します:

     >>> def f(**kw):
     ...    print sorted(kw)
     ...
     >>> ud=UserDict.UserDict()
     >>> ud['a'] = 1
     >>> ud['b'] = 'string'
     >>> f(**ud)
     ['a', 'b']

  (Contributed by Alexander Belopolsky; bpo-1686487.)

  同時に、 "*args" 引数のあとでキーワード引数を与える関数呼び出しも今
  では合法です。:

     >>> def f(*args, **kw):
     ...     print args, kw
     ...
     >>> f(1,2,3, *(4,5,6), keyword=13)
     (1, 2, 3, 4, 5, 6) {'keyword': 13}

  以前はこれは構文エラーになっていました。 (Contributed by Amaury
  Forgeot d'Arc; bpo-3473.)

* 新しいビルトイン "next(iterator, [default])" は指定したイテレータよ
  り次のアイテムを返します。 *iterator* が使い果たされている場合、
  *default* 引数が与えられていれがこれを、そうでなければ
  "StopIteration" 例外を起こします。 (Backported in bpo-2719.)

* Tuples now have "index()" and "count()" methods matching the list
  type's "index()" and "count()" methods:

     >>> t = (0,1,2,3,4,0,1,2)
     >>> t.index(3)
     3
     >>> t.count(0)
     2

  (Contributed by Raymond Hettinger)

* ビルトイン型が拡張スライス構文をサポートするために改善されています。
  色々な "(start, stop, step)" 組み合わせを受け付けます。以前はこれの
  サポートは限定的で、ものによっては動作しませんでした。 (Implemented
  by Thomas Wouters.)

* Properties now have three decorators, "@~property.getter",
  "@~property.setter" and "@~property.deleter", that are decorators
  providing useful shortcuts for adding a getter, setter or deleter
  function to an existing property. You would use them like this:

     class C(object):
         @property
         def x(self):
             return self._x

         @x.setter
         def x(self, value):
             self._x = value

         @x.deleter
         def x(self):
             del self._x

     class D(C):
         @C.x.getter
         def x(self):
             return self._x * 2

         @x.setter
         def x(self, value):
             self._x = value / 2

* Several methods of the built-in set types now accept multiple
  iterables: "intersection()", "intersection_update()", "union()",
  "update()", "difference()" and "difference_update()".

     >>> s=set('1234567890')
     >>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
     set(['2'])
     >>> s.difference('246', '789')
     set(['1', '0', '3', '5'])

  (Contributed by Raymond Hettinger.)

* たくさんの浮動小数点数機能が追加されました。 "float()" 関数は文字列
  "nan" を IEEE 754 非数 (Not A Number) 値に変換し、 "+inf" と "-inf"
  は正あるいは負の無限大に変換します。これは IEEE 754 セマンティクスの
  あらゆるプラットフォームで動作します。 (Contributed by Christian
  Heimes; bpo-1635.)

  Other functions in the "math" module, "isinf()" and "isnan()",
  return true if their floating-point argument is infinite or Not A
  Number.  (bpo-1640)

  浮動小数点数を 16 進表記文字列に変換する変換関数が追加されています
  (bpo-3008)。これら関数は 10 進と 2 進との間の変換で起こる丸め誤差を
  持ち込まずに浮動小数点数と文字列表現の相互変換をします。浮動小数点数
  は文字列表現を返す "hex()" メソッドを持ち、また、 "float.fromhex()"
  メソッドが文字列から浮動小数点数に戻します:

     >>> a = 3.75
     >>> a.hex()
     '0x1.e000000000000p+1'
     >>> float.fromhex('0x1.e000000000000p+1')
     3.75
     >>> b=1./3
     >>> b.hex()
     '0x1.5555555555555p-2'

* 数に関する繊細さ: 符号付ゼロ (-0 と +0) をサポートするシステムで 2
  つの浮動小数点数から複素数を作る際に、 "complex()" コンストラクタが
  ゼロの符号を維持するようになりました。 (Fixed by Mark T. Dickinson;
  bpo-1507.)

* Classes that inherit a "__hash__()" method from a parent class can
  set "__hash__ = None" to indicate that the class isn't hashable.
  This will make "hash(obj)" raise a "TypeError" and the class will
  not be indicated as implementing the "Hashable" ABC.

  You should do this when you've defined a "__cmp__()" or "__eq__()"
  method that compares objects by their value rather than by identity.
  All objects have a default hash method that uses "id(obj)" as the
  hash value.  There's no tidy way to remove the "__hash__()" method
  inherited from a parent class, so assigning "None" was implemented
  as an override.  At the C level, extensions can set "tp_hash" to
  "PyObject_HashNotImplemented()". (Fixed by Nick Coghlan and Amaury
  Forgeot d'Arc; bpo-2235.)

* "GeneratorExit" 例外が "Exception" ではなく "BaseException" のサブク
  ラスになっています。 "except Exception:" をする例外ハンドラが意図せ
  ず "GeneratorExit" 捕捉してしまうことがなくなります。 (Contributed
  by Chad Austin; bpo-1537.)

* Generator objects now have a "gi_code" attribute that refers to the
  original code object backing the generator. (Contributed by Collin
  Winter; bpo-1473257.)

* ビルトイン関数 "compile()" が位置引数だけでなくキーワード引数も受け
  付けるようになりました。  (Contributed by Thomas Wouters;
  bpo-1444529.)

* "complex()" コンストラクタが括弧で囲まれた複素数表現文字列を受け付け
  るようになっています。 "complex(repr(cplx))" で元に戻せるということ
  です。例えば "complex('(3+4j)')" は今では値 "(3+4j)" を返します。
  (bpo-1491866)

* The string "translate()" method now accepts "None" as the
  translation table parameter, which is treated as the identity
  transformation.   This makes it easier to carry out operations that
  only delete characters.  (Contributed by Bengt Richter and
  implemented by Raymond Hettinger; bpo-1193128.)

* The built-in "dir()" function now checks for a "__dir__()" method on
  the objects it receives.  This method must return a list of strings
  containing the names of valid attributes for the object, and lets
  the object control the value that "dir()" produces. Objects that
  have "__getattr__()" or "__getattribute__()" methods can use this to
  advertise pseudo-attributes they will honor. (bpo-1591665)

* Instance method objects have new attributes for the object and
  function comprising the method; the new synonym for "im_self" is
  "__self__", and "im_func" is also available as "__func__". The old
  names are still supported in Python 2.6, but are gone in 3.0.

* 目立たない変更: "locals()" 関数を "class" ステートメント内で使う際、
  結果の辞書はもはや自由変数を返しません。(この場合、自由変数は
  "class" ステートメント内で参照される変数で、クラスの属性ではありませ
  ん。)


最適化
------

* "warnings" モジュールが C で書き直されました。これにより警告をパーサ
  から発行出来、また、インタプリタの起動が高速化しています。
  (Contributed by Neal Norwitz and Brett Cannon; bpo-1631171.)

* 型オブジェクトがメソッドのキャッシュを持つようになっています。これは
  個別のクラスについての正しいメソッド実装を見つけるのに必要な仕事を減
  らします。いったんキャッシュされれば、インタプリタは呼び出さなければ
  ならない正しいメソッドを知るために基底クラス群を横断しなくてもよくな
  ります。基底クラスやクラス自身が修正されれば、Python の動的な振る舞
  いの面においても正しくあり続けなければならないので、キャッシュはクリ
  アされます。 (Original optimization implemented by Armin Rigo,
  updated for Python 2.6 by Kevin Jacobs; bpo-1700288.)

  デフォルトではこの変更は、Python コアに含まれる型のみに適用されます
  。拡張モジュールは必ずしもこのキャッシュに互換ではなく、拡張モジュー
  ルはメソッドキャッシュを有効にするために、モジュールの "tp_flags" フ
  ィールドに明示的に "Py_TPFLAGS_HAVE_VERSION_TAG" を追加しなければな
  りません。(このメソッドキャッシュに対して互換であるためには、拡張モ
  ジュールのコードは、それが実装するどんな型についても "tp_dict" メン
  バに直接アクセスしたり修正したりしてはなりません。ほとんどのモジュー
  ルはこれをしていませんが、Python インタプリタがそれを検知することは
  出来ません。 bpo-1878 にいくらかの議論がありますので参照してください
  。)

* キーワード引数を使う関数呼び出しが、素早くポインタで比較することで顕
  著に高速化しています。これは常に文字列丸ごとを比較する時間を省きます
  。 (Contributed by Raymond Hettinger, after an initial
  implementation by Antoine Pitrou; bpo-1819.)

* "struct" モジュールの全ての関数が C で書き換えられました。「Need For
  Speed スプリント」での作業の成果です。 (Contributed by Raymond
  Hettinger.)

* いくつかの標準ビルトイン型が、その型オブジェクトにビットをセットする
  ようになりました。これは、オブジェクトがそれら型のサブクラスの一つで
  あるかどうかのチェックするのを高速化します。 (Contributed by Neal
  Norwitz.)

* Unicode strings now use faster code for detecting whitespace and
  line breaks; this speeds up the "split()" method by about 25% and
  "splitlines()" by 35%. (Contributed by Antoine Pitrou.)  Memory
  usage is reduced by using pymalloc for the Unicode string's data.

* The "with" statement now stores the "__exit__()" method on the
  stack, producing a small speedup.  (Implemented by Jeffrey Yasskin.)

* メモリ使用を減らすために、一番作られたオブジェクトをガーベージコレク
  トする際に、ガーベージコレクタが内部のフリーリストをクリアするように
  なりました。これはオペレーティングシステムにすぐに返されます。


インタプリタの変更
------------------

Two command-line options have been reserved for use by other Python
implementations.  The "-J" switch has been reserved for use by Jython
for Jython-specific options, such as switches that are passed to the
underlying JVM.  "-X" has been reserved for options specific to a
particular implementation of Python such as CPython, Jython, or
IronPython.  If either option is used with Python 2.6, the interpreter
will report that the option isn't currently used.

Python インタプリタに "-B" スイッチを渡すか、インタプリタ実行前に環境
変数 "PYTHONDONTWRITEBYTECODE" をセットするかのどちらかで、 ".pyc" や
".pyo" が作られないようにすることが出来るようになりました。この設定は
Python プログラムから "sys.dont_write_bytecode" 変数として利用可能で、
Python コードはこの変数を変更してインタプリタの振る舞いを変えることが
出来ます。 (Contributed by Neal Norwitz and Georg Brandl.)

標準入力、標準出力、標準エラー出力に使うエンコーディングを、インタプリ
タ起動前に環境変数 "PYTHONIOENCODING" を設定することで指定出来るように
なりました。値は "<encoding>" または "<encoding>:<errorhandler>" 形式
の文字列でなければなりません。 *encoding* 部分はエンコーディングの名前
で、例えば "utf-8" や "latin-1" です; 省略可能な *errorhandler* 部分は
エンコーディングによって処理出来ない文字に対して何をするのかを指定する
もので、 "error", "ignore", "replace" のどれかです。 (Contributed by
Martin von Löwis.)


新しいモジュールと改良されたモジュール
======================================

全てのリリースに置いて、 Python の標準ライブラリはたくさんの改良とバグ
修正がされてきました。ここでは一部の注目に値する変更を、モジュール名で
辞書順ソートしてリストアップしています。もっと完全な変更リストが見たけ
れば、ソースツリー内の "Misc/NEWS" ファイルか、全ての完全な詳細が入っ
ている Subversion のログを参照してください。

* The "asyncore" and "asynchat" modules are being actively maintained
  again, and a number of patches and bugfixes were applied.
  (Maintained by Josiah Carlson; see bpo-1736190 for one patch.)

* The "bsddb" module also has a new maintainer, Jesús Cea Avión, and
  the package is now available as a standalone package.  The web page
  for the package is www.jcea.es/programacion/pybsddb.htm. The plan is
  to remove the package from the standard library in Python 3.0,
  because its pace of releases is much more frequent than Python's.

  The "bsddb.dbshelve" module now uses the highest pickling protocol
  available, instead of restricting itself to protocol 1. (Contributed
  by W. Barnes.)

* The "cgi" module will now read variables from the query string of an
  HTTP POST request.  This makes it possible to use form actions with
  URLs that include query strings such as "/cgi-
  bin/add.py?category=1".  (Contributed by Alexandre Fiori and Nubis;
  bpo-1817.)

  The "parse_qs()" and "parse_qsl()" functions have been relocated
  from the "cgi" module to the "urlparse" module. The versions still
  available in the "cgi" module will trigger
  "PendingDeprecationWarning" messages in 2.6 (bpo-600362).

* "cmath" モジュールに大掛かりな改訂が行われました。Mark Dickinson と
  Christian Heimes による貢献です。5 つの新しい関数が追加されました:

  * "polar()" converts a complex number to polar form, returning the
    modulus and argument of the complex number.

  * "rect()" does the opposite, turning a modulus, argument pair back
    into the corresponding complex number.

  * "phase()" returns the argument (also called the angle) of a
    complex number.

  * "isnan()" returns True if either the real or imaginary part of its
    argument is a NaN.

  * "isinf()" returns True if either the real or imaginary part of its
    argument is infinite.

  The revisions also improved the numerical soundness of the "cmath"
  module.  For all functions, the real and imaginary parts of the
  results are accurate to within a few units of least precision (ulps)
  whenever possible.  See bpo-1381 for the details.  The branch cuts
  for "asinh()", "atanh()", and "atan()" have also been corrected.

  そのモジュールのテストは大変拡大しました; およそ 2000 の新たなテスト
  ケースが数学関数群を鍛え上げます。

  IEEE 754 プラットフォームでは "cmath" モジュールは、IEEE 754 の特殊
  値と浮動小数点例外を、C99 標準の付録 'G' での一貫性のある方法で処理
  するようになりました。

* A new data type in the "collections" module: "namedtuple(typename,
  fieldnames)" is a factory function that creates subclasses of the
  standard tuple whose fields are accessible by name as well as index.
  For example:

     >>> var_type = collections.namedtuple('variable',
     ...             'id name type size')
     >>> # Names are separated by spaces or commas.
     >>> # 'id, name, type, size' would also work.
     >>> var_type._fields
     ('id', 'name', 'type', 'size')

     >>> var = var_type(1, 'frequency', 'int', 4)
     >>> print var[0], var.id    # Equivalent
     1 1
     >>> print var[2], var.type  # Equivalent
     int int
     >>> var._asdict()
     {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
     >>> v2 = var._replace(name='amplitude')
     >>> v2
     variable(id=1, name='amplitude', type='int', size=4)

  Several places in the standard library that returned tuples have
  been modified to return "namedtuple()" instances.  For example, the
  "decimal.Decimal.as_tuple()" method now returns a named tuple with
  "sign", "digits", and "exponent" fields.

  (Contributed by Raymond Hettinger.)

* Another change to the "collections" module is that the "deque" type
  now supports an optional *maxlen* parameter; if supplied, the
  deque's size will be restricted to no more than *maxlen* items.
  Adding more items to a full deque causes old items to be discarded.

     >>> from collections import deque
     >>> dq=deque(maxlen=3)
     >>> dq
     deque([], maxlen=3)
     >>> dq.append(1); dq.append(2); dq.append(3)
     >>> dq
     deque([1, 2, 3], maxlen=3)
     >>> dq.append(4)
     >>> dq
     deque([2, 3, 4], maxlen=3)

  (Contributed by Raymond Hettinger.)

* The "Cookie" module's "Morsel" objects now support an "httponly"
  attribute.  In some browsers. cookies with this attribute set cannot
  be accessed or manipulated by JavaScript code. (Contributed by Arvin
  Schnell; bpo-1638033.)

* A new window method in the "curses" module, "chgat()", changes the
  display attributes for a certain number of characters on a single
  line.  (Contributed by Fabian Kreutz.)

     # Boldface text starting at y=0,x=21
     # and affecting the rest of the line.
     stdscr.chgat(0, 21, curses.A_BOLD)

  The "Textbox" class in the "curses.textpad" module now supports
  editing in insert mode as well as overwrite mode. Insert mode is
  enabled by supplying a true value for the *insert_mode* parameter
  when creating the "Textbox" instance.

* The "datetime" module's "strftime()" methods now support a "%f"
  format code that expands to the number of microseconds in the
  object, zero-padded on the left to six places.  (Contributed by Skip
  Montanaro; bpo-1158.)

* The "decimal" module was updated to version 1.66 of the General
  Decimal Specification.  New features include some methods for some
  basic mathematical functions such as "exp()" and "log10()":

     >>> Decimal(1).exp()
     Decimal("2.718281828459045235360287471")
     >>> Decimal("2.7182818").ln()
     Decimal("0.9999999895305022877376682436")
     >>> Decimal(1000).log10()
     Decimal("3")

  The "as_tuple()" method of "Decimal" objects now returns a named
  tuple with "sign", "digits", and "exponent" fields.

  (Implemented by Facundo Batista and Mark Dickinson.  Named tuple
  support added by Raymond Hettinger.)

* The "difflib" module's "SequenceMatcher" class now returns named
  tuples representing matches, with "a", "b", and "size" attributes.
  (Contributed by Raymond Hettinger.)

* An optional "timeout" parameter, specifying a timeout measured in
  seconds, was added to the "ftplib.FTP" class constructor as well as
  the "connect()" method.  (Added by Facundo Batista.) Also, the "FTP"
  class's "storbinary()" and "storlines()" now take an optional
  *callback* parameter that will be called with each block of data
  after the data has been sent. (Contributed by Phil Schwartz;
  bpo-1221598.)

* The "reduce()" built-in function is also available in the
  "functools" module.  In Python 3.0, the builtin has been dropped and
  "reduce()" is only available from "functools"; currently there are
  no plans to drop the builtin in the 2.x series. (Patched by
  Christian Heimes; bpo-1739906.)

* 可能な場合には、 "getpass" モジュールはプロンプトメッセージ出力とパ
  スワードの読み取りに "/dev/tty" を使うようになりました。利用出来ない
  場合は標準エラー出力と標準入力が使われます。端末に入力パスワードがエ
  コーされるかもしれない場合、プロンプト表示の前に警告が出力されます。
  (Contributed by Gregory P. Smith.)

* "glob.glob()" 関数が、Unicode パスが使われるかディレクトリ内に
  Unicode ファイル名がマッチすると Unicode ファイル名を返すようになり
  ました。 (bpo-1001604)

* "heapq" モジュールの新しい関数 "merge(iter1, iter2, ...)" は、任意の
  数のソートされたデータを返すイテラブルを取り、全てのイテラブルの内容
  をソートされた順に返す新しいジェネレータを返します (---訳注: 誤解を
  招く表現なので補足しておきますが、入力のイテレータはソート済みである
  ことを「仮定」し、出力のジェネレータは「入力が主張している」順序に従
  うだけです。入力がソートされていなくても並べ替えられるわけではありま
  せん。リファレンスにはここはきちんと書かれています。---)。例えば:

     >>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
     [1, 2, 3, 5, 8, 9, 16]

  Another new function, "heappushpop(heap, item)", pushes *item* onto
  *heap*, then pops off and returns the smallest item. This is more
  efficient than making a call to "heappush()" and then "heappop()".

  "heapq" は以前使っていた「以下("<=")」比較ではなく「より小さい("<")
  」比較だけを使って実装されています。これにより "heapq" に格納する型
  の要件が "list.sort()" メソッドに合致します。 (Contributed by
  Raymond Hettinger.)

* An optional "timeout" parameter, specifying a timeout measured in
  seconds, was added to the "httplib.HTTPConnection" and
  "HTTPSConnection" class constructors.  (Added by Facundo Batista.)

* Most of the "inspect" module's functions, such as "getmoduleinfo()"
  and "getargs()", now return named tuples. In addition to behaving
  like tuples, the elements of the  return value can also be accessed
  as attributes. (Contributed by Raymond Hettinger.)

  Some new functions in the module include "isgenerator()",
  "isgeneratorfunction()", and "isabstract()".

* "itertools" モジュールにいくつかの関数が追加されています。

  "izip_longest(iter1, iter2, ...[, fillvalue])" はそれぞれの要素群か
  らタプルを生成します; イテラブルの要素数がほかのものより短ければ欠落
  値として *fillvalue* が埋められます。例えば:

     >>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
     ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))

  "product(iter1, iter2, ..., [repeat=N])" は与えたイテラブルの直積
  (Cartesian product)、つまりそれぞれのイテラブルから返るその要素たち
  の全てのありうる組み合わせを含むタプルの集合を返します。:

     >>> list(itertools.product([1,2,3], [4,5,6]))
     [(1, 4), (1, 5), (1, 6),
      (2, 4), (2, 5), (2, 6),
      (3, 4), (3, 5), (3, 6)]

  省略可能 *repeat* キーワード引数が与えられると、イテラブルが一つであ
  ればこれが *N* 個、複数あればそのセットが *N* 回与えられたとみなしま
  す。単一のイテラブルに対しては *N* 要素タプルのリストで返ります:

     >>> list(itertools.product([1,2], repeat=3))
     [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
      (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]

  2 つのイテラブルであれば *2N* 要素タプルのリストで返ります:

     >>> list(itertools.product([1,2], [3,4], repeat=2))
     [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
      (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
      (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
      (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]

  "combinations(iterable, r)"  は、入力 *iterable* の要素からなる長さ
  *r* の部分列を返します (---訳注: 数学の初等組み合わせ論の「組合せ
  (combination)」 ---):

     >>> list(itertools.combinations('123', 2))
     [('1', '2'), ('1', '3'), ('2', '3')]
     >>> list(itertools.combinations('123', 3))
     [('1', '2', '3')]
     >>> list(itertools.combinations('1234', 3))
     [('1', '2', '3'), ('1', '2', '4'),
      ('1', '3', '4'), ('2', '3', '4')]

  "permutations(iter[, r])" は入力 *iterable* の長さ *r* の順列を返し
  ます。 *r* が指定されなければ、イテラブルが生成する全要素数がデフォ
  ルトで使われます (---訳注: 数学の初等組み合わせ論の「順列 (sequence
  without repetition)」または群論や組合せ論の「置換 (permutation)」。
  リファレンスでは訳出で置換も順列も両方出てきていますが、高校教育で習
  う用語で「順列」が伝わりやすいのでここでは「順列」としています。
  ---):

     >>> list(itertools.permutations([1,2,3,4], 2))
     [(1, 2), (1, 3), (1, 4),
      (2, 1), (2, 3), (2, 4),
      (3, 1), (3, 2), (3, 4),
      (4, 1), (4, 2), (4, 3)]

  "itertools.chain(*iterables)" is an existing function in "itertools"
  that gained a new constructor in Python 2.6.
  "itertools.chain.from_iterable(iterable)" takes a single iterable
  that should return other iterables.  "chain()" will then return all
  the elements of the first iterable, then all the elements of the
  second, and so on.

     >>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
     [1, 2, 3, 4, 5, 6]

  (All contributed by Raymond Hettinger.)

* The "logging" module's "FileHandler" class and its subclasses
  "WatchedFileHandler", "RotatingFileHandler", and
  "TimedRotatingFileHandler" now have an optional *delay* parameter to
  their constructors.  If *delay* is true, opening of the log file is
  deferred until the first "emit()" call is made.  (Contributed by
  Vinay Sajip.)

  "TimedRotatingFileHandler" also has a *utc* constructor parameter.
  If the argument is true, UTC time will be used in determining when
  midnight occurs and in generating filenames; otherwise local time
  will be used.

* いくつかの新しい関数が "math" モジュールに追加されました:

  * "isinf()" と "isnan()" は与えられた浮動小数点数が、順に、(正または
    負の) 無限大であるかどうか、非数 (NaN=Not a Number) であるかどうか
    を返します。

  * "copysign()" は IEEE 754 数の符号ビットをコピーします。 *x* の絶対
    値と *y* の符号ビットを組み合わせたものを返します。例えば
    "math.copysign(1, -0.0)" は -1.0 を返します。 (Contributed by
    Christian Heimes.)

  * "factorial()" は階乗を計算します。 (Contributed by Raymond
    Hettinger; bpo-2138.)

  * "fsum()" はイテラブルからの数列を、部分和の計算を通じて精度の損失
    を避けながら積み上げた合計の計算をします。 (Contributed by Jean
    Brouwers, Raymond Hettinger, and Mark Dickinson; bpo-2819.)

  * "acosh()", "asinh()", "atanh()" は逆双曲線関数を計算します。

  * "log1p()" は *1+x*  の自然対数 (底 *e* の対数) を返します。

  * "trunc()" rounds a number toward zero, returning the closest
    "Integral" that's between the function's argument and zero. Added
    as part of the backport of PEP 3141's type hierarchy for numbers.

* "math" モジュールは、特に浮動小数点例外と IEEE 754 の特殊値の処理に
  おいて、プラットフォーム間に渡る振る舞いの一貫性をさらに高めるように
  改善されました。

  可能な場合にはいつでもこのモジュールは 754 の特殊値について、C99 標
  準の勧告に従います。例えば、 "sqrt(-1.)" は今ではほとんど全てのプラ
  ットフォームで "ValueError" となるはずで、 "sqrt(float('NaN'))" は全
  ての IEEE 754 プラットフォームで NaN を返すはずです。C99 標準の付録
  'F' で 'divide-by-zero' または 'invalid' を伝えることを勧告している
  箇所では Python は "ValueError" を投げます。C99 標準の付録 'F' で
  'overflow' を伝えることを勧告している箇所では Python は
  "OverflowError" を投げます。 (See bpo-711019 and bpo-1640.)

  (Contributed by Christian Heimes and Mark Dickinson.)

* "mmap" objects now have a "rfind()" method that searches for a
  substring beginning at the end of the string and searching
  backwards.  The "find()" method also gained an *end* parameter
  giving an index at which to stop searching. (Contributed by John
  Lenton.)

* The "operator" module gained a "methodcaller()" function that takes
  a name and an optional set of arguments, returning a callable that
  will call the named function on any arguments passed to it.  For
  example:

     >>> # Equivalent to lambda s: s.replace('old', 'new')
     >>> replacer = operator.methodcaller('replace', 'old', 'new')
     >>> replacer('old wine in old bottles')
     'new wine in new bottles'

  (Contributed by Georg Brandl, after a suggestion by Gregory
  Petrosyan.)

  The "attrgetter()" function now accepts dotted names and performs
  the corresponding attribute lookups:

     >>> inst_name = operator.attrgetter(
     ...        '__class__.__name__')
     >>> inst_name('')
     'str'
     >>> inst_name(help)
     '_Helper'

  (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)

* "os" モジュールがいくつか新しくシステムコールをラップしています。開
  いたファイルについて、 "fchmod(fd, mode)" はモードを変更し、
  "fchown(fd, uid, gid)" は所有権を変更し、 "lchmod(path, mode)" はシ
  ンボリックリンクのモードを変更します。 (Contributed by Georg Brandl
  and Christian Heimes.)

  "chflags()" and "lchflags()" are wrappers for the corresponding
  system calls (where they're available), changing the flags set on a
  file.  Constants for the flag values are defined in the "stat"
  module; some possible values include "UF_IMMUTABLE" to signal the
  file may not be changed and "UF_APPEND" to indicate that data can
  only be appended to the file.  (Contributed by M. Levinson.)

  "os.closerange(low, high)" は効率よく全ての *low* から *high* のファ
  イルデスクリプタをクローズします。全てのエラーは無視されます。それと
  *high* はクローズ対象ではないです。この関数は既に "subprocess" モジ
  ュールがプロセスを開始するのを高速化するために使われています。
  (Contributed by Georg Brandl; bpo-1663329.)

* The "os.environ" object's "clear()" method will now unset the
  environment variables using "os.unsetenv()" in addition to clearing
  the object's keys.  (Contributed by Martin Horcicka; bpo-1181.)

* "os.walk()" 関数に "followlinks" パラメータが追加されています。これ
  を真にすると、シンボリックリンクが指す相手のディレクトリを渡り歩くよ
  うになります。後方互換のためにこのパラメータのデフォルトは偽です。な
  お、親ディレクトリを指すシンボリックリンクなど参照が循環していると、
  無限再帰に陥りますので注意してください。 (bpo-1273829)

* In the "os.path" module, the "splitext()" function has been changed
  to not split on leading period characters. This produces better
  results when operating on Unix's dot-files. For example,
  "os.path.splitext('.ipython')" now returns "('.ipython', '')"
  instead of "('', '.ipython')". (bpo-1115886)

  新規関数 "os.path.relpath(path, start='.')" は、与えられれば "start"
  からの、与えられなければカレントディレクトリからの、目的地 "path" へ
  の相対パスを返します。 (Contributed by Richard Barran; bpo-1339796.)

  Windows において、 "os.path.expandvars()" が "%var%" 形式の記述に環
  境変数を展開し、 "~user" にユーザのホームディレクトリのパスを展開す
  るようになりました。 (Contributed by Josiah Carlson; bpo-957650.)
  (---訳注: "~user" は実在した仕様かわかりません。2.7 に該当する実装も
  コメントも docstring もリファレンスもありませんし、当然この振る舞い
  は現在実在していません。---)

* "pdb" モジュールで提供される Python デバッガに新たなコマンドが追加さ
  れました: "run" はデバッグ対象の Python プログラムを再起動します。ま
  たオプションとして、対象プログラムに与えるコマンドライン引数を渡せま
  す。 (Contributed by Rocky Bernstein; bpo-1393667.)

* トレースバックのデバッグを開始するのに使われる "pdb.post_mortem()"
  が、トレースバックが与えられない場合に "sys.exc_info()" からの戻り値
  のトレースバックを使うようになりました。 (Contributed by Facundo
  Batista; bpo-1106316.)

* The "pickletools" module now has an "optimize()" function that takes
  a string containing a pickle and removes some unused opcodes,
  returning a shorter pickle that contains the same data structure.
  (Contributed by Raymond Hettinger.)

* A "get_data()" function was added to the "pkgutil" module that
  returns the contents of resource files included with an installed
  Python package.  For example:

     >>> import pkgutil
     >>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
     BaseException
      +-- SystemExit
      +-- KeyboardInterrupt
      +-- GeneratorExit
      +-- Exception
           +-- StopIteration
           +-- StandardError
      ...

  (Contributed by Paul Moore; bpo-2439.)

* The "pyexpat" module's "Parser" objects now allow setting their
  "buffer_size" attribute to change the size of the buffer used to
  hold character data. (Contributed by Achim Gaedke; bpo-1137.)

* The "queue" module now provides queue variants that retrieve entries
  in different orders.  The "PriorityQueue" class stores queued items
  in a heap and retrieves them in priority order, and "LifoQueue"
  retrieves the most recently added entries first, meaning that it
  behaves like a stack. (Contributed by Raymond Hettinger.)

* The "random" module's "Random" objects can now be pickled on a
  32-bit system and unpickled on a 64-bit system, and vice versa.
  Unfortunately, this change also means that Python 2.6's "Random"
  objects can't be unpickled correctly on earlier versions of Python.
  (Contributed by Shawn Ligocki; bpo-1727780.)

  新たな "triangular(low, high, mode)" は、三角分布 (triangular
  distribution) に従う乱数を生成します。 *mode* は分布内の最頻値で、返
  却値は *high* を含まない *low* と *high* の間です。 (Contributed by
  Wladmir van der Laan and Raymond Hettinger; bpo-1681432.)

* "re" モジュールによって実行される長い正規表現検索が届けられるシグナ
  ルをチェックするようになり、これにより多大な時間を要する検索を中断出
  来るようになります。 (Contributed by Josh Hoyt and Ralf Schmitt;
  bpo-846388.) (---訳注: 原文を忠実に訳すとわかりにくいですが、単に C
  のレベルでシグナルハンドラを仕掛けたので Python が割り込める、という
  のがここで言っていることです。本質的には「長い」や「時間のかかる」は
  あまり関係ないです。---)

  正規表現モジュールは、小さな正規表現固有仮想マシン用のバイトコードを
  コンパイルすることで実装されています。信頼出来ないコードにより、悪意
  あるバイトコード文字列を直接作って破滅させることが出来ます。ですので
  、2.6 では正規表現バイトコードの検証をするようにしてあります。
  (Contributed by Guido van Rossum from work for Google App Engine;
  bpo-3487.)

* The "rlcompleter" module's "complete()" method will now ignore
  exceptions triggered while evaluating a name. (Fixed by Lorenz
  Quack; bpo-2250.)

* The "sched" module's "scheduler" instances now have a read-only
  "queue" attribute that returns the contents of the scheduler's
  queue, represented as a list of named tuples with the fields "(time,
  priority, action, argument)". (Contributed by Raymond Hettinger;
  bpo-1861.)

* The "select" module now has wrapper functions for the Linux
  "epoll()" and BSD "kqueue()" system calls. "modify()" method was
  added to the existing "poll" objects; "pollobj.modify(fd,
  eventmask)" takes a file descriptor or file object and an event
  mask, modifying the recorded event mask for that file. (Contributed
  by Christian Heimes; bpo-1657.)

* "shutil.copytree()" が省略可能引数 *ignore* を取るようになっています
  。呼び出し可能オブジェクトを渡します。この呼び出し可能オブジェクトは
  それぞれのディレクトリパスとその内容リストを受け取って、コピーせずに
  無視したい名前のリストを返します。

  The "shutil" module also provides an "ignore_patterns()" function
  for use with this new parameter.  "ignore_patterns()" takes an
  arbitrary number of glob-style patterns and returns a callable that
  will ignore any files and directories that match any of these
  patterns.  The following example copies a directory tree, but skips
  both ".svn" directories and Emacs backup files, which have names
  ending with '~':

     shutil.copytree('Doc/library', '/tmp/library',
                     ignore=shutil.ignore_patterns('*~', '.svn'))

  (Contributed by Tarek Ziadé; bpo-2663.)

* Tkinter や GTK+ などのような場所で、シグナルハンドリングと GUI 処理
  のイベントループを組み合わせることは、長い間悩みの種でした; ほとんど
  のソフトウェアはポーリングを行って、わずかばかりの時間で起き上がって
  は GUI イベントが起きていないかチェックするハメになっています。
  "signal" モジュールが、これをより効率的に行えるようにしました。
  "signal.set_wakeup_fd(fd)" でファイルデスクリプタをセットすると、イ
  ベント受信時にファイルデスクリプタにバイトが書き込まれます。 C レベ
  ルの関数 "PySignal_SetWakeupFd()" もあります。同じくファイルデスクリ
  プタを渡します。

  Event loops will use this by opening a pipe to create two
  descriptors, one for reading and one for writing.  The writable
  descriptor will be passed to "set_wakeup_fd()", and the readable
  descriptor will be added to the list of descriptors monitored by the
  event loop via "select()" or "poll()". On receiving a signal, a byte
  will be written and the main event loop will be woken up, avoiding
  the need to poll.

  (Contributed by Adam Olsen; bpo-1583.)

  The "siginterrupt()" function is now available from Python code, and
  allows changing whether signals can interrupt system calls or not.
  (Contributed by Ralf Schmitt.)

  The "setitimer()" and "getitimer()" functions have also been added
  (where they're available).  "setitimer()" allows setting interval
  timers that will cause a signal to be delivered to the process after
  a specified time, measured in wall-clock time, consumed process
  time, or combined process+system time.  (Contributed by Guilherme
  Polo; bpo-2240.)

* The "smtplib" module now supports SMTP over SSL thanks to the
  addition of the "SMTP_SSL" class. This class supports an interface
  identical to the existing "SMTP" class. (Contributed by Monty
  Taylor.)  Both class constructors also have an optional "timeout"
  parameter that specifies a timeout for the initial connection
  attempt, measured in seconds.  (Contributed by Facundo Batista.)

  LMTP プロトコル (**RFC 2033**) 実装もモジュールに追加されています。
  LMTP はメールキューを管理しないエージェント間で e-mail を転送する際
  に、SMTP の代わりに使われます。(LMTP implemented by Leif Hedstrom;
  bpo-957003.)

  "smtplib.SMTP.starttls()" now complies with **RFC 3207** and forgets
  any knowledge obtained from the server not obtained from the TLS
  negotiation itself.  (Patch contributed by Bill Fenner; bpo-829951.)

* The "socket" module now supports TIPC
  (https://tipc.sourceforge.net/), a high-performance non-IP-based
  protocol designed for use in clustered environments.  TIPC addresses
  are 4- or 5-tuples. (Contributed by Alberto Bertogli; bpo-1646.)

  A new function, "create_connection()", takes an address and connects
  to it using an optional timeout value, returning the connected
  socket object.  This function also looks up the address's type and
  connects to it using IPv4 or IPv6 as appropriate.  Changing your
  code to use "create_connection()" instead of "socket(socket.AF_INET,
  ...)" may be all that's required to make your code work with IPv6.

* The base classes in the "SocketServer" module now support calling a
  "handle_timeout()" method after a span of inactivity specified by
  the server's "timeout" attribute.  (Contributed by Michael
  Pomraning.)  The "serve_forever()" method now takes an optional poll
  interval measured in seconds, controlling how often the server will
  check for a shutdown request. (Contributed by Pedro Werneck and
  Jeffrey Yasskin; bpo-742598, bpo-1193577.)

* Gerhard Häring により保守されている "sqlite3" モジュールが、Python
  2.5 時のバージョン 2.3.2 からバージョン 2.4.1 に更新されました。

* The "struct" module now supports the C99 _Bool type, using the
  format character "'?'". (Contributed by David Remahl.)

* The "Popen" objects provided by the "subprocess" module now have
  "terminate()", "kill()", and "send_signal()" methods. On Windows,
  "send_signal()" only supports the "SIGTERM" signal, and all these
  methods are aliases for the Win32 API function "TerminateProcess()".
  (Contributed by Christian Heimes.)

* A new variable in the "sys" module, "float_info", is an object
  containing information derived from the "float.h" file about the
  platform's floating-point support.  Attributes of this object
  include "mant_dig" (number of digits in the mantissa), "epsilon"
  (smallest difference between 1.0 and the next largest value
  representable), and several others.  (Contributed by Christian
  Heimes; bpo-1534.)

  Another new variable, "dont_write_bytecode", controls whether Python
  writes any ".pyc" or ".pyo" files on importing a module. If this
  variable is true, the compiled files are not written.  The variable
  is initially set on start-up by supplying the "-B" switch to the
  Python interpreter, or by setting the "PYTHONDONTWRITEBYTECODE"
  environment variable before running the interpreter.  Python code
  can subsequently change the value of this variable to control
  whether bytecode files are written or not. (Contributed by Neal
  Norwitz and Georg Brandl.)

  Information about the command-line arguments supplied to the Python
  interpreter is available by reading attributes of a named tuple
  available as "sys.flags".  For example, the "verbose" attribute is
  true if Python was executed in verbose mode, "debug" is true in
  debugging mode, etc. These attributes are all read-only.
  (Contributed by Christian Heimes.)

  A new function, "getsizeof()", takes a Python object and returns the
  amount of memory used by the object, measured in bytes.  Built-in
  objects return correct results; third-party extensions may not, but
  can define a "__sizeof__()" method to return the object's size.
  (Contributed by Robert Schuppenies; bpo-2898.)

  現在動作中のプロファイラとトレーサーを、 "sys.getprofile()" と
  "sys.gettrace()" で知ることが出来るようになりました。 (Contributed
  by Georg Brandl; bpo-1648.)

* "tarfile" モジュールが、既にサポートされている POSIX.1-1988 (ustar)
  と GNU tar フォーマットに加えて、POSIX.1-2001 (pax) をサポートするよ
  うになりました。デフォルトは GNU tar です; これと違うフォーマットで
  ファイルを開くには "format" パラメータで指定します:

     tar = tarfile.open("output.tar", "w",
                        format=tarfile.PAX_FORMAT)

  新しい "encoding" と "errors" パラメータはエンコーディングと文字変換
  のエラー処理方法を指定します。 "'strict'", "'ignore'",  "'replace'"
  は Python の 3 つの標準エラー処理です; "'utf-8'" は特殊で、不正な文
  字を、それの UTF-8 表現に置き換えます。(文字変換は、PAX フォーマット
  が Unicode ファイル名をサポートするために現れ、デフォルトは UTF-8 エ
  ンコーディングです。)

  The "tarfile.TarFile.add()" method now accepts an "exclude" argument
  that's a function that can be used to exclude certain filenames from
  an archive. The function must take a filename and return true if the
  file should be excluded or false if it should be archived. The
  function is applied to both the name initially passed to "add()" and
  to the names of files in recursively added directories.

  (All changes contributed by Lars Gustäbel).

* An optional "timeout" parameter was added to the "telnetlib.Telnet"
  class constructor, specifying a timeout measured in seconds.  (Added
  by Facundo Batista.)

* "tempfile.NamedTemporaryFile" クラスは普通はこれが作った一時ファイル
  を、ファイルクローズ時に削除します。この振る舞いを、コンストラクタの
  パラメータに "delete=False" を渡すことで変更出来るようになりました。
  (Contributed by Damien Miller; bpo-1537850.)

  A new class, "SpooledTemporaryFile", behaves like a temporary file
  but stores its data in memory until a maximum size is exceeded.  On
  reaching that limit, the contents will be written to an on-disk
  temporary file.  (Contributed by Dustin J. Mitchell.)

  The "NamedTemporaryFile" and "SpooledTemporaryFile" classes both
  work as context managers, so you can write "with
  tempfile.NamedTemporaryFile() as tmp: ...". (Contributed by
  Alexander Belopolsky; bpo-2021.)

* The "test.test_support" module gained a number of context managers
  useful for writing tests. "EnvironmentVarGuard()" is a context
  manager that temporarily changes environment variables and
  automatically restores them to their old values.

  Another context manager, "TransientResource", can surround calls to
  resources that may or may not be available; it will catch and ignore
  a specified list of exceptions.  For example, a network test may
  ignore certain failures when connecting to an external web site:

     with test_support.TransientResource(IOError,
                                     errno=errno.ETIMEDOUT):
         f = urllib.urlopen('https://sf.net')
         ...

  Finally, "check_warnings()" resets the "warnings" module's warning
  filters and returns an object that will record all warning messages
  triggered (bpo-3781):

     with test_support.check_warnings() as wrec:
         warnings.simplefilter("always")
         # ... code that triggers a warning ...
         assert str(wrec.message) == "function is outdated"
         assert len(wrec.warnings) == 1, "Multiple warnings raised"

  (Contributed by Brett Cannon.)

* The "textwrap" module can now preserve existing whitespace at the
  beginnings and ends of the newly created lines by specifying
  "drop_whitespace=False" as an argument:

     >>> S = """This  sentence  has a bunch   of
     ...   extra   whitespace."""
     >>> print textwrap.fill(S, width=15)
     This  sentence
     has a bunch
     of    extra
     whitespace.
     >>> print textwrap.fill(S, drop_whitespace=False, width=15)
     This  sentence
       has a bunch
        of    extra
        whitespace.
     >>>

  (Contributed by Dwayne Bailey; bpo-1581073.)

* The "threading" module API is being changed to use properties such
  as "daemon" instead of "setDaemon()" and "isDaemon()" methods, and
  some methods have been renamed to use underscores instead of camel-
  case; for example, the "activeCount()" method is renamed to
  "active_count()".  Both the 2.6 and 3.0 versions of the module
  support the same properties and renamed methods, but don't remove
  the old methods.  No date has been set for the deprecation of the
  old APIs in Python 3.x; the old APIs won't be removed in any 2.x
  version. (Carried out by several people, most notably Benjamin
  Peterson.)

  The "threading" module's "Thread" objects gained an "ident" property
  that returns the thread's identifier, a nonzero integer.
  (Contributed by Gregory P. Smith; bpo-2871.)

* The "timeit" module now accepts callables as well as strings for the
  statement being timed and for the setup code. Two convenience
  functions were added for creating "Timer" instances: "repeat(stmt,
  setup, time, repeat, number)" and "timeit(stmt, setup, time,
  number)" create an instance and call the corresponding method.
  (Contributed by Erik Demaine; bpo-1533909.)

* The "tkinter" module now accepts lists and tuples for options,
  separating the elements by spaces before passing the resulting value
  to Tcl/Tk. (Contributed by Guilherme Polo; bpo-2906.)

* タートルグラフィックスのための "turtle" モジュールが Gregor Lingl に
  より大幅に拡張されました。 モジュールの新しい機能は次の通りです:

  * 亀の移動と回転のアニメーションの改善。

  * Control over turtle movement using the new "delay()", "tracer()",
    and "speed()" methods.

  * 亀に新しい姿を設定できたり、新しい座標系を定義できるようになりまし
    た。

  * Turtles now have an "undo()" method that can roll back actions.

  * マウスやキーボードからの入力イベントに反応するための簡易なサポート
    が入り、簡単なゲームを書けるようになりました。

  * "turtle.cfg" を使って、turtle の画面の起動時の見た目をカスタマイズ
    できるようになりました。

  * モジュールの docstring が、他の言語に翻訳された docstring に置き換
    えられるようになりました。

  (bpo-1513695)

* An optional "timeout" parameter was added to the "urllib.urlopen"
  function and the "urllib.ftpwrapper" class constructor, as well as
  the "urllib2.urlopen" function.  The parameter specifies a timeout
  measured in seconds.   For example:

     >>> u = urllib2.urlopen("http://slow.example.com",
                             timeout=3)
     Traceback (most recent call last):
       ...
     urllib2.URLError: <urlopen error timed out>
     >>>

  (Added by Facundo Batista.)

* "unicodedata" モジュールで提供される Unicode データベースが、バージ
  ョン 5.1.0 に更新されました。 (Updated by Martin von Löwis;
  bpo-3811.)

* The "warnings" module's "formatwarning()" and "showwarning()" gained
  an optional *line* argument that can be used to supply the line of
  source code.  (Added as part of bpo-1631171, which re-implemented
  part of the "warnings" module in C code.)

  A new function, "catch_warnings()", is a context manager intended
  for testing purposes that lets you temporarily modify the warning
  filters and then restore their original values (bpo-3781).

* The XML-RPC "SimpleXMLRPCServer" and "DocXMLRPCServer" classes can
  now be prevented from immediately opening and binding to their
  socket by passing "False" as the *bind_and_activate* constructor
  parameter.  This can be used to modify the instance's
  "allow_reuse_address" attribute before calling the "server_bind()"
  and "server_activate()" methods to open the socket and begin
  listening for connections. (Contributed by Peter Parente;
  bpo-1599845.)

  "SimpleXMLRPCServer" also has a "_send_traceback_header" attribute;
  if true, the exception and formatted traceback are returned as HTTP
  headers "X-Exception" and "X-Traceback".  This feature is for
  debugging purposes only and should not be used on production servers
  because the tracebacks might reveal passwords or other sensitive
  information.  (Contributed by Alan McIntyre as part of his project
  for Google's Summer of Code 2007.)

* The "xmlrpclib" module no longer automatically converts
  "datetime.date" and "datetime.time" to the "xmlrpclib.DateTime"
  type; the conversion semantics were not necessarily correct for all
  applications.  Code using "xmlrpclib" should convert "date" and
  "time" instances. (bpo-1330538)  The code can also handle dates
  before 1900 (contributed by Ralf Schmitt; bpo-2014) and 64-bit
  integers represented by using "<i8>" in XML-RPC responses
  (contributed by Riku Lindblad; bpo-2985).

* The "zipfile" module's "ZipFile" class now has "extract()" and
  "extractall()" methods that will unpack a single file or all the
  files in the archive to the current directory, or to a specified
  directory:

     z = zipfile.ZipFile('python-251.zip')

     # Unpack a single file, writing it relative
     # to the /tmp directory.
     z.extract('Python/sysmodule.c', '/tmp')

     # Unpack all the files in the archive.
     z.extractall()

  (Contributed by Alan McIntyre; bpo-467924.)

  The "open()", "read()" and "extract()" methods can now take either a
  filename or a "ZipInfo" object.  This is useful when an archive
  accidentally contains a duplicated filename. (Contributed by Graham
  Horler; bpo-1775025.)

  最後に、 "zipfile" がアーカイブするファイルのファイル名として
  Unicode の使用をサポートするようになりました。  (Contributed by
  Alexey Borzenkov; bpo-1734346.)  (---訳注: リファレンスに注意事項と
  して書かれていますが、zip ファイルのファイル名標準は存在しないのでこ
  れは問題を起こすことがあります。---)


"ast" モジュール
----------------

"ast" モジュールは Python コードの抽象構文木 (Abstract Syntax Tree) 表
現を提供します。また、Armin Ronacher は共通タスクを実行するさまざまな
ヘルパー関数を寄稿しました。これらは HTML テンプレートパッケージである
とか、コードアナライザ、などなどの、Python コードを処理するツールで有
用となるでしょう。

The "parse()" function takes an expression and returns an AST. The
"dump()" function outputs a representation of a tree, suitable for
debugging:

   import ast

   t = ast.parse("""
   d = {}
   for i in 'abcdefghijklm':
       d[i + i] = ord(i) - ord('a') + 1
   print d
   """)
   print ast.dump(t)

これの出力は深くネストされたツリーです:

   Module(body=[
     Assign(targets=[
       Name(id='d', ctx=Store())
      ], value=Dict(keys=[], values=[]))
     For(target=Name(id='i', ctx=Store()),
         iter=Str(s='abcdefghijklm'), body=[
       Assign(targets=[
         Subscript(value=
           Name(id='d', ctx=Load()),
             slice=
             Index(value=
               BinOp(left=Name(id='i', ctx=Load()), op=Add(),
                right=Name(id='i', ctx=Load()))), ctx=Store())
        ], value=
        BinOp(left=
         BinOp(left=
          Call(func=
           Name(id='ord', ctx=Load()), args=[
             Name(id='i', ctx=Load())
            ], keywords=[], starargs=None, kwargs=None),
          op=Sub(), right=Call(func=
           Name(id='ord', ctx=Load()), args=[
             Str(s='a')
            ], keywords=[], starargs=None, kwargs=None)),
          op=Add(), right=Num(n=1)))
       ], orelse=[])
      Print(dest=None, values=[
        Name(id='d', ctx=Load())
      ], nl=True)
    ])

The "literal_eval()" method takes a string or an AST representing a
literal expression, parses and evaluates it, and returns the resulting
value.  A literal expression is a Python expression containing only
strings, numbers, dictionaries, etc. but no statements or function
calls.  If you need to evaluate an expression but cannot accept the
security risk of using an "eval()" call, "literal_eval()" will handle
it safely:

   >>> literal = '("a", "b", {2:4, 3:8, 1:2})'
   >>> print ast.literal_eval(literal)
   ('a', 'b', {1: 2, 2: 4, 3: 8})
   >>> print ast.literal_eval('"a" + "b"')
   Traceback (most recent call last):
     ...
   ValueError: malformed string

The module also includes "NodeVisitor" and "NodeTransformer" classes
for traversing and modifying an AST, and functions for common
transformations such as changing line numbers.


The "future_builtins" module
----------------------------

Python 3.0 makes many changes to the repertoire of built-in functions,
and most of the changes can't be introduced in the Python 2.x series
because they would break compatibility. The "future_builtins" module
provides versions of these built-in functions that can be imported
when writing 3.0-compatible code.

このモジュールに今のところ含まれるのは:

* "ascii(obj)": 2.x の "repr()" と同じことをします。Python 3.0 では
  "repr()" は Unicode 文字列を返すようになっていて、一方 "ascii()" は
  純粋な ASCII バイト文字列を返します。

* "filter(predicate, iterable)", "map(func, iterable1, ...)": 3.0 と同
  じようにイテレータを返し、これは 2.x のビルトインがリストで返すのと
  は違っています。

* "hex(value)", "oct(value)": instead of calling the "__hex__()" or
  "__oct__()" methods, these versions will call the "__index__()"
  method and convert the result to hexadecimal or octal.  "oct()" will
  use the new "0o" notation for its result.


"json" モジュール: JavaScript オブジェクト記法
----------------------------------------------

新しい "json" モジュールは、JSON (Javascript Object Notation) と
Python 型のエンコーディング、デコーディングをサポートします。JSON は軽
量なデータ交換フォーマットで、頻繁にウェブアプリケーションで使われます
。JSON の詳細情報は http://www.json.org にあります。

"json" モジュールはほとんどのビルトイン型のデコーディングとエンコーデ
ィングサポートを備えています。以下の例は辞書のエンコードとデコードをし
ています:

   >>> import json
   >>> data = {"spam": "foo", "parrot": 42}
   >>> in_json = json.dumps(data) # Encode the data
   >>> in_json
   '{"parrot": 42, "spam": "foo"}'
   >>> json.loads(in_json) # Decode into a Python object
   {"spam": "foo", "parrot": 42}

ほかの何か型をサポートするのに独自のエンコーダ、デコーダを書くことも出
来ます。JSON 文字列の pretty-printing もサポートされています。

"json" (もともと simplejson と呼ばれていました) は Bob Ippolito によっ
て書かれました。


"plistlib" モジュール: プロパティリストパーサ
---------------------------------------------

".plist" フォーマットは Mac OS X で一般的に使われ、基本的なデータ型(数
値、文字列、リスト、辞書)を XML ベースのフォーマットにシリアライズして
格納します。データ型の XML-RPC シリアライズに似ています。

Mac OS X で主に使われるとはいえ、そのフォーマットはまったく Mac 固有で
はなくその Python 実装は Python がサポートするあらゆるプラットフォーム
で動作するので、"plistlib" は標準ライブラリに昇格しました。

モジュールを使うのは単純です:

   import sys
   import plistlib
   import datetime as dt

   # Create data structure
   data_struct = dict(lastAccessed=dt.datetime.now(),
                      version=1,
                      categories=('Personal','Shared','Private'))

   # Create string containing XML.
   plist_str = plistlib.writePlistToString(data_struct)
   new_struct = plistlib.readPlistFromString(plist_str)
   print data_struct
   print new_struct

   # Write data structure to a file and read it back.
   plistlib.writePlist(data_struct, '/tmp/customizations.plist')
   new_struct = plistlib.readPlist('/tmp/customizations.plist')

   # read/writePlist accepts file-like objects as well as paths.
   plistlib.writePlist(data_struct, sys.stdout)


ctypes の強化
-------------

Thomas Heller は "ctypes" モジュールの保守と拡張を続けました。

"ctypes" now supports a "c_bool" datatype that represents the C99
"bool" type.  (Contributed by David Remahl; bpo-1649190.)

"ctypes" の string, buffer, array 型が拡張スライスインデクス構文をサポ
ートするように改善され、 "(start, stop, step)" の色々な組み合わせが使
えます。 (Implemented by Thomas Wouters.)

All "ctypes" data types now support "from_buffer()" and
"from_buffer_copy()" methods that create a ctypes instance based on a
provided buffer object.  "from_buffer_copy()" copies the contents of
the object, while "from_buffer()" will share the same memory area.

新しい呼び出しの慣例は、 "ctypes" にそれぞれのラップされた呼び出しの発
生時に "errno" あるいは Win32 LastError 変数をクリアすることを伝えるこ
とです。 (Implemented by Thomas Heller; bpo-1798.)

You can now retrieve the Unix "errno" variable after a function call.
When creating a wrapped function, you can supply "use_errno=True" as a
keyword parameter to the "DLL" function and then call the module-level
methods "set_errno()" and "get_errno()" to set and retrieve the error
value.

The Win32 LastError variable is similarly supported by the "DLL",
"OleDLL()", and "WinDLL()" functions. You supply "use_last_error=True"
as a keyword parameter and then call the module-level methods
"set_last_error()" and "get_last_error()".

The "byref()" function, used to retrieve a pointer to a ctypes
instance, now has an optional *offset* parameter that is a byte count
that will be added to the returned pointer.


SSL サポートの改善
------------------

Bill Janssen は Python 2.6 の Secure Sockets Layer サポートを大掛かり
に改善しました。行われたのは新モジュール "ssl" の追加です。これは
OpenSSL ライブラリの上に構築されています。この新しいモジュールはプロト
コルのネゴシエイトのさらなる制御、X.509 証明書の使用、そして SSL サー
バ (クライアントの対語としての) を Python で書くためのより良いサポート
を提供しています。既存の "socket" モジュールにある SSL サポートは削除
されずにそのまま使えますが、Python 3.0 では削除されます。

To use the new module, you must first create a TCP connection in the
usual way and then pass it to the "ssl.wrap_socket()" function. It's
possible to specify whether a certificate is required, and to obtain
certificate info by calling the "getpeercert()" method.

参考: "ssl" モジュールについてのドキュメント。


非推奨と削除
============

* 文字列を例外として送出することは出来なくなりました。これをすると
  "TypeError" を起こします。

* Changes to the "Exception" interface as dictated by **PEP 352**
  continue to be made.  For 2.6, the "message" attribute is being
  deprecated in favor of the "args" attribute.

* (3.0 警告モード) Python 3.0 はたくさんの時代遅れのモジュールを削除し
  、ほかのものも名前変更するような標準ライブラリの再編成が特色となりま
  す。Python 2.6 を 3.0 警告モードで動かすと、それらがインポートされる
  際に警告が励起されます。

  The list of deprecated modules is: "audiodev", "bgenlocations",
  "buildtools", "bundlebuilder", "Canvas", "compiler", "dircache",
  "dl", "fpformat", "gensuitemodule", "ihooks", "imageop", "imgfile",
  "linuxaudiodev", "mhlib", "mimetools", "multifile", "new", "pure",
  "statvfs", "sunaudiodev", "test.testall", and "toaiff".

* The "gopherlib" module has been removed.

* The "MimeWriter" module and "mimify" module have been deprecated;
  use the "email" package instead.

* The "md5" module has been deprecated; use the "hashlib" module
  instead.

* The "posixfile" module has been deprecated; "fcntl.lockf()" provides
  better locking.

* The "popen2" module has been deprecated; use the "subprocess"
  module.

* The "rgbimg" module has been removed.

* The "sets" module has been deprecated; it's better to use the built-
  in "set" and "frozenset" types.

* The "sha" module has been deprecated; use the "hashlib" module
  instead.


ビルドならびに C API の変更
===========================

Python のビルド過程と C API の変更は以下の通りです:

* Python now must be compiled with C89 compilers (after 19 years!).
  This means that the Python source tree has dropped its own
  implementations of "memmove()" and "strerror()", which are in the
  C89 standard library.

* Python 2.6 は Microsoft Visual Studio 2008 (version 9.0) でビルド出
  来ます。そしてこれが新しいデフォルトコンパイラです。 "PCbuild" ディ
  レクトリのビルドファイルを参照して下さい。 (Implemented by Christian
  Heimes.)

* Mac OS X では、Python 2.6 は 4 種類のユニバーサルビルドでコンパイル
  出来ます。 **configure** スクリプトは "--with-universal-
  archs=[32-bit|64-bit|all]" スイッチを取って、32-bit アーキテクチャ
  (x86, PowerPC), 64-bit (x86-64 and PPC-64), あるいは両方のバイナリを
  ビルド出来ます。 (Contributed by Ronald Oussoren.)

* A new function added in Python 2.6.6, "PySys_SetArgvEx()", sets the
  value of "sys.argv" and can optionally update "sys.path" to include
  the directory containing the script named by "sys.argv[0]" depending
  on the value of an *updatepath* parameter.

  This function was added to close a security hole for applications
  that embed Python.  The old function, "PySys_SetArgv()", would
  always update "sys.path", and sometimes it would add the current
  directory.  This meant that, if you ran an application embedding
  Python in a directory controlled by someone else, attackers could
  put a Trojan-horse module in the directory (say, a file named
  "os.py") that your application would then import and run.

  If you maintain a C/C++ application that embeds Python, check
  whether you're calling "PySys_SetArgv()" and carefully consider
  whether the application should be using "PySys_SetArgvEx()" with
  *updatepath* set to false.  Note that using this function will break
  compatibility with Python versions 2.6.5 and earlier; if you have to
  continue working with earlier versions, you can leave the call to
  "PySys_SetArgv()" alone and call
  "PyRun_SimpleString("sys.path.pop(0)\n")" afterwards to discard the
  first "sys.path" component.

  Security issue reported as **CVE 2008-5983**; discussed in gh-50003,
  and fixed by Antoine Pitrou.

* The BerkeleyDB module now has a C API object, available as
  "bsddb.db.api".   This object can be used by other C extensions that
  wish to use the "bsddb" module for their own purposes. (Contributed
  by Duncan Grisby.)

* PEP 3118 改訂版バッファプロトコル で前述の新しいバッファインターフェ
  イスのために、 "PyObject_GetBuffer()" と "PyBuffer_Release()" とほか
  少しの関数が追加されました。

* Python's use of the C stdio library is now thread-safe, or at least
  as thread-safe as the underlying library is.  A long-standing
  potential bug occurred if one thread closed a file object while
  another thread was reading from or writing to the object.  In 2.6
  file objects have a reference count, manipulated by the
  "PyFile_IncUseCount()" and "PyFile_DecUseCount()" functions.  File
  objects can't be closed unless the reference count is zero.
  "PyFile_IncUseCount()" should be called while the GIL is still held,
  before carrying out an I/O operation using the "FILE *" pointer, and
  "PyFile_DecUseCount()" should be called immediately after the GIL is
  re-acquired. (Contributed by Antoine Pitrou and Gregory P. Smith.)

* Importing modules simultaneously in two different threads no longer
  deadlocks; it will now raise an "ImportError".  A new API function,
  "PyImport_ImportModuleNoBlock()", will look for a module in
  "sys.modules" first, then try to import it after acquiring an import
  lock.  If the import lock is held by another thread, an
  "ImportError" is raised. (Contributed by Christian Heimes.)

* Several functions return information about the platform's floating-
  point support.  "PyFloat_GetMax()" returns the maximum representable
  floating-point value, and "PyFloat_GetMin()" returns the minimum
  positive value.  "PyFloat_GetInfo()" returns an object containing
  more information from the "float.h" file, such as ""mant_dig""
  (number of digits in the mantissa), ""epsilon"" (smallest difference
  between 1.0 and the next largest value representable), and several
  others. (Contributed by Christian Heimes; bpo-1534.)

* C functions and methods that use "PyComplex_AsCComplex()" will now
  accept arguments that have a "__complex__()" method.  In particular,
  the functions in the "cmath" module will now accept objects with
  this method. This is a backport of a Python 3.0 change. (Contributed
  by Mark Dickinson; bpo-1675423.)

* Python C API に 2 つの大文字小文字を区別しない文字列比較関数
  "PyOS_stricmp(char*, char*)" と "PyOS_strnicmp(char*, char*,
  Py_ssize_t)" が追加されました。 (Contributed by Christian Heimes;
  bpo-1635.)

* 多くの C 拡張が、 "init*" 関数内でモジュール辞書に整数と文字列定数を
  追加するために独自の小さなマクロを定義しています。 Python 2.6 ではつ
  いにモジュールに値を追加する標準マクロを定義しました。
  "PyModule_AddStringMacro" と "PyModule_AddIntMacro()" です。
  (Contributed by Christian Heimes.)

* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
  they are macros, not functions.  "Py_Size()" became "Py_SIZE()",
  "Py_Type()" became "Py_TYPE()", and "Py_Refcnt()" became
  "Py_REFCNT()". The mixed-case macros are still available in Python
  2.6 for backward compatibility. (bpo-1629)

* Distutils は C 拡張を、デバッグバージョンの Python 実行時に別のディ
  レクトリにビルドするようになりました。 (Contributed by Collin
  Winter; bpo-1530959.)

* いくつかの基本データ型、例えば数値や文字列型は、あとで再利用されるオ
  ブジェクトのフリーリスト(---訳注: メモリ管理での alloc/free の free
  。---)を内部的に管理しています。それらデータ構造はこのフリーリストに
  関して、命名規約に従うようにしました; その変数名は常に "free_list"
  、カウンタは常に "numfree" 、そしてマクロ "Py<typename>_MAXFREELIST"
  が必ず定義されます。

* 新たに追加された Makefile のターゲット "make patchcheck" は、Python
  ソースツリーに対してパッチを作る準備をします: 修正された ".py" ファ
  イル全てに含まれる末尾の余分な空白を取り除き、ドキュメンテーションが
  変更されているかをチェックし、そして "Misc/ACKS" と "Misc/NEWS" が更
  新されているかどうかを報告します。 (Contributed by Brett Cannon.)

  もう一つの新しいターゲット "make profile-opt" は、GCC の profile-
  guided 最適化を使った Python バイナリをビルドします。これは Python
  をプロファイリングを有効にしてビルドし、プロファイル結果のセットを得
  るためのテストスイートを実施し、そして最適化のためにそれら結果を使っ
  てビルドします。 (Contributed by Gregory P. Smith.)


ポート特有の変更: Windows
-------------------------

* Windows 95, 98, ME, NT4 のサポートはとりやめられました。 Python 2.6
  は最低でも Windows 2000 SP4 が必要です。

* Windows での新しいデフォルトコンパイラが Visual Studio 2008 (version
  9.0) になっています。Visual Studio 2003 (version 7.1) と 2005
  (version 8.0) のビルドディレクトリは PC/ に移動しました。新しい
  "PCbuild" ディレクトリは X64, デバッグビルド、Profile Guided
  Optimization (PGO) をサポートしています。PGO ビルドは通常ビルドに較
  べておよそ 10% 高速化になります。 (Contributed by Christian Heimes
  with help from Amaury Forgeot d'Arc and Martin von Löwis.)

* The "msvcrt" module now supports both the normal and wide char
  variants of the console I/O API.  The "getwch()" function reads a
  keypress and returns a Unicode value, as does the "getwche()"
  function.  The "putwch()" function takes a Unicode character and
  writes it to the console. (Contributed by Christian Heimes.)

* "os.path.expandvars()" は "%var%" 形式を環境変数で置換し、 "~user"
  をユーザのホームディレクトリパスに置換します(---訳注: 上のほうの訳注
  参照。---)。 (Contributed by Josiah Carlson; bpo-957650.)

* The "socket" module's socket objects now have an "ioctl()" method
  that provides a limited interface to the "WSAIoctl()" system
  interface.

* The "_winreg" module now has a function,
  "ExpandEnvironmentStrings()", that expands environment variable
  references such as "%NAME%" in an input string.  The handle objects
  provided by this module now support the context protocol, so they
  can be used in "with" statements. (Contributed by Christian Heimes.)

  "_winreg" also has better support for x64 systems, exposing the
  "DisableReflectionKey()", "EnableReflectionKey()", and
  "QueryReflectionKey()" functions, which enable and disable registry
  reflection for 32-bit processes running on 64-bit systems.
  (bpo-1753245)

* The "msilib" module's "Record" object gained "GetInteger()" and
  "GetString()" methods that return field values as an integer or a
  string. (Contributed by Floris Bruynooghe; bpo-2125.)


ポート特有の変更: Mac OS X
--------------------------

* Python をフレームワークビルドでコンパイルする際に、 **configure** ス
  クリプトに "--with-framework-name" オプションでフレームワーク名を指
  定出来るようになりました。

* The "macfs" module has been removed.  This in turn required the
  "macostools.touched()" function to be removed because it depended on
  the "macfs" module.  (bpo-1490190)

* Many other Mac OS modules have been deprecated and will be removed
  in Python 3.0: "_builtinSuites", "aepack", "aetools", "aetypes",
  "applesingle", "appletrawmain", "appletrunner", "argvemulator",
  "Audio_mac", "autoGIL", "Carbon", "cfmfile", "CodeWarrior",
  "ColorPicker", "EasyDialogs", "Explorer", "Finder", "FrameWork",
  "findertools", "ic", "icglue", "icopen", "macerrors", "MacOS",
  "macfs", "macostools", "macresource", "MiniAEFrame", "Nav",
  "Netscape", "OSATerminology", "pimp", "PixMapWrapper", "StdSuites",
  "SystemEvents", "Terminal", and "terminalcommand".


ポート特有の変更: IRIX
----------------------

A number of old IRIX-specific modules were deprecated and will be
removed in Python 3.0: "al" and "AL", "cd", "cddb", "cdplayer", "CL"
and "cl", "DEVICE", "ERRNO", "FILE", "FL" and "fl", "flp", "fm",
"GET", "GLWS", "GL" and "gl", "IN", "IOCTL", "jpeg", "panelparser",
"readcd", "SV" and "sv", "torgb", "videoreader", and "WAIT".


Python 2.6 への移植
===================

このセクションでは前述の変更とバグフィックスにより必要となるかもしれな
いコードの変更を列挙します:

* ハッシュ化をサポートしないクラスはその定義内でその事実を示すために、
  "__hash__ = None" をセットすべきです。

* 文字列を例外として送出することは出来なくなりました。これをすると
  "TypeError" を起こします。

* The "__init__()" method of "collections.deque" now clears any
  existing contents of the deque before adding elements from the
  iterable.  This change makes the behavior match "list.__init__()".

* "object.__init__()" previously accepted arbitrary arguments and
  keyword arguments, ignoring them.  In Python 2.6, this is no longer
  allowed and will result in a "TypeError".  This will affect
  "__init__()" methods that end up calling the corresponding method on
  "object" (perhaps through using "super()"). See bpo-1683368 for
  discussion.

* The "Decimal" constructor now accepts leading and trailing
  whitespace when passed a string.  Previously it would raise an
  "InvalidOperation" exception.  On the other hand, the
  "create_decimal()" method of "Context" objects now explicitly
  disallows extra whitespace, raising a "ConversionSyntax" exception.

* 実装上の誤り(事故)で、ビルトインの "__import__()" 関数にファイルパス
  を渡すと指定したファイルをインポート出来ていました。しかしながらこれ
  は決して意図した振る舞いではありませんでした。実装は今ではこのケース
  を明示的にチェックし、 "ImportError" を起こします。

* C API: "PyImport_Import()" と "PyImport_ImportModule()" 関数がデフォ
  ルトで、相対インポートではなく絶対インポートをするようになっています
  。これはほかのモジュールをインポートする C 拡張に影響します。

* C API: ハッシュされるべきではない拡張データ型は、 "tp_hash" スロット
  を "PyObject_HashNotImplemented()" と定義すべきです。

* The "socket" module exception "socket.error" now inherits from
  "IOError".  Previously it wasn't a subclass of "StandardError" but
  now it is, through "IOError". (Implemented by Gregory P. Smith;
  bpo-1706815.)

* The "xmlrpclib" module no longer automatically converts
  "datetime.date" and "datetime.time" to the "xmlrpclib.DateTime"
  type; the conversion semantics were not necessarily correct for all
  applications.  Code using "xmlrpclib" should convert "date" and
  "time" instances. (bpo-1330538)

* (3.0 警告モード) "Exception" クラスはスライスやインデクスアクセスで
  警告を出します; "Exception" のタプルのような振る舞いはのちに取り除か
  れます。

* (3.0 警告モード) 2 つの辞書や 2 つの比較メソッドを実装しないオブジェ
  クトの不等号比較は警告されます。 "dict1 == dict2" はまだ動作しますが
  、 "dict1 < dict2" はのちに取り除かれます。

  Python のスコープルールの実装の詳細であるセル間の比較も、警告を引き
  起こします。なぜならこれは、3.0 ではそのような比較は完全に禁止されて
  いるからです。

Python を埋め込んだアプリケーションでは:

* The "PySys_SetArgvEx()" function was added in Python 2.6.6, letting
  applications close a security hole when the existing
  "PySys_SetArgv()" function was used.  Check whether you're calling
  "PySys_SetArgv()" and carefully consider whether the application
  should be using "PySys_SetArgvEx()" with *updatepath* set to false.


謝辞
====

著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の
人々に感謝します:  Georg Brandl, Steve Brown, Nick Coghlan, Ralph
Corderoy, Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr,
Antoine Pitrou, Brian Warner.
