What's New in Python 2.6

著者:

A.M. Kuchling (amk at amk.ca)

この記事では、2008 年 10 月 1 日にリリースされた Python 2.6 の新機能を説明します。 リリース日程は 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.

参考

3xxx 番台の PEP には Python 3.0 への提案が含まれています。 PEP 3000 は Python 3.0 の開発プロセスを説明しています。 まず全般的な目標を説明する PEP 3100 を読み、次に具体的な機能を提案する、それ以降の番号の PEP を調べてください。

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

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

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

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

そこで Python Software Foundation のインフラストラクチャ委員会は課題追跡システムを公募し、ボランティアに各種製品をセットアップして SourceForge から一部のバグやパッチを取り込むよう依頼しました。 Jira、Launchpad、Roundup、Trac の 4 製品が検討され、最終的に Jira と Roundup の 2 つに絞られました。 Jira は商用製品で、フリーソフトウェアプロジェクトには無償のホスティング環境を提供します。 Roundup はオープンソースのプロジェクトで、管理するボランティアとホスト用サーバーが必要です。

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

Python のバグトラッカーのホスティングは、南アフリカのステレンボッシュにある Upfront Systems が親切に提供しています。 Martin von Löwis は SourceForge から既存のバグやパッチを取り込むために多大な労力を費やしました。 取り込み用のスクリプトは https://svn.python.org/view/tracker/importer/ にあり、SourceForge から 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 にすればいいでしょ、と持ちかけるのですが、良い変換を達成することにとらわれて、誰一人として仕事を完遂させようと時間を捧げることはしませんでした。

2.6 の開発中、Georg Brandl は文書を処理する新しいツール群の構築に多大な労力を費やしました。 その成果は Sphinx というパッケージで、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

式を評価した結果は、コンテキスト管理プロトコルに対応するオブジェクトである必要があります (つまり、__enter__() メソッドと __exit__() メソッドを備えている必要があります)。

with-block を実行する前にオブジェクトの __enter__() が呼ばれるため、そこで準備のコードを実行できます。 値を返すこともでき、variable が指定されていればその名前に束縛されます。 (variable に代入されるのは expression の結果では ない 点に注意してください。)

with-block の実行が終わると、ブロックが例外を送出した場合も含めて、オブジェクトの __exit__() メソッドが呼ばれるので、そこで後始末のコードを実行できます。

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

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

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

注釈

この場合、__enter__() が self を返すので、f は open() が作ったオブジェクトそのものです。

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

lock = threading.Lock()
with lock:
    # コードのクリティカルセクション
    ...

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

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

# デフォルトの精度である 28 桁で表示
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # このブロック内のコードはすべて 16 桁の精度を使う。
    # ブロックを抜けると元のコンテキストに戻る。
    print v.sqrt()

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

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

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

  • 式を評価した結果は、「コンテキストマネージャー」と呼ばれるオブジェクトである必要があります。 コンテキストマネージャーには __enter__() と __exit__() の両メソッドが必要です。

  • コンテキストマネージャーの __enter__() メソッドが呼ばれ、その戻り値が VAR に代入されます。 as VAR 節がなければ、値は単に捨てられます。

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

  • BLOCK が例外を送出した場合、コンテキストマネージャーの __exit__() が例外の詳細を表す 3 つの引数で呼ばれます。 これは type, value, traceback という sys.exc_info() と同じ値で、例外がなければ None にもなります。 メソッドの戻り値で例外を再送出するかどうかが決まり、偽の値なら再送出し、True なら抑制します。 例外を抑制すべき場合はまれです。 抑制すると、with 文を含むコードの作者は、何か問題が起きたことを知る手段を失うからです。

  • BLOCK が例外を送出しなかった場合も __exit__() メソッドは呼ばれますが、type、value、traceback はすべて None になります。

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

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

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

db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... その他の操作 ...

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:
    # データベースのインターフェース
    def cursor(self):
        "新しいトランザクションを開始し、カーソルオブジェクトを返す"
    def commit(self):
        "現在のトランザクションをコミットする"
    def rollback(self):
        "現在のトランザクションをロールバックする"

__enter__() メソッドは、新しいトランザクションを開始するだけなので簡単です。 この用途では、作成したカーソルオブジェクトを返すと便利なので、メソッドの戻り値にします。 利用者は with 文に as cursor を追加して、カーソルを変数名に束縛できます。

class DatabaseConnection:
    ...
    def __enter__(self):
        # 新しいトランザクションを開始するコード
        cursor = self.cursor()
        return cursor

__exit__() メソッドは処理の大部分を担うため、最も複雑になります。 このメソッドは例外が発生したかどうかを確認する必要があります。 例外がなければトランザクションをコミットし、例外があればロールバックします。

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

