What's New In Python 3.0
************************

著者:
   Guido van Rossum

この記事では 2.6 と比較した Python 3.0 での新機能を解説します。 Python
3.0、あるいは "Python 3000"、 "Py3K" は初めて *意図的に後方非互換にし
た* Python のリリースです。 Python 3.0 は2008年12月3日にリリースされま
した。 通常のリリースよりも多くの変更があり、全ての Python ユーザにと
って重要です。 しかし、変更について理解したら Python に実際にはそれほ
ど変更がないことが分かるでしょう。 全体的に見れば、よく知られた悩みの
種が概ね解決され、昔の粗雑なものが取り除かれています。

この記事は全ての新機能を完璧な仕様を示そうとはしませんが、便利な概要に
ついては説明しようとしています。 全詳細については Python 3.0 のドキュ
メントや、本編で引かれている多くの PEP を参照してください。 特定の機能
の実装や設計原理について完全に理解したいなら、通常のドキュメントよりも
詳しいことが書いてある PEP を見るとよいでしょう。 しかし、一旦機能が完
全に実装されると、普通 PEP は最新の状態に保たれないことに注意してくだ
さい。

この文書で全項目に触れるべきなのですが、時間の制約のためそうではありま
せん。 いつもの新リリースのように、 ソース配布の *Misc/NEWS* には些細
な変更についても詳細な情報があります。


よくある悩みの種
================

このセクションは Python 2.5 に慣れていたら躓いてしまいそうな少数の変更
の一覧です。


print関数
---------

"print" 文は "print()" 関数に置き換えられ、古い "print" 文の特殊な文法
の殆どがキーワード引数で置き換えられています (**PEP 3105**)。 例:

   Old: print "The answer is", 2*2
   New: print("The answer is", 2*2)

   Old: print x,           # Trailing comma suppresses newline
   New: print(x, end=" ")  # Appends a space instead of a newline

   Old: print              # Prints a newline
   New: print()            # You must call the function!

   Old: print >>sys.stderr, "fatal error"
   New: print("fatal error", file=sys.stderr)

   Old: print (x, y)       # prints repr((x, y))
   New: print((x, y))      # Not the same as print(x, y)!

項目間の区切りをカスタマイズすることもできます。例:

   print("There are <", 2**32, "> possibilities!", sep="")

これは以下を出力します :

   There are <4294967296> possibilities!

注釈:

* "print()" 関数は、古い "print" 文の "ソフトスペース" 機能をサポート
  しません。例えば Python 2.x では、 "print "A\n", "B"" は ""A\nB\n""
  を出力していましたが、 Python 3.0 では、 "print("A\n", "B")" は
  ""A\n B\n"" を出力します。

* 最初は、対話モードで古い "print x" を何回もタイプしてしまうでしょう
  。代わりに "print(x)" とタイプするよう再教育してください。

* "2to3" ソース変換ツールを使うと、すべての "print" 文が "print()" 関
  数呼び出しに自動的に置換されるので、大きなプロジェクトでもさほど問題
  にならないでしょう。


リストからビューおよびイテレータへ
----------------------------------

いくつかの良く使われている API はもはやリストを返しません:

* "dict" の "dict.keys()", "dict.items()" そして "dict.values()" メソ
  ッドはリストの代わりに "views" を返します。 例えば: "k = d.keys();
  k.sort()" は上手く動きません。 代わりに "k = sorted(d)" を使ってくだ
  さい (これは Python 2.5 でも動作し、効率的です)。

* Also, the "dict.iterkeys()", "dict.iteritems()" and
  "dict.itervalues()" methods are no longer supported.

* "map()" と "filter()" はイテレータを返します。もしも本物のリストが必
  要で、全ての入力シーケンスが同じ長さの場合であれば、簡単に直すなら
  "map()" を "list()" で包みます。例えば "list(map(...))" という具合。
  ですがより良いのは、大抵はリスト内包を使うことです (特に元々のコード
  が "lambda" を使っている場合)。あるいはコードを、リストを全く必要と
  しないように書き換えましょう。とりわけトリッキーなのは、関数に副作用
  を起こさせるために呼び出される "map()" です; この場合確実な変換は普
  通に "for" ループを使うことです (そもそもリストを作ること自体が無駄
  遣いでしょう)。

  入力シーケンスの長さが同じとは限らないならば、 "map()" は最も短いシ
  ーケンスが消費されつくすと処理をやめます。Python 2.x での "map()" 用
  法と全く互換にするにはシーケンスを "itertools.zip_longest()" で包ん
  でください。例えば "map(func, *sequences)" を "list(map(func,
  itertools.zip_longest(*sequences)))" とします。

* "range()" now behaves like "xrange()" used to behave, except it
  works with values of arbitrary size.  The latter no longer exists.

* "zip()" はイテレータを返します。


順序比較
--------

Python 3.0 で順序比較のルールが簡単になりました。