class DatabaseConnection:
    ...
    def __exit__(self, type, value, tb):
        if tb is None:
            # 例外がないのでコミット
            self.commit()
        else:
            # 例外が発生したのでロールバック。
            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 で、モジュールをスクリプトとして実行出来ます。パッケージ内のモジュールを実行する際に、相対インポートが正しく動作していませんでした。

Python 2.6 では、この問題の修正として module.__package__ 属性が追加されました。 この属性があれば、相対インポートは __name__ ではなく、この属性の値を基準に行われます。

PEP 302 形式のインポーターは、必要に応じて __package__ を設定できます。 -m オプションを実装する runpy モジュールもこれを設定するようになり、パッケージ内から実行するスクリプトで相対インポートが正しく動作するようになりました。

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

Python の実行時、モジュール検索パス sys.path には通常、パスの末尾が "site-packages" のディレクトリが含まれます。 このディレクトリは、マシンや特定のサイトの Python 環境の全ユーザーが利用できる、ローカルにインストールしたパッケージを置くためのものです。

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):
    "階乗を計算する。"
    # N が 4 の倍数なら、この関数は大幅に時間がかかる。
    if (N % 4) == 0:
        time.sleep(.05 * N/4)

    # 結果を計算
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # 結果をキューへ入れる
    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):
    "階乗を計算する。"
    # 結果を計算
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # 結果を辞書に格納
    dictionary[N] = fact

if __name__ == '__main__':
    p = Pool(5)
    mgr = Manager()
    d = mgr.dict()         # 共有辞書を作成

    # プールを使ってタスクを実行
    for N in range(1, 1000, 10):
        p.apply_async(factorial, (N, d))

    # プールを閉じ、タスクの追加を終了する。
    p.close()

    # タスクの終了を待つ
    p.join()

    # 結果を出力
    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: 進化版文字列フォーマッティング

Python 3.0 では % 演算子に加え、より強力な文字列書式化メソッド format() が導入されます。 str.format() のサポートは Python 2.6 にも移植されました。

2.6 では、8 ビット文字列と Unicode 文字列の両方に .format() メソッドがあり、文字列をテンプレートとして扱い、書式化する引数を受け取ります。 テンプレートでは波括弧 ({、}) を特殊文字として使います。

>>> # 位置引数 0 を文字列へ埋め込む。
>>> "User ID: {0}".format("root")
'User ID: root'
>>> # 名前を指定したキーワード引数を使う
>>> "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 をキーに値のルックアップされます。数値で始まる文字列は整数に変換されます。フォーマット文字列内でこれ以上複雑な表現は書けません。

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

>>> # フィールド 0: 左揃え、15 文字幅まで埋める
>>> # フィールド 1: 右揃え、6 文字幅まで埋める
>>> 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:  # 誤り!
    ...

このコードの作者はきっと 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 文字

C レベルでは、Python 3.0 で 8 ビット文字列型の名前が、Python 2.x の PyStringObject から PyBytesObject に変わります。 Python 2.6 は #define によって PyBytesObject()、PyBytes_Check()、PyBytes_FromStringAndSize() など、文字列に関連するすべての関数やマクロの名前を使えるようにしています。

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.

    (Python 2.6 の io.StringIO は Python だけで実装されているため、かなり低速です。 当面は既存の StringIO や cStringIO モジュールを使い続けるとよいでしょう。 いずれ Python 3.0 の io は高速化のために C で書き直され、その実装が 2.x にも移植されるかもしれません。)

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 は、メモリが書き込み可能である必要があることを示します。

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

  • PyBUF_C_CONTIGUOUS と PyBUF_F_CONTIGUOUS は、それぞれ C 連続 (最後の次元が最も速く変化) と Fortran 連続 (最初の次元が最も速く変化) の配列配置を要求します。

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:

# Python の型を登録
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 。

R5RS Scheme 仕様の Scheme の数値データ型。

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')  # すべての入力の共通部分
    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)

  • インスタンスメソッドオブジェクトに、それを構成するオブジェクトと関数を表す新しい属性名が加わりました。 im_self は __self__、im_func は __func__ という名前でも使えます。 古い名前は Python 2.6 では引き続きサポートされますが、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.

  • with 文が __exit__() メソッドをスタックに格納するようになり、少し高速になりました。 (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 のログを参照してください。

  • asyncore と asynchat の活発な保守が再開され、多数のパッチやバグ修正が適用されました。 (保守担当は Josiah Carlson です。パッチの一例は bpo-1736190 を参照してください。)

  • 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.)

  • cgi モジュールが、HTTP POST リクエストのクエリー文字列からも変数を読むようになりました。 これにより、"/cgi-bin/add.py?category=1" のようにクエリー文字列を含む URL をフォームの送信先にできます。 (Alexandre Fiori と 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' での一貫性のある方法で処理するようになりました。

  • collections モジュールに新しいデータ型が加わりました。 namedtuple(typename, fieldnames) は、フィールドへインデックスだけでなく名前でもアクセスできる、標準のタプルのサブクラスを作るファクトリー関数です。 例えば次のようになります。

    >>> var_type = collections.namedtuple('variable',
    ...             'id name type size')
    >>> # 名前はスペースまたはカンマで区切る。
    >>> # 'id, name, type, size' でもよい。
    >>> var_type._fields
    ('id', 'name', 'type', 'size')
    
    >>> var = var_type(1, 'frequency', 'int', 4)
    >>> print var[0], var.id    # 同じ意味
    1 1
    >>> print var[2], var.type  # 同じ意味
    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.)

  • Cookie モジュールの Morsel が、httponly 属性に対応しました。 一部のブラウザーでは、この属性を設定したクッキーに JavaScript からアクセスしたり、変更したりすることができません。 (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.)

    # y=0,x=21 から行末までを
    # 太字にする。
    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.)

  • httplib.HTTPConnection と HTTPSConnection のコンストラクターに、タイムアウトを秒単位で指定する省略可能な timeout パラメーターが加わりました。 (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:

    >>> # 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.)

  • socket が、クラスター環境向けに設計された、IP を使わない高性能プロトコル TIPC (https://tipc.sourceforge.net/) に対応しました。 TIPC アドレスは 4 要素または 5 要素のタプルです。 (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.

  • SocketServer の基底クラスは、サーバーの timeout が指定する時間だけ活動がないと、handle_timeout() を呼ぶようになりました。 (Michael Pomraning による貢献です。) serve_forever() には秒単位のポーリング間隔を指定する省略可能な引数が加わり、終了要求を確認する頻度を制御できます。 (Pedro Werneck と Jeffrey Yasskin による貢献です。bpo-742598、bpo-1193577。)

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

  • struct が、書式文字 '?' で C99 の _Bool 型に対応しました。 (David Remahl による貢献です。)

  • subprocess の Popen に、terminate()、kill()、send_signal() メソッドが加わりました。 Windows の send_signal() が対応するシグナルは SIGTERM だけで、これらはすべて Win32 API の TerminateProcess() に相当します。 (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).

  • telnetlib.Telnet のコンストラクターに、秒単位のタイムアウトを指定する省略可能な timeout が加わりました。 (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.)

  • test.test_support に、テストに便利なコンテキストマネージャーが加わりました。 EnvironmentVarGuard() は、環境変数を一時的に変更し、自動的に元へ戻すコンテキストマネージャーです。

    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")
        # ... 警告を発生させるコード ...
        assert str(wrec.message) == "function is outdated"
        assert len(wrec.warnings) == 1, "Multiple warnings raised"
    

    (Contributed by Brett Cannon.)

  • textwrap に drop_whitespace=False を渡すと、新しく作る行の先頭と末尾にある既存の空白を保持できるようになりました。

    >>> 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')
    
    # 単一のファイルを /tmp ディレクトリからの
    # 相対パスへ展開する。
    z.extract('Python/sysmodule.c', '/tmp')
    
    # アーカイブのすべてのファイルを展開する。
    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) # データをエンコード
>>> in_json
'{"parrot": 42, "spam": "foo"}'
>>> json.loads(in_json) # Python オブジェクトへデコード
{"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 を起こします。

  • PEP 352 に従った Exception のインターフェースの変更が続いています。 2.6 では message が非推奨となり、代わりに args を使います。

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

    非推奨となるモジュールは次のとおりです: audiodev, bgenlocations, buildtools, bundlebuilder, Canvas, compiler, dircache, dl, fpformat, gensuitemodule, ihooks, imageop, imgfile, linuxaudiodev, mhlib, mimetools, multifile, new, pure, statvfs, sunaudiodev, test.testall, と toaiff.

  • gopherlib モジュールが削除されました。

  • MimeWriter と mimify が非推奨となりました。 代わりに email を使ってください。

  • md5 が非推奨となりました。 代わりに hashlib を使ってください。

  • posixfile が非推奨となりました。 fcntl.lockf() がより適切なロックを提供します。

  • popen2 が非推奨となりました。 subprocess を使ってください。

  • rgbimg モジュールが削除されました。

  • sets が非推奨となりました。 組み込みの set と frozenset を使う方がよいでしょう。

  • sha が非推奨となりました。 代わりに hashlib を使ってください。

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

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

  • Python のコンパイルには C89 コンパイラーが必須になりました (19 年を経て、ようやくです!)。 そのため、C89 標準ライブラリに含まれる memmove() と strerror() の独自実装が Python のソースツリーから削除されました。

  • 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.)

  • Python 2.6.6 で追加された PySys_SetArgvEx() は sys.argv を設定し、updatepath の値に応じて、sys.argv[0] が示すスクリプトのディレクトリを sys.path に追加することもできます。

    この関数は、Python を組み込むアプリケーションのセキュリティホールを塞ぐために追加されました。 従来の PySys_SetArgv() は常に sys.path を更新し、現在のディレクトリを追加する場合がありました。 そのため、他人が管理するディレクトリで Python を組み込んだアプリケーションを実行すると、攻撃者がそこへトロイの木馬のようなモジュール (例えば os.py) を置き、アプリケーションにインポート・実行させることができました。

    Python を組み込む C/C++ アプリケーションの保守担当者は、PySys_SetArgv() を呼んでいるか確認し、updatepath を偽にした PySys_SetArgvEx() を使うべきか慎重に検討してください。 ただし、この関数を使うと Python 2.6.5 以前との互換性がなくなります。 以前のバージョンにも対応する必要があれば、PySys_SetArgv() はそのままにし、その後 PyRun_SimpleString("sys.path.pop(0)\n") を呼んで sys.path の先頭要素を取り除けます。

    このセキュリティ問題は CVE 2008-5983 として報告され、gh-50003 で議論され、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 の C stdio ライブラリの使用が、スレッドセーフになりました。 少なくとも、基盤となるライブラリと同程度にはスレッドセーフです。 これまでは、一つのスレッドがファイルオブジェクトを閉じる間に別のスレッドが読み書きすると起きる潜在的なバグが、長く残っていました。 2.6 のファイルオブジェクトには、PyFile_IncUseCount() と PyFile_DecUseCount() で操作する参照カウントがあり、ゼロでなければ閉じられません。 FILE * で I/O を行う前、まだ GIL を保持している間に PyFile_IncUseCount() を呼び、GIL を再取得した直後に PyFile_DecUseCount() を呼ぶ必要があります。 (Antoine Pitrou と Gregory P. Smith による貢献です。)

  • 異なるスレッドから同時にモジュールをインポートすることでデッドロックが発生することはなくなりました; 今では ImportError になります。新たな API 関数 PyImport_ImportModuleNoBlock() は最初に sys.modules を探し、インポートロック獲得後にインポートしようと試みます。インポートロックが他のスレッドにより獲得されていれば ImportError が発生します。(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.)

  • 関数ではなくマクロであることを明確にするため、3.0 と 2.6 の両方でいくつかのマクロが改名されました。 Py_Size() は Py_SIZE()、Py_Type() は Py_TYPE()、Py_Refcnt() は Py_REFCNT() になりました。 Python 2.6 では後方互換性のため、大小文字が混在する旧名も使えます。 (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.)

  • msvcrt が、コンソール I/O API の通常版とワイド文字版の両方に対応しました。 getwch() と getwche() はキー入力を読んで Unicode 値を返し、putwch() は Unicode 文字を受け取ってコンソールへ書き込みます。 (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.

  • _winreg に ExpandEnvironmentStrings() が加わり、入力文字列の %NAME% などの環境変数参照を展開できます。 このモジュールのハンドルオブジェクトはコンテキストプロトコルにも対応し、with 文で使えます。 (Christian Heimes による貢献です。)

    _winreg の x64 対応も改善され、DisableReflectionKey()、EnableReflectionKey()、QueryReflectionKey() が公開されました。 64 ビット環境で動く 32 ビットプロセスのレジストリリフレクションを有効・無効にするための関数です。 (bpo-1753245)

  • msilib の Record に、フィールド値を整数や文字列で返す GetInteger() と GetString() が加わりました。 (Floris Bruynooghe による貢献です。bpo-2125。)

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

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

  • macfs が削除されました。 それに伴い、macfs に依存していた macostools.touched() も削除されました。 (bpo-1490190)

  • そのほか、多数の Mac OS 用モジュールが非推奨となり、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, と terminalcommand.

ポート特有の変更: IRIX

多数の古い IRIX 専用モジュールが非推奨となり、Python 3.0 で削除されます: al と AL, cd, cddb, cdplayer, CL と cl, DEVICE, ERRNO, FILE, FL と fl, flp, fm, GET, GLWS, GL と gl, IN, IOCTL, jpeg, panelparser, readcd, SV と sv, torgb, videoreader, と 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 を埋め込んだアプリケーションでは:

  • Python 2.6.6 で PySys_SetArgvEx() が追加され、従来の PySys_SetArgv() を使った場合のセキュリティホールを塞げるようになりました。 PySys_SetArgv() を呼んでいるか確認し、updatepath を偽にした PySys_SetArgvEx() を使うべきか慎重に検討してください。

謝辞

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