* 順序比較演算子 ("<", "<=", ">=", ">")  は、そのオペランドが自然な順
  序づけを持たない場合 TypeError 例外を送出します。  "1 < ''", "0 >
  None" または "len <= len" のような式は無効になり、 "None < None" は
  "False" を返す代わりに "TypeError" を送出します。その結果、 不均一な
  リスト（訳注：比較不能な型からなる要素が混在するリスト）のソートは意
  味がなくなりました。 -- 全ての要素は互いに比較できなければなりません
  。これは "==" と "!=" 演算子には適用されないことに注意してください:
  別々の比較不可能な型のオブジェクトを比較すると常に、互いに等しくない
  と評価されます。

* "sorted()" and "list.sort()" no longer accept the *cmp* argument
  providing a comparison function.  Use the *key* argument instead.
  N.B. the *key* and *reverse* arguments are now "keyword-only".

* The "cmp()" function should be treated as gone, and the "__cmp__()"
  special method is no longer supported.  Use "__lt__()" for sorting,
  "__eq__()" with "__hash__()", and other rich comparisons as needed.
  (If you really need the "cmp()" functionality, you could use the
  expression "(a > b) - (a < b)" as the equivalent for "cmp(a, b)".)


整数
----

* **PEP 237**: Essentially, "long" renamed to "int". That is, there is
  only one built-in integral type, named "int"; but it behaves mostly
  like the old "long" type.

* **PEP 238**: An expression like "1/2" returns a float.  Use "1//2"
  to get the truncating behavior.  (The latter syntax has existed for
  years, at least since Python 2.2.)

* The "sys.maxint" constant was removed, since there is no longer a
  limit to the value of integers.  However, "sys.maxsize" can be used
  as an integer larger than any practical list or string index.  It
  conforms to the implementation's "natural" integer size and is
  typically the same as "sys.maxint" in previous releases on the same
  platform (assuming the same build options).

* long 整数の "repr()" はもはや末尾に "L" を持ちません。そのため、無条
  件に "L" を取り除くコードは代わりに最後の数字を取り除いてしまうでし
  ょう。 (代わりに "str()" を使用してください。)

* 8進数リテラルが "0720" の形でなくなりました。代わりに "0o720" を使っ
  てください。


Unicode 対 8 ビット、ではなく、テキスト対データに
-------------------------------------------------

バイナリと Unicode について知っていると思っている全てが変わりました。

* Python 3.0 でのコンセプトは、Unicode 文字列と 8 ビット文字列、という
  対比ではなくて、 *テキスト* と (バイナリ) *データ* の違いと考える、
  というものです。全てのテキストは Unicode です; 一方で *エンコードさ
  れた* Unicode はバイナリデータとして表現されます。テキストを保持する
  のに使われる型は "str" で、データには "bytes" を使います。2.x での状
  況との最大の違いは、Python 3.0 でテキストとデータを混ぜようとすれば
  "TypeError" となることです。Python 2.x では Unicode と 8 ビット文字
  列を混ぜたとすれば、8 ビット文字列がたまたま 7 ビット (ASCII) バイト
  だけから出来ていれば動くし非 ASCII バイトがあれば
  "UnicodeDecodeError" となっていたでしょう。この、データ値に依存した
  振る舞いが、何年にも渡って夥しい数の悲劇を生み出していました。

* As a consequence of this change in philosophy, pretty much all code
  that uses Unicode, encodings or binary data most likely has to
  change.  The change is for the better, as in the 2.x world there
  were numerous bugs having to do with mixing encoded and unencoded
  text.  To be prepared in Python 2.x, start using "unicode" for all
  unencoded text, and "str" for binary or encoded data only.  Then the
  "2to3" tool will do most of the work for you.

* Unicode テキストのリテラルに "u"..."" を使うことはもはやできません。
  しかし、バイナリーデータのリテラルには "b"..."" を使わなければなりま
  せん。(---訳注: この "u"..."" は Python 3.3 で再び使えるようになりま
  した。 ---)

* "str" 型と "bytes" 型を混ぜて使うことは出来ませんから、それらはいつ
  でも明示的に変換しなければいけません。 "str" から "bytes" にするには
  "str.encode()" を使ってください。そして "bytes" から "str" にするに
  は "bytes.decode()" を使います。それぞれ "bytes(s, encoding=...)" 、
  "str(b, encoding=...)" を使うことも出来ます。

* Like "str", the "bytes" type is immutable.  There is a separate
  *mutable* type to hold buffered binary data, "bytearray".  Nearly
  all APIs that accept "bytes" also accept "bytearray".  The mutable
  API is based on "collections.MutableSequence".

* raw 文字列リテラル内にある全てのバックスラッシュが「字句通り」に解釈
  されます。つまり "'\U'" も "'\u'" も、 raw 文字列内にあっては何ら特
  別に扱われないということです。例えば "r'\u20ac'" は Python 3.0 では
  6 文字の文字列です。Python 2.x では "ur'\u20ac'" が単一の「ユーロ」
  文字であったのにです。(無論この変更は raw 文字列リテラルについてだけ
  のもので、ユーロ文字は Python 3.0 で "'\u20ac'" です。)

* The built-in "basestring" abstract type was removed.  Use "str"
  instead.  The "str" and "bytes" types don't have functionality
  enough in common to warrant a shared base class.  The "2to3" tool
  (see below) replaces every occurrence of "basestring" with "str".

* テキストファイルとして開かれたファイル (これは従来どおり "open()" で
  のデフォルトのモード) は、 (メモリ内の) 文字列と (ディスクでの) バイ
  ト列との写像をするのに、常にエンコーディングを使います。バイナリファ
  イル (モードに "b" を付けて開いたもの) はメモリ内では常にバイト列を
  使います。このことで、もしもファイルが誤ったモードやエンコーディング
  で開かれようとすると、I/O はきっと口やかましく失敗します。こっそり正
  しくないデータを生み出すのではなく。それに加えて、ファイルを開く際に
  は Unix ユーザでさえもこれからは、 (テキストかバイナリかの) 正しいモ
  ードを選択する必要があるということです。プラットフォームにはそれ特有
  のデフォルトエンコーディングがあります。Unix 的プラットフォームでは
  これは環境変数 "LANG" にセットされているかもしれません (あるいは時々
  ほかのプラットフォーム特有の、ロケールに関係した環境変数にもセットさ
  れています)。全てとは言いませんが多くの場合は、システムのデフォルト
  は UTF-8 です; ですが決してこのデフォルトを当てにすべきではありませ
  ん。純粋な ASCII テキスト以上のものを読み書きするどんなアプリケーシ
  ョンも、きっとエンコーディングをオーバライド出来る手段を持つべきです
  。 "codecs" 内にあるエンコーディングを熟知したストリームを使うことは
  、今ではもう必要なくなりました。

* "sys.stdin", "sys.stdout", "sys.stderr" の初期値はいまでは Unicode
  のみのテキストファイルです (つまりそれらは "io.TextIOBase" のインス
  タンスです)。バイト列データをそれらのストリームで読み書きするには、
  "io.TextIOBase.buffer" 属性を使う必要があります。

* ファイル名は、API へは (Unicode) 文字列を渡し、 (Unicode) 文字列が返
  ります。これにはプラットフォーム特有の問題があるかもしれません。とい
  うのも、いくつかのプラットフォームではファイル名は任意のバイト文字列
  だからです。(他方では、Windows ではファイル名はネイティブに Unicode
  で格納されています。) 次善策として、ほとんどの API (たとえば
  "open()" と "os" モジュール内の多くの関数) はファイル名として、文字
  列だけでなく "bytes" を受け付け、そして少しの API は "bytes" を返す
  かどうかを要求出来る手段を持っています。それゆえに "os.listdir()" は
  引数が "bytes" インスタンスであれば "bytes" のリストで返し、
  "os.getcwdb()" はカレントディレクトリを "bytes" で返します。
  "os.listdir()" が文字列のリストで返す際、適切にデコード出来ないファ
  イル名は "UnicodeError" とはせずに無視されることにご注意ください。

* "os.environ" や "sys.argv" のようないくつかのシステム API にも問題が
  ありえます。システムにより利用可能とされるべきバイト列がデフォルトエ
  ンコーディングで解釈不能な場合です。環境変数 "LANG" をセットしてプロ
  グラムを再実行することが、おそらく最善のアプローチです。

* **PEP 3138**: 文字列への "repr()" はもう非 ASCII 文字をエスケープし
  ません。ただし、制御文字、Unicode 標準で印字不可状態のコードポイント
  は今でもエスケープされます。

* **PEP 3120**: ソースのエンコードのデフォルトが UTF-8 になりました。

* **PEP 3131**: 非 ASCII 文字を識別子として使用することが出来るように
  なりました。 (そうはいっても標準ライブラリは、コメント内での貢献者の
  名前以外では ASCII だけのままです。)

* "StringIO" および "cStringIO" モジュールは廃止されました。その代わり
  "io" モジュールをインポートして、テキストやデータには "io.StringIO"
  や "io.BytesIO" を使用してください。

* Unicode HOWTO を参照してください。Python 3.0 向けに更新されました。


構文の変更の概要
================

このセクションは Python 3.0 における全ての *構文の* 変更についての簡単
な概要です。


新たな構文
----------

* **PEP 3107**: Function argument and return value annotations.  This
  provides a standardized way of annotating a function's parameters
  and return value.  There are no semantics attached to such
  annotations except that they can be introspected at runtime using
  the "__annotations__" attribute.  The intent is to encourage
  experimentation through metaclasses, decorators or frameworks.

* **PEP 3102**: キーワード専用引数。 パラメータリスト中で "*args" のあ
  とに現れる名前付きパラメータは、呼び出す際には *必ず* キーワード引数
  の構文を使う必要があります (---訳注: "def fun(*a, kw):" という定義で
  "fun(1, 2, 3)" は NG で "fun(1, 2, kw=3)" としなければならない。ここ
  までは 2.x と同じ ---)。 この PEP により、可変引数リストを受け取らず
  にキーワード専用引数だけを許したい場合にそれを主張するために剥き出し
  の "*" をパラメータリスト内に書けるようになりました (---訳注: "def
  fun(*, kw):" と定義出来る。この定義では "fun(kw=1)" としてしか呼び出
  せない。 "fun(1)" はダメ。---)。

* クラス定義内で、基底クラスのリストのあとでキーワード引数が許されるよ
  うになりました。これは metaclass を指定するための新しい規約 (次セク
  ション参照) に使われるものですが、 metaclass サポートだけのためだけ
  でなく他の目的に使うことも出来ます。

* **PEP 3104**: "nonlocal" 文。 "nonlocal x" を使うと外側の (ただしグ
  ローバルでない) スコープから、直接変数を代入することが出来るようにな
  ります。 "nonlocal" は新しく予約語になりました。

* **PEP 3132**: 拡張されたイテレータのアンパック。 "a, b, *rest =
  some_sequence" のようなことを書けるようになりました。 "*rest, a =
  stuff" も出来ます。 "rest" オブジェクトは常に (空かもしれなくても)
  リストです; 右辺には任意のイテラブルを置けます。例えば:

     (a, *rest, b) = range(5)

  これは *a* に "0" を、 *b* に "4" を、そして *rest* に "[1, 2, 3]"
  をセットします。

* 辞書内包表記: "{k: v for k, v in stuff}" は "dict(stuff)" と同じ意味
  ですが、より柔軟です。 (これは **PEP 274** で支持されています。)

* セットリテラル、例えば "{1, 2}"。"{}" は空の辞書であることに注意して
  ください。空のセットには "set()" を使用してください。セットの内包表
  記もサポートされました。例えば "{x for x in stuff}" は "set(stuff)"
  と同じ意味ですが、より柔軟です。

* 新たな8進数リテラル、e.g. "0o720" (2.6 で既にありました)。古い8進数
  リテラル ("0720") は廃止されました。

* 新たなバイナリリテラル、e.g. "0b1010" (2.6 で既にありました) と、関
  連する新しい組み込み関数 "bin()" が導入されました。

* "b" または "B" で始まるバイトリテラルと、関連する新しい組み込み関数
  "bytes()" が導入されました。


変更された構文
--------------

* **PEP 3109** と **PEP 3134**: 新たな "raise" 文のシンタックス:
  "raise [*expr* [from *expr*]]"。以下を参照してください。

* "as" と "with" は予約語になりました。 (実際には 2.6 から)

* "True"、"False"、および "None" が予約語になりました。(2.6 では既に
  "None" が部分的に制限されていました)

* Change from "except" *exc*, *var* to "except" *exc* "as" *var*.  See
  **PEP 3110**.

* **PEP 3115**: 新たなメタクラスのシンタックス．以下の;

     class C:
         __metaclass__ = M
         ...

  代わりに次のようにしてください:

     class C(metaclass=M):
         ...

  The module-global "__metaclass__" variable is no longer supported.
  (It was a crutch to make it easier to default to new-style classes
  without deriving every class from "object".)

* リスト内包表記はもう "[... for *var* in *item1*, *item2*, ...]" とい
  う構文形をサポートしません。代わりに "[... for *var* in (*item1*,
  *item2*, ...)]" を使用してください。また、リスト内包表記は異なるセマ
  ンティクスを持つことに注意してください。リスト内包表記は "list()" コ
  ンストラクタ内のジェネレータ式の糖衣構文に近く、特にループの制御変数
  はスコープ外ではもう使用することができません。

* *ellipsis* ("...") はどこででも原子的な式として使うことが出来ます。
  (以前はスライス内でのみ許されていました。) また、"..." と書かなけれ
  ば *ならなく* なりました。 (以前は文法の些細な偶然により ". . ." と
  書くことも出来ました。)


削除された操作
--------------

* **PEP 3113**: タプル引数のアンパックが削除されました.  "def foo(a,
  (b, c)): ..." のように書くことはできません。かわりに "def foo(a,
  b_c): b, c = b_c" を使用してください。

* バッククオートが削除されました (代わりに "repr()" を使用してください
  )。

* "<>" が削除されました (代わりに "!=" を使用してください)。

* 削除されたキーワード: "exec()" はキーワードでなくなりましたが、関数
  として残りました。 (幸運にも関数のシンタックスは 2.x でも許容されて
  います。)  また、 "exec()" はストリーム引数を受け取らなくなりました
  。"exec(f)" の代わりに "exec(f.read())" を使うことができます。

* "l" または "L" で終わる整数リテラルはサポートされません。

* "u" or "U" で始まる文字列リテラルはサポートされません。(---訳注: こ
  の "u"..."" は Python 3.3 で再び使えるようになりました。 ---)

* "from" *module* "import" "*" はモジュールレベルでのみ許され、関数内
  での使用は許されません。

* 相対インポートに許される構文は "from .[*module*] import *name*" のみ
  です。 "." で始まらない形の全ての "import" は絶対インポートと解釈さ
  れます。 (**PEP 328**)

* 古い形式のクラスはサポートされません。


Python 2.6 で既にあった変更
===========================

おそらく多くのユーザが一足飛びに Python 2.5 から Python 3.0 に移行しよ
うとするでしょうから、このセクションでは、もともとは Python 3.0 のため
にデザインされたものの Python 2.6 にバックポートされた新機能について、
読者に思い出してもらいましょう。 What's New in Python 2.6 内の対応する
セクションにはもっと長い説明が書かれています。

* PEP 343: "with" ステートメント. "with" 文は今では標準機能となったの
  で、 "__future__" からインポートする必要はもうありません。 コンテキ
  ストマネージャを書く と contextlib モジュール も見てください。

* PEP 366: メインモジュールからの明示的相対インポート. "-m" オプション
  の有用性を強化します。パッケージ内にあるモジュールを参照している際に
  関係します。

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

* PEP 371: multiprocessing パッケージ.

* PEP 3101: 進化版文字列フォーマッティング. 注意: 2.6 の記述では
  "format()" メソッドが 8 ビット文字列と Unicode 文字列両方について述
  べていますが、3.0 では "str" 型 (Unicode サポートを持ったテキスト文
  字列) だけがこのメソッドをサポートしています。 "bytes" 型にはありま
  せん。計画では最終的にはこれだけが唯一の文字列フォーマットの API に
  なり、Python 3.1 では "%" 演算子は非推奨扱いを開始する予定です。(---
  訳注: "%" 演算子の撤廃は影響が大き過ぎるからか、現実には (ドキュメン
  トでの軽い記述を除き) 実行時に特別に非推奨扱いされることは 3.5 にな
  ってさえもいまだありません。 ---)

* PEP 3105: print を関数にする. これはもはや標準機能となったので、
  "__future__" からインポートする必要はありません。詳細はこのドキュメ
  ントの上の方に書いてあります。

* PEP 3110: 例外処理の変更.  The "except" *exc* "as" *var* syntax is
  now standard and "except" *exc*, *var* is no longer supported.  (Of
  course, the "as" *var* part is still optional.)

* PEP 3112: バイトリテラル. 文字列リテラル "b"..."" 表記 (とそのお仲間
  "b'...'", "b"""..."""", "br"..."" など) は今では "bytes" 型です。

* PEP 3116: 新しい I/O ライブラリ.  The "io" module is now the
  standard way of doing file I/O.  The built-in "open()" function is
  now an alias for "io.open()" and has additional keyword arguments
  *encoding*, *errors*, *newline* and *closefd*.  Also note that an
  invalid *mode* argument now raises "ValueError", not "IOError".  The
  binary file object underlying a text file object can be accessed as
  "f.buffer" (but beware that the text object maintains a buffer of
  itself in order to speed up the encoding and decoding operations).

* PEP 3118: 改訂版バッファプロトコル.  The old builtin "buffer()" is
  now really gone; the new builtin "memoryview()" provides (mostly)
  similar functionality.

* PEP 3119: 抽象基底クラス.  The "abc" module and the ABCs defined in
  the "collections" module plays a somewhat more prominent role in the
  language now, and built-in collection types like "dict" and "list"
  conform to the "collections.MutableMapping" and
  "collections.MutableSequence" ABCs, respectively.

* PEP 3127: 整数リテラルのサポートと文法. 上述のとおり、新しい 8 進数
  リテラル表現だけが唯一の 8 進数リテラル表現となり、また、バイナリリ
  テラルが追加されました。

* PEP 3129: クラスデコレータ.

* PEP 3141: 数値の型階層. "numbers" が、もう一つの新しく ABC を使うモ
  ジュールで、Python の「数値塔 (numeric tower)」を定義しています。新
  しい "fractions" モジュールが "numbers.Rational" を実装していること
  にも注目してください。


ライブラリの変更
================

時間の制約により、この文書は標準ライブラリの非常に幅広い変更について徹
底的に取り上げてはいません。 ライブラリの大きな変更については **PEP
3108** を参照してください。 ここでは要約を示します:

* 多くの古いモジュールは削除されました。 "gopherlib" (もう使われません
  ) や "md5" ("hashlib" に代替されました) 等のいくつかのモジュールは
  **PEP 4** で既に廃止予定でした。 他のモジュールは、Irix、BeOS ならび
  に Mac OS 9 等のプラットフォームでのサポートが打ち切られた (**PEP
  11** 参照) ために削除されました。 いくつかのモジュールは使われなかっ
  たり、より良い代用品があるため Python 3.0 で削除されました 網羅的な
  リストは **PEP 3108** を参照してください。

* The "bsddb3" package was removed because its presence in the core
  standard library has proved over time to be a particular burden for
  the core developers due to testing instability and Berkeley DB's
  release schedule.  However, the package is alive and well,
  externally maintained at
  https://www.jcea.es/programacion/pybsddb.htm.

* いくつかのモジュールは **PEP 8** に従っていないか、その他の理由によ
  り名前が変更されました:

  +-------------------------+-------------------------+
  | 以前の名前              | 新しい名前              |
  |=========================|=========================|
  | _winreg                 | winreg                  |
  +-------------------------+-------------------------+
  | ConfigParser            | configparser            |
  +-------------------------+-------------------------+
  | copy_reg                | copyreg                 |
  +-------------------------+-------------------------+
  | Queue                   | queue                   |
  +-------------------------+-------------------------+
  | SocketServer            | socketserver            |
  +-------------------------+-------------------------+
  | markupbase              | _markupbase             |
  +-------------------------+-------------------------+
  | repr                    | reprlib                 |
  +-------------------------+-------------------------+
  | test.test_support       | test.support            |
  +-------------------------+-------------------------+

* A common pattern in Python 2.x is to have one version of a module
  implemented in pure Python, with an optional accelerated version
  implemented as a C extension; for example, "pickle" and "cPickle".
  This places the burden of importing the accelerated version and
  falling back on the pure Python version on each user of these
  modules.  In Python 3.0, the accelerated versions are considered
  implementation details of the pure Python versions. Users should
  always import the standard version, which attempts to import the
  accelerated version and falls back to the pure Python version.  The
  "pickle" / "cPickle" pair received this treatment.  The "profile"
  module is on the list for 3.1.  The "StringIO" module has been
  turned into a class in the "io" module.

* 関連のあるモジュールのいくつかはパッケージにまとめられ、ふつうサブモ
  ジュール名は単純化されました。結果として以下のようなパッケージが出来
  ました:

  * "dbm" ("anydbm", "dbhash", "dbm", "dumbdbm", "gdbm", "whichdb").

  * "html" ("HTMLParser", "htmlentitydefs").

  * "http" ("httplib", "BaseHTTPServer", "CGIHTTPServer",
    "SimpleHTTPServer", "Cookie", "cookielib").

  * "tkinter" (all "Tkinter"-related modules except "turtle").  The
    target audience of "turtle" doesn't really care about "tkinter".
    Also note that as of Python 2.6, the functionality of "turtle" has
    been greatly enhanced.

  * "urllib" ("urllib", "urllib2", "urlparse", "robotparse").

  * "xmlrpc" ("xmlrpclib", "DocXMLRPCServer", "SimpleXMLRPCServer").

**PEP 3108** で取り上げられていない標準ライブラリーの他の変更:

* Killed "sets".  Use the built-in "set()" class.

* Cleanup of the "sys" module: removed "sys.exitfunc()",
  "sys.exc_clear()", "sys.exc_type", "sys.exc_value",
  "sys.exc_traceback".  (Note that "sys.last_type" etc. remain.)

* Cleanup of the "array.array" type: the "read()" and "write()"
  methods are gone; use "fromfile()" and "tofile()" instead.  Also,
  the "'c'" typecode for array is gone -- use either "'b'" for bytes
  or "'u'" for Unicode characters.

* Cleanup of the "operator" module: removed "sequenceIncludes()" and
  "isCallable()".

* Cleanup of the "thread" module: "acquire_lock()" and
  "release_lock()" are gone; use "acquire()" and "release()" instead.

* Cleanup of the "random" module: removed the "jumpahead()" API.

* The "new" module is gone.

* The functions "os.tmpnam()", "os.tempnam()" and "os.tmpfile()" have
  been removed in favor of the "tempfile" module.

* "tokenize" モジュールはバイトでも機能するように変更されました。メイ
  ンのエントリポイントは generate_tokens から "tokenize.tokenize()" に
  なりました。

* "string.letters" and its friends ("string.lowercase" and
  "string.uppercase") are gone.  Use "string.ascii_letters" etc.
  instead.  (The reason for the removal is that "string.letters" and
  friends had locale-specific behavior, which is a bad idea for such
  attractively named global "constants".)

* Renamed module "__builtin__" to "builtins" (removing the
  underscores, adding an 's').  The "__builtins__" variable found in
  most global namespaces is unchanged.  To modify a builtin, you
  should use "builtins", not "__builtins__"!


**PEP 3101**: 文字列整形の新たなアプローチ
==========================================

* 組み込みの新しい文字列書式化操作で、文字列の "%" 演算子を置き換える
  ものです。(しかしながら "%" 演算子はまだサポートされます; Python 3.1
  で非推奨となり、将来のいつかの時点で削除されます。) 完全な詳細は
  **PEP 3101** をお読み下さい。 (--- 訳注: Python 2.6 で既にあった変更
  での対応する記述に書いた訳注を参照。---)


例外に関する変更
================

例外の送出や捕捉を行う API は整理され、 強力な新機能が追加されました:

* **PEP 352**: 全ての例外は (直接的にまたは間接的に) "BaseException"
  を継承しなければなりません。 "BaseException" は例外階層の根です。 こ
  れは勧告としては新しくありませんが、"BaseException" 継承の *要求* は
  新しいです。 (Python 2.6 は依然として昔のクラスを送出するのを許容し
  ており、捕捉するものについての制限はありません。) 結果として文字列例
  外は終に本当の意味で、完全になくなりました。

* ほとんど全ての例外は、実際は "Exception" を継承すべきです。
  "BaseException" は最上位で扱われるべき例外、例えば "SystemExit" や
  "KeyboardInterrupt" の基底クラスとしてのみ使われるべきでしす。上記カ
  テゴリーを除く全ての例外を処理するのに推奨されるイディオムは
  "except" "Exception" です。

* "StandardError" was removed.

* Exceptions no longer behave as sequences.  Use the "args" attribute
  instead.

* **PEP 3109**: Raising exceptions.  You must now use "raise
  *Exception*(*args*)" instead of "raise *Exception*, *args*".
  Additionally, you can no longer explicitly specify a traceback;
  instead, if you *have* to do this, you can assign directly to the
  "__traceback__" attribute (see below).

* **PEP 3110**: 例外の捕捉。 "except *SomeException*, *variable*" では
  なく "except *SomeException* as *variable*" としなければなりません。
  その上 "except" ブロックがある場合 *variable* は明示的に削除されます
  。

* **PEP 3134**: Exception chaining.  There are two cases: implicit
  chaining and explicit chaining.  Implicit chaining happens when an
  exception is raised in an "except" or "finally" handler block.  This
  usually happens due to a bug in the handler block; we call this a
  *secondary* exception.  In this case, the original exception (that
  was being handled) is saved as the "__context__" attribute of the
  secondary exception. Explicit chaining is invoked with this syntax:

     raise SecondaryException() from primary_exception

  (where *primary_exception* is any expression that produces an
  exception object, probably an exception that was previously caught).
  In this case, the primary exception is stored on the "__cause__"
  attribute of the secondary exception.  The traceback printed when an
  unhandled exception occurs walks the chain of "__cause__" and
  "__context__" attributes and prints a separate traceback for each
  component of the chain, with the primary exception at the top.
  (Java users may recognize this behavior.)

* **PEP 3134**: Exception objects now store their traceback as the
  "__traceback__" attribute.  This means that an exception object now
  contains all the information pertaining to an exception, and there
  are fewer reasons to use "sys.exc_info()" (though the latter is not
  removed).

* Windows が拡張モジュールのロードに失敗したときの例外メッセージが少し
  改善しました。 例えば、"error code 193" は "%1 is not a valid Win32
  application" になりました。 文字列は英語でないロケールを扱えるように
  なりました。


その他の変更
============


演算子と特殊メソッド
--------------------

* "!=" は "==" と逆の結果をかえします（"==" が "NotImplemented" を返さ
  なければ）。

* 「非束縛メソッド (unbound methods)」という概念は言語から削除されまし
  た。クラス属性としてのメソッドを参照しても今では普通の関数オブジェク
  トが得られます。

* "__getslice__()", "__setslice__()" and "__delslice__()" were killed.
  The syntax "a[i:j]" now translates to "a.__getitem__(slice(i, j))"
  (or "__setitem__()" or "__delitem__()", when used as an assignment
  or deletion target, respectively).

* **PEP 3114**:  "next()" 標準メソッドは "__next__()" に改名されました
  。

* The "__oct__()" and "__hex__()" special methods are removed --
  "oct()" and "hex()" use "__index__()" now to convert the argument to
  an integer.

* Removed support for "__members__" and "__methods__".

* The function attributes named "func_X" have been renamed to use the
  "__X__" form, freeing up these names in the function attribute
  namespace for user-defined attributes.  To wit, "func_closure",
  "func_code", "func_defaults", "func_dict", "func_doc",
  "func_globals", "func_name" were renamed to "__closure__",
  "__code__", "__defaults__", "__dict__", "__doc__", "__globals__",
  "__name__", respectively.

* "__nonzero__()" is now "__bool__()".


組み込み
--------

* **PEP 3135**: 新しくなった "super()" 。今では "super()" は引数なしで
  呼び出せます。(これが "class" 内で定義される通常のインスタンスメソッ
  ド内であると仮定して) 正しいクラスとインスタンスが自動的に選択されま
  す。引数ありの場合の "super()" の振る舞いには変更はありません。

* **PEP 3111**: "raw_input()" was renamed to "input()".  That is, the
  new "input()" function reads a line from "sys.stdin" and returns it
  with the trailing newline stripped. It raises "EOFError" if the
  input is terminated prematurely. To get the old behavior of
  "input()", use "eval(input())".

* 新しい組み込み関数 "next()" が追加されました。 オブジェクトの
  "__next__()" メソッドを呼び出します。

* "round()" 関数の丸めの戦略と戻り値の型が変更されました。ど真ん中の場
  合に、四捨五入ではなく最近接偶数への丸めをするようになりました。(例
  えば "round(2.5)" は今では "2" を返します。 "3" ではなく。) (---訳注
  : 丸めモードについては Wikipedia 参照。---) "round(x[, n])" は常に浮
  動小数点数の結果を返す代わりに、 "x.__round__([n])" に処理を委譲する
  ようになりました。これは一般的に、単一引数で呼ばれた際に整数を返し、
  二つの引数で呼ばれた場合は "x" と同じ型の値として返します。

* Moved "intern()" to "sys.intern()".

* Removed: "apply()".  Instead of "apply(f, args)" use "f(*args)".

* Removed "callable()".  Instead of "callable(f)" you can use
  "isinstance(f, collections.Callable)".  The "operator.isCallable()"
  function is also gone.

* Removed "coerce()".  This function no longer serves a purpose now
  that classic classes are gone.

* Removed "execfile()".  Instead of "execfile(fn)" use
  "exec(open(fn).read())".

* Removed the "file" type.  Use "open()".  There are now several
  different kinds of streams that open can return in the "io" module.

* Removed "reduce()".  Use "functools.reduce()" if you really need it;
  however, 99 percent of the time an explicit "for" loop is more
  readable.

* Removed "reload()".  Use "imp.reload()".

* Removed. "dict.has_key()" -- use the "in" operator instead.


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

時間がないため、以下のC APIへの変更点のリストは *かなり* 不完全です。

* Mac OS 9, BeOS, RISCOS, Irix, Tru64 に限らず、いくつものプラットフォ
  ームのサポートが打ち切られました。

* **PEP 3118**: 新たなバッファ API。

* **PEP 3121**: 例外モジュールの初期化と最終化

* **PEP 3123**: "PyObject_HEAD" を標準的な C に一致。

* 制限付き実行 の C API サポートはこれ以上されません。

* "PyNumber_Coerce()", "PyNumber_CoerceEx()", "PyMember_Get()", and
  "PyMember_Set()" C APIs are removed.

* 新たな C API "PyImport_ImportModuleNoBlock()"、
  "PyImport_ImportModule()" のように動きますが、インポートロックでブロ
  ックしません (代わりにエラーを返します)。

* ブール変換の C 水準のスロットとメソッドがリネームされました:
  "nb_nonzero" が "nb_bool" になりました。

* Removed "METH_OLDARGS" and "WITH_CYCLE_GC" from the C API.


性能
====

3.0 の可搬化 (generalization) による正味の結果は、Python 3.0 を
pystone ベンチマークすると Python 2.5 より 10% 遅くなる、というもので
した。これはどうやら小さい整数についての特殊処理を削除したことに一番大
きな要因があるようです。これには改善の余地がありますが、それは 3.0 リ
リース以降でしょう!


Python 3.0 への移植
===================

(---訳注: 今では独立したクックブック How to port Python 2 Code to
Python 3 があるのでそちらをご覧下さい。---) 既存の Python 2.5 や 2.6
のソースコードを Python 3.0 に移植する最良の策は以下の通りです:

* (必須:) 優秀なテストカバレッジから始めてください。

* Python 2.6 に移植します。Python 2.x を Python 2.(x+1) に移植する普通
  の作業以上のことをしてはいけません。確実に全てのテストを通してくださ
  い。

* (まだ 2.6 を使います:) コマンドラインに "-3" オプションを渡します。
  これは 3.0 で削除された (または変更された) 機能についての警告発行を
  有効にします。再びテストスイートを実行して、そして警告が出たコードを
  それがなくなるまで修正し、全てのテストをパスさせます。

* Run the "2to3" source-to-source translator over your source code
  tree.  Run the result of the translation under Python 3.0.  Manually
  fix up any remaining issues, fixing problems until all tests pass
  again.

Python 2.6 と 3.0 両方で変更なしに動作するコードを書こうとすることはお
奨め出来ません; それをするととても捻じ曲がったコーディングスタイルを使
う必要があるでしょう。例えば "print" やメタクラスを避けたりとかそんな
。Python 2.6 と 3.0 両バージョンともに対するサポートを必要とするライブ
ラリを保守しているのであれば、最良のアプローチは上記スリーステップを修
正して、2.6 版のソースコードを編集して "2to3" する、を繰り返すことです
。これは 3.0 版のソースコードを編集するより良いです。(---訳注: ここで
言っていることは正論なのですが、 "2to3" は「Python 3 では動くが Python
2 では動かない (かもしれない)」ものを生成します。2016 時点でも Python
2.7 はかなり元気 (予定では 2020 年までは公式にサポートされる) ですので
両バージョン (ただし今だと 2.7 と 3.2 以降) で変更なしで動作するものを
必要とすることは、残念ながらまだ多いでしょう (あなたが作っているのがラ
イブラリであるならば)。これについては How to port Python 2 Code to
Python 3 に少し書かれています。 ---)

C 拡張を Python 3.0 に移植するには、 Python 3 への拡張モジュール移植
を参照してください。
