What's New in Python 2.4
************************

著者:
   A.M. Kuchling

この文書は 2005 年 3 月 30 日にリリースされた Python 2.4.1 の新機能に
ついて解説します。

Python 2.4 は、真ん中サイズ、のリリースです。急進的だった Python 2.2
ほどには多くの変更をしていませんが、保守的だった 2.3 よりは多くの機能
を導入しています。新しい言語機能で最も重要なのが、関数デコレータとジェ
ネレータ式です。ほかのほとんどの変更は標準ライブラリに対するものです。

Python 2.3 から 2.4 の CVS 変更ログによれば、適用されたパッチは 481、
フィックスされたバグは 502 ありました。ともに、少なく見積もって、です
。

このドキュメントは個々の新機能の完全な詳細を提供するのではなくて、簡易
な概要を提供することを目的にしています。完全な詳細が知りたければ、
Python ライブラリリファレンス、Python リファレンスマニュアルのような
Python 2.4 のドキュメントを参照してください。多くの場合個別の新機能に
ついての実装の説明やデザインの根拠については PEP に託されています。


PEP 218: ビルトインの集合オブジェクト
=====================================

Python 2.3 introduced the "sets" module.  C implementations of set
data types have now been added to the Python core as two new built-in
types, "set(iterable)" and "frozenset(iterable)".  They provide high
speed operations for membership testing, for eliminating duplicates
from sequences, and for mathematical operations like unions,
intersections, differences, and symmetric differences.

   >>> a = set('abracadabra')              # 文字列から集合を作る
   >>> 'z' in a                            # 高速な所属判定
   False
   >>> a                                   # a に含まれる重複しない文字
   set(['a', 'r', 'b', 'c', 'd'])
   >>> ''.join(a)                          # 文字列に戻す
   'arbcd'

   >>> b = set('alacazam')                 # 2 つ目の集合を作る
   >>> a - b                               # a に含まれ b に含まれない文字
   set(['r', 'd', 'b'])
   >>> a | b                               # a または b に含まれる文字
   set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
   >>> a & b                               # a と b の両方に含まれる文字
   set(['a', 'c'])
   >>> a ^ b                               # a または b の片方だけに含まれる文字
   set(['r', 'd', 'b', 'm', 'z', 'l'])

   >>> a.add('z')                          # 新しい要素を追加
   >>> a.update('wxy')                     # 複数の新しい要素を追加
   >>> a
   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
   >>> a.remove('x')                       # 要素を一つ取り除く
   >>> a
   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])

"frozenset()" 型は "set()" の immutable 版です。 immutable かつハッシ
ュ可能なので、辞書のキーやほかの set のメンバとして使えるでしょう。

The "sets" module remains in the standard library, and may be useful
if you wish to subclass the "Set" or "ImmutableSet" classes.  There
are currently no plans to deprecate the module.

参考:

  **PEP 218** - 集合オブジェクト型をビルトインに追加する
     元々は Greg Wilson によって提案され、完全な実装は Raymond
     Hettinger によってなされました。


PEP 237: 長整数と整数を一体化していく
=====================================

この PEP の非常に長期に渡る移行は Python 2.2 に始まり、Python 2.4 でさ
らにもう一歩前進しています。2.3 では int/long の一体化後に異なる振る舞
いをする整数演算をすると "FutureWarning" 警告を出して、結果の値は (プ
ラットフォーム依存で) 32 ビットまたは 64 ビットに制限していました。2.4
ではこれらの式はもう警告は出さず、代わりにいつでも(2.3 とは違った)長整
数となる結果をはじき出します。

問題を起こしうる式は主として左シフトで、そして長い 16 進リテラルと 8
進リテラルです。例えば "2 << 32" は 2.3 では警告とともに 32 ビットプラ
ットフォームでは結果は 0 になります。Python 2.4 ではこの式は正しい答え
の 8589934592 になります。

参考:

  **PEP 237** - 長整数と整数を一体化していく
     オリジナルの PEP は Moshe Zadka と GvR (Guido van Rossum) によっ
     て書かれました。.2.4 での変更については Kalle Svensson によって実
     装されました。


PEP 289: ジェネレータ式
=======================

Python 2.2 で導入されたイテレータ機能と "itertools" モジュールによって
、データセット全体を一度にメモリへ読み込まずに、大きなデータセットをル
ープで処理するプログラムが書きやすくなりました。 リスト内包表記はすべ
ての要素を含む Python のリストオブジェクトを作るので、この用途にはあま
り向きません。 必然的にすべてのオブジェクトをメモリへ読み込むことにな
り、データセットが非常に大きい場合には問題になり得ます。 関数型のスタ
イルでプログラムを書こうとすると、次のように書くのが自然でしょう。

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

こうではなく

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

最初の形の方が簡潔でおそらく読みやすいですが、扱っているのがとても多く
のリンクオブジェクトであるならば、全てのリンクオブジェクトが一気にメモ
リに載らないように二つ目の形で書く必要がありました。

ジェネレータ式はリスト内包と似た動作をしますが、リスト全体を実体化しま
せん; 代わりにそれは、要素を一つずつ返すジェネレータを返します。上述の
例はこう書けます:

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

上の例でのように、ジェネレータ式は常に括弧の中に書かなければなりません
。関数呼び出しを囲む括弧もそれに含まれるので、関数にそのまま渡すイテレ
ータを作りたければこれで良いです:

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

ジェネレータ式はリスト内包とは色々小さい点で違います。最も顕著なのはル
ープ変数 (上の例での *obj*) がジェネレータ式の外からアクセス不能なこと
です。リスト内包はループの制御変数が最後に代入された値で残ります; 将来
のバージョンの Python では、この振る舞いはリスト内包がこの点でジェネレ
ータ式と同じになるように変更されます。 (---訳注: Python 2.7 でもリスト
内包のこの振る舞いは変わっておらず、警告ともなりません。制御変数が内包
のスコープ外で可視でなくなったのは Python 3.0 からです。---)

参考:

  **PEP 289** - ジェネレータ式
     Raymond Hettinger によって提案され、Hye-Shik Chang に導かれた早期
     の尽力によって Jiwon Seo により実装されました。


PEP 292: より単純な文字列置換 (string substitution)
===================================================

標準ライブラリに、文字列を変数で置換するための代替メカニズムをもたらす
新しいくつかのクラスが追加されました; この置換のスタイルは、訓練されて
いないユーザがテンプレートを編集する必要があるようなアプリケーションに
とって、より良いものでしょう。

変数置換を名前で行うためのいつもの方法は "%" 演算子です:

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

テンプレート文字列を書くのに、閉じ括弧のあとの "i" や "s" を忘れやすい
です。これはそのテンプレートが Python モジュール内にあるなら大問題でも
ありません。コードを実行し、「サポートされないフォーマット文字
(unsupported format character)」な "ValueError" を喰らい、問題を直すだ
けのことです。ですが、例えば Mailman のようなアプリケーションを考えて
みてください。テンプレート文字列や翻訳は、Python 言語について承知して
いないユーザが編集するのです。フォーマット文字列の構文はそのようなユー
ザに説明するには複雑で、彼らが間違いをやらかした場合には、親切なフィー
ドバックを彼らに与えるのは難しいのです。

PEP 292 adds a "Template" class to the "string" module that uses "$"
to indicate a substitution:

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

If a key is missing from the dictionary, the "substitute()" method
will raise a "KeyError".  There's also a "safe_substitute()" method
that ignores missing keys:

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

参考:

  **PEP 292** - より単純な文字列置換 (string substitution)
     Barry Warsaw 著、実装


PEP 318: 関数とメソッドのためのデコレータ
=========================================

Python 2.2 は Python オブジェクトモデルを静的メソッド、クラスメソッド
を追加することで拡張はしましたが、それらを定義する新たな手段を提供する
ような Python 構文の拡張はしませんでした。このため、 "def" でメソッド
は普通に書いたのち、新型メソッドとしての関数へ仕立て上げる
"staticmethod()" または "classmethod()" にその結果のメソッドを渡す、と
いう手順を取る必要がありました。このような具合でした:

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

      meth = classmethod(meth)   # ラップしたクラスメソッドに名前を束縛し直す

メソッドがとても長かったりすると、関数のボディの後ろの "classmethod()"
呼び出しは見失ったり忘れたりしやすいものでした。

そのような定義をもっと読みやすくするために何か構文を追加する、という意
図は常にありましたが、2.2 のリリース時点では良い構文は明らかではありま
せんでした。本日時点でさえ *いまだ* 明らかとは言えませんが、ユーザは静
的メソッドとクラスメソッドを簡単に手にする手段を注文し続けています; 新
たな構文的機能はこの要求に合うように追加されました。

この新たな機能は「関数デコレータ (function decorators)」と呼ばれます。
この名前は "classmethod()", "staticmethod()", とその仲間たちが関数オブ
ジェクトに追加的な情報を保存することから着想を得たものです; それらは関
数をより多くの詳細で *デコレート (修飾) している* というわけです。

記法は Java より拝借して "'@'" 文字を指示子として使います。この新たな
構文を使うと、上記の例はこのように書けます:

   class C:

      @classmethod
      def meth (cls):
          ...

"@classmethod" は "meth=classmethod(meth)" 代入の速記法です。より一般
的には、このように書けば…:

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

これはデコレータ前史の以下コードと等価です:

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

デコレータは関数定義の前になければなりません。一行ごとに一つのデコレー
タです。 def ステートメントと同じ行にあってはダメです。つまり "@A def
f(): ..." は不正です。モジュールレベルかクラス内の関数定義のみをデコレ
ート出来ます; クラス定義はデコレート出来ません。(--- 訳注: クラス定義
のデコレータは Python 2.6 で追加されました (PEP 3129) 。---)

デコレータはただの関数です。引数としてデコレートされる関数を取り、同じ
関数か何か新しいオブジェクトを返すだけの。結果がほかのデコレータ適用さ
れるの出ない限りは、デコレータの戻り値は呼び出し可能である必要はありま
せん (普通はそうですが)。あなた自身のデコレータを書くのは簡単です。続
く単純な例は、関数オブジェクトに単に属性をセットするだけのものです:

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

もう少しだけ現実的な例として、続く例ではデコレータに、与えられた引数が
整数かどうかチェックさせてみます:

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

       return wrapper

   @require_int
   def p1 (arg):
       print arg

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

**PEP 318** にある例はこのアイディアのもっと凝った版が含まれていて、そ
れは要求型の指定と戻り値のチェックの両方が出来ます。

デコレータ関数は引数を取ることが出来ます。引数が与えられた場合、あなた
のデコレータ関数はそれら引数のみで呼び出され、そして新しいデコレータを
返さなければなりません; この関数は単一の関数を取らなければならず、前述
のように関数を返さなければなりません。言い換えると、 "@A @B @C(args)"
はこうなります:

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

これが正しいと理解するには少しばかり頭をひねる必要がありますが、難しす
ぎることはありません。

関連する小さな変更として、関数の "func_name" 属性が書き換え可能になり
ました。 この属性はトレースバックで関数名を表示するために使われるので
、デコレーターで新しい関数を作って返す場合は、その名前を変更するように
してください。

参考:

  **PEP 318** - 関数、メソッド、クラスのためのデコレータ
     Kevin D. Smith, Jim Jewett, Skip Montanaro により著されました。数
     多くの人々が関数デコレータ実装のパッチを書きましたが、実際にチェ
     ックインされたものは Mark Russell が書いた #979728 でした。

  https://wiki.python.org/moin/PythonDecoratorLibrary
     数多くのデコレータ例を含む Wiki ページ。


PEP 322: 逆順のイテレーション
=============================

新しいビルトイン関数 "reversed(seq)" は、シーケンスを受け取って、シー
ケンスの要素を逆順にループするイテレータを返します:

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

"range(1,4)[::-1]" のようにする拡張スライスでのやり方に比較して
"reversed()" は読みやすく、実行が高速で、大体の場合はメモリ使用が少な
く済みます。

"reversed()" は任意のイテレータは受け付けず、シーケンスのみ受け付ける
ことに注意してください。イテレータを逆順にしたければ、最初に "list()"
でリストに変換してください:

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

参考:

  **PEP 322**  - 逆順のイテレーション
     Raymond Hettinger 著、実装.


PEP 324: 新しい subprocess モジュール
=====================================

標準ライブラリにはサブプロセスを実行する方法がいくつもあり、機能や複雑
さもそれぞれ異なります。 "os.system(command)" は使いやすいものの、遅く
(シェルのプロセスを起動してコマンドを実行します)、危険でもあります (シ
ェルのメタ文字のエスケープに注意する必要があります)。 "popen2" モジュ
ールにはサブプロセスの標準出力や標準エラーを取得できるクラスがあります
が、名前が分かりにくくなっています。 "subprocess" モジュールはこれを整
理し、必要になり得る機能をすべて備えた統一的なインターフェースを提供し
ます。

"popen2" に複数のクラスがあるのに対し、"subprocess" には
"subprocess.Popen" という一つのクラスがあり、そのコンストラクターがさ
まざまなキーワード引数を受け付けます。

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

*args* は普通は文字列のシーケンスで、サブプロセスとして実行するプログ
ラムへの引数群となります。 (*shell* 引数が真の場合は *args* はシェルに
解釈を任せるために渡す文字列に出来、つまりこの場合 "os.system()" と同
じことをします。)

*stdin*, *stdout*, *stderr* はサブプロセスの入力・出力・エラーのストリ
ームを指定します。ファイルオブジェクトかファイル記述子を渡すことが出来
ます。あるいは定数 "subprocess.PIPE" を渡してサブプロセスと親とのパイ
プを作成することが出来ます。

コンストラクタには多くの便利なオプションがあります:

* *close_fds* はサブプロセス実行前に全てのファイル記述子をクローズする
  ことを要求します。

* *cwd* はサブプロセスを実行する作業ディレクトリを指定します (デフォル
  トは親の作業ディレクトリです)。

* *env* は環境変数を指定する辞書です。

* *preexec_fn* は子が開始する前に呼び出される関数です。

* *universal_newlines* で、子の入出力を、Python の *universal
  newlines* 機能で開きます。

Once you've created the "Popen" instance, you can call its "wait()"
method to pause until the subprocess has exited, "poll()" to check if
it's exited without pausing,  or "communicate(data)" to send the
string *data* to the subprocess's standard input.
"communicate(data)"  then reads any data that the subprocess has sent
to its standard output  or standard error, returning a tuple
"(stdout_data, stderr_data)".

"call()" is a shortcut that passes its arguments along to the "Popen"
constructor, waits for the command to complete, and returns the status
code of the subprocess.  It can serve as a safer analog to
"os.system()":

   sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
   if sts == 0:
       # 成功
       ...
   else:
       # dpkg がエラーを返した
       ...

コマンドはシェルを使うことなく呼び出されます。もしシェルを本当に使いた
いのであればキーワード引数として "shell=True" を与えた上でシーケンスの
代わりに文字列を与えることが出来ます:

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

PEP にはシェルと Python コードの様々な例が採られていて、シェルスクリプ
トをいかにして "subprocess" を用いて Python コードに変換するかを示して
います。PEP のこのセクションを読むことを強くお勧めします。

参考:

  **PEP 324** - subprocess - プロセスのための新たなモジュール
     Fredrik Lundh 他によるサポートによって、Peter Åstrand により PEP
     著と実装が行われました。


PEP 327: Decimal データ型
=========================

Python has always supported floating-point (FP) numbers, based on the
underlying C double type, as a data type.  However, while most
programming languages provide a floating-point type, many people (even
programmers) are unaware that floating-point numbers don't represent
certain decimal fractions accurately.  The new "Decimal" type can
represent these fractions accurately, up to a user-specified precision
limit.


なぜ Decimal が必要なのか?
--------------------------

浮動小数点数が使う表現方法に起因する制約があります。浮動小数点数は 3
つの構成要素から成ります:

* 符号(sign)。正または負。

* 仮数部(mantissa)。一桁の 2 進値に端数部が続きます。例えば 2 進数で
  "1.01" は "1 + 0/2 + 1/4" で 10 進表記で 1.25 です。

* 指数部(exponent)。小数点がその数値のどこに位置するかを表します。

例えば 1.25 は、正の符号を持ち、仮数部の値は (2 進数で) 1.01 で、指数
部は 0 です (小数点は移動の必要がありません)。5 は同じ符号と仮数部を持
ち、指数部は、仮数部が 4 倍なので 2 (2 を底とする 2 の 冪乗) です;
1.25 * 4 は 5 です。

Modern systems usually provide floating-point support that conforms to
a standard called IEEE 754.  C's double type is usually implemented as
a 64-bit IEEE 754 number, which uses 52 bits of space for the
mantissa.  This means that numbers can only be specified to 52 bits of
precision.  If you're trying to represent numbers whose expansion
repeats endlessly, the expansion is cut off after 52 bits.
Unfortunately, most software needs to produce output in base 10, and
common fractions in base 10 are often repeating decimals in binary.
For example, 1.1 decimal is binary "1.0001100110011 ..."; .1 = 1/16 +
1/32 + 1/256 plus an infinite number of additional terms.  IEEE 754
has to chop off that infinitely repeated decimal after 52 digits, so
the representation is slightly inaccurate.

ときどきあなたはこの不正確さを、数値を表示する際に目にするでしょう:

   >>> 1.1
   1.1000000000000001

この不正確さは数値を表示する際にいつでも目に見えるわけではありません。
浮動小数点数から文字列への変換が C ライブラリによって提供されていて、C
ライブラリのほとんどが賢明な出力を生成しようと頑張っているからです。そ
れが表示されないにしても、不正確さはそれでも存在していて、後続の計算へ
の誤差が大きくなりえます。

多くのアプリケーションではこれは重要ではありません。モニタにプロットし
て表示するのに 1.1 と 1.1000000000000001 の差は小さすぎて見えません。
大抵は出力を一定の桁位置までに制限して出力するものですし、2 やら 3 や
ら 8 桁などの位置で丸めたりすれば誤差は決して露わにはなりません。です
がそれが重要なアプリケーションにとっては、あなた自身のカスタム数学ルー
チンのための実装作業は膨大になります。

Hence, the "Decimal" type was created.


The "Decimal" type
------------------

A new module, "decimal", was added to Python's standard library.  It
contains two classes, "Decimal" and "Context".  "Decimal" instances
represent numbers, and "Context" instances are used to wrap up various
settings such as the precision and default rounding mode.

"Decimal" instances are immutable, like regular Python integers and FP
numbers; once it's been created, you can't change the value an
instance represents.  "Decimal" instances can be created from integers
or strings:

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

符号(sign)、10進数値のタプルで表した仮数部(mantissa)、指数部(exponent)
を含んだタプルを渡すことも出来ます:

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

注意: 符号ビットは負符号の有無なので、 0 が正、1  が負です。

Converting from floating-point numbers poses a bit of a problem:
should the FP number representing 1.1 turn into the decimal number for
exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced? The
decision was to dodge the issue and leave such a conversion out of the
API.  Instead, you should convert the floating-point number into a
string using the desired precision and pass the string to the
"Decimal" constructor:

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

Once you have "Decimal" instances, you can perform the usual
mathematical operations on them.  One limitation: exponentiation
requires an integer exponent:

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

You can combine "Decimal" instances with integers, but not with
floating-point numbers:

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

"Decimal" numbers can be used with the "math" and "cmath" modules, but
note that they'll be immediately converted to  floating-point numbers
before the operation is performed, resulting in a possible loss of
precision and accuracy.  You'll also get back a regular floating-point
number and not a "Decimal".

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

"Decimal" instances have a "sqrt()" method that returns a "Decimal",
but if you need other things such as trigonometric functions you'll
have to implement them.

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


The "Context" type
------------------

Instances of the "Context" class encapsulate several settings for
decimal operations:

* "prec" is the precision, the number of decimal places.

* "rounding" specifies the rounding mode.  The "decimal" module has
  constants for the various possibilities: "ROUND_DOWN",
  "ROUND_CEILING", "ROUND_HALF_EVEN", and various others.

* "traps" is a dictionary specifying what happens on encountering
  certain error conditions: either  an exception is raised or  a value
  is returned.  Some examples of error conditions are division by
  zero, loss of precision, and overflow.

There's a thread-local default context available by calling
"getcontext()"; you can change the properties of this context to alter
the default precision, rounding, or trap handling.  The following
example shows the effect of changing the precision of the default
context:

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

エラー状態の場合のデフォルトアクションを選択出来ます; モジュールは無限
大(infinity)あるいは非数(not-a-number: NaN)を返すか、例外を投げるかで
す:

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

The "Context" instance also has various methods for formatting numbers
such as "to_eng_string()" and "to_sci_string()".

さらに詳しく知りたければ "decimal" モジュールのドキュメントを読んで下
さい。これには簡単に始められるチュートリアルとリファレンスが入っていま
す。

参考:

  **PEP 327** - Decimal データ型
     Facundo Batista によって著され、Facundo Batista, Eric Price,
     Raymond Hettinger, Aahz,  Tim Peters らによって実装されました。

  http://www.lahey.com/float.htm
     この記事は浮動小数点数の不正確さが起こりうるたくさんの問題につい
     て、Fortran コードを使って解説しています。

  https://speleotrove.com/decimal/
     10 進数ベースの表現についての記述です(訳注: decimal-based は小数
     ベースとも 10 進数ベースとも取れるのですが、後者にしておきました)
     。この表現方法は標準として提案されていて、この Python の decimal
     型の基礎になっています。この題材の多くが Rexx 言語設計者である
     Mike Cowlishaw によって著されました。


PEP 328: マルチラインインポート
===============================

言語の変更の一つは小さな文法的な微調整で、モジュールからたくさんの名前
をインポートするのを簡単にするためのものです。 "from module import
names" 文において、 *names* はカンマ区切りのシーケンスです。シーケンス
がとても長くなった場合、同じモジュールからのインポート文を何度も書くか
、行末をバックスラッシュでエスケープするかするでしょう、このように:

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

Python 2.4 での文法的な変更は、単純に names を丸括弧で囲んでも良い、と
するだけのものです。Python は丸括弧内の改行を無視しますので、バックス
ラッシュはもう必要ありません:

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

その PEP は、全ての "import" 文が絶対インポートであること、相対インポ
ートであることを示すには "." 文字で開始すること、の提案もしています。
PEP のこの部分は Python 2.4 では実装されていませんが、 Python 2.5 向け
には完了しています。

参考:

  **PEP 328** - マルチラインインポートと、絶対/相対インポート
     Aahz 著.  Multi-line imports は Dima Dorfman により実装。


PEP 331: Locale に依存しない Float/String 変換
==============================================

The "locale" modules lets Python software select various conversions
and display conventions that are localized to a particular country or
language. However, the module was careful to not change the numeric
locale because various functions in Python's implementation required
that the numeric locale remain set to the "'C'" locale.  Often this
was because the code was using the C library's "atof()" function.

しかし数値ロケールを設定しないと、外部の C ライブラリを使う拡張モジュ
ールでは正しいロケールが設定されず、問題が起きました。 変更のきっかけ
となった例は GTK+ で、ユーザーインターフェースのウィジェットが現在のロ
ケールに従って数値を表示していませんでした。

この PEP に記述された解法は、ロケール設定を無視して ASCII のみの変換を
実施する 3 つの新しい Python API 関数を追加することです:

* "PyOS_ascii_strtod(str, ptr)"  and "PyOS_ascii_atof(str, ptr)" both
  convert a string to a C double.

* "PyOS_ascii_formatd(buffer, buf_len, format, d)" は double を ASCII
  文字列に変換します。

これらの関数のコードは GLib ライブラリ (https://developer-
old.gnome.org/glib/2.26/) から来ています。 その開発者たちは親切にも該
当する関数のライセンスを変更し、Python Software Foundation に寄贈して
くれました。 "locale" モジュールは数値ロケールを変更できるようになり、
GTK+ などの拡張モジュールが正しい結果を得られるようになりました。

参考:

  **PEP 331** - Locale に依存しない Float/String 変換
     Christian R. Reis 著, 実装 Gustavo Carneiro.


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

以下が、Python 2.4 言語コアに加えられた全ての変更点です。

* 関数とメソッドのためのデコレータが追加されました。 (**PEP 318**).

* ビルトインの "set()" 型と "frozenset()" 型が追加されました (**PEP
  218**)。ほか新たなビルトイン関数 "reversed(seq)" 関数が追加されまし
  た (**PEP 322**)。

* ジェネレータ式が追加されました (**PEP 289**).

* いくらかの数値式は、もう 32 ビットや 64 ビットに制限されません
  (**PEP 237**).

* "from module import names" ステートメントにおいて、 *names* を括弧で
  囲むことが出来るようになりました (**PEP 328**).

* "dict.update()" メソッドが "dict" コンストラクタと同じ形式の引数を取
  れるようになりました。これには任意のマッピング、キー/値ペアのイテラ
  ブルとキーワード引数を含みます。 (Contributed by Raymond Hettinger.)

* The string methods "ljust()", "rjust()", and "center()" now take an
  optional argument for specifying a fill character other than a
  space. (Contributed by Raymond Hettinger.)

* Strings also gained an "rsplit()" method that works like the
  "split()" method but splits from the end of the string.
  (Contributed by Sean Reifschneider.)

     >>> 'www.python.org'.split('.', 1)
     ['www', 'python.org']
     'www.python.org'.rsplit('.', 1)
     ['www.python', 'org']

* Three keyword parameters, *cmp*, *key*, and *reverse*, were added to
  the "sort()" method of lists. These parameters make some common
  usages of "sort()" simpler. All of these parameters are optional.

  For the *cmp* parameter, the value should be a comparison function
  that takes two parameters and returns -1, 0, or +1 depending on how
  the parameters compare. This function will then be used to sort the
  list.  Previously this was the only parameter that could be provided
  to "sort()".

  *key* には単一パラメータ関数を渡します。これはリスト要素を受け取り、
  要素の比較キーを返す関数です。リストはその比較キーを使ってソートされ
  ます。続く例はリストを大文字小文字区別なく並び替えます:

     >>> L = ['A', 'b', 'c', 'D']
     >>> L.sort()                 # 大文字・小文字を区別してソート
     >>> L
     ['A', 'D', 'b', 'c']
     >>> # 'key' パラメーターでリストをソート
     >>> L.sort(key=lambda x: x.lower())
     >>> L
     ['A', 'b', 'c', 'D']
     >>> # 従来の方法
     >>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
     >>> L
     ['A', 'b', 'c', 'D']

  The last example, which uses the *cmp* parameter, is the old way to
  perform a case-insensitive sort.  It works but is slower than using
  a *key* parameter. Using *key* calls "lower()" method once for each
  element in the list while using *cmp* will call it twice for each
  comparison, so using *key* saves on invocations of the "lower()"
  method.

  単純なキー関数や比較関数には、しばしば "lambda" 関数を避けて非束縛メ
  ソッドを使えます。例えば上記の大文字小文字によらない並べ替えはこのよ
  うに書くのが最善です:

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

  最後の *reverse* パラメータはブーリアン値を取ります。真ならばリスト
  は逆順にソートされます。 "L.sort(); L.reverse()" と書く代わりにこれ
  からは "L.sort(reverse=True)" と書けます。

  ソートの結果がステーブル(安定)であることが保障されるようになりました
  。つまり 2 つの要素が同列である場合、入力と同じ順序が保たれます。例
  えば人物リストを名前でソートしたのちに年齢でソートすると結果は、年齢
  でソートされていますが同年齢の人物は名前順です。

  (All changes to "sort()" contributed by Raymond Hettinger.)

* 新たに追加されたビルトイン関数 "sorted(iterable)" はインプレイスなメ
  ソッド "list.sort()" と似た振る舞いをしますが、式内で使えます。違い
  は:

* 入力には任意のイテラブルを取れます;

* 新しく構築されたコピーをソートし、オリジナルは無傷のままにします; そ
  して

* 式として新しいソート済みコピーを返します。

     >>> L = [9,7,8,3,2,4,1,6,5]
     >>> [10+i for i in sorted(L)]       # リスト内包表記でも使用可能
     [11, 12, 13, 14, 15, 16, 17, 18, 19]
     >>> L                               # 元のリストは変更されない
     [9,7,8,3,2,4,1,6,5]
     >>> sorted('Monty Python')          # 任意のイテラブルを入力にできる
     [' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']

     >>> # 辞書の内容をキーの値でソートして表示
     >>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
     >>> for k, v in sorted(colormap.iteritems()):
     ...     print k, v
     ...
     black 4
     blue 2
     green 3
     red 1
     yellow 5

  (Contributed by Raymond Hettinger.)

* Integer operations will no longer trigger an "OverflowWarning". The
  "OverflowWarning" warning will disappear in Python 2.5.

* インタプリタに新たに "-m" スイッチが加わりました。これは名前を取り、
  "sys.path" にある対応するモジュールを検索し、そしてそのモジュールを
  スクリプトとして実行します。たとえば Python プロファイラを "python
  -m profile" で起動することが出来るようになりました。 (Contributed by
  Nick Coghlan.)

* "eval(expr, globals, locals)" 関数と "execfile(filename, globals,
  locals)" 関数、 "exec" 文が *locals* パラメータに任意のマッピング型
  を受け取れるようになりました。以前は正規の Python 辞書である必要があ
  りました。 (Contributed by Raymond Hettinger.)

* The "zip()" built-in function and "itertools.izip()" now return an
  empty list if called with no arguments. Previously they raised a
  "TypeError" exception.  This makes them more suitable for use with
  variable length argument lists:

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

  (Contributed by Raymond Hettinger.)

* モジュールのインポート中に失敗しても、部分的に初期化されたモジュール
  オブジェクトが "sys.modules" に残らなくなりました。 不完全なモジュー
  ルオブジェクトが残ると、その後の同じモジュールのインポートが成功した
  ように見え、分かりにくいエラーにつながっていました。 (Tim Peters が
  修正しました。)

* "None" が定数になっています。 "None" という名前に新しい値を割り当て
  ようとするコードは、今では構文エラーになります。 (Contributed by
  Raymond Hettinger.)


最適化
------

* The inner loops for list and tuple slicing were optimized and now
  run about one-third faster.  The inner loops for dictionaries were
  also optimized, resulting in performance boosts for "keys()",
  "values()", "items()", "iterkeys()", "itervalues()", and
  "iteritems()". (Contributed by Raymond Hettinger.)

* リストを拡大・縮小する仕組みが、速度とメモリ効率の両面で最適化されま
  した。 コードの経路が効率化され、システムの "realloc()" の呼び出し頻
  度も減ったことで、リストへの追加や取り出しが高速になりました。 リス
  ト内包表記にも効果があります。 "list.extend()" も最適化され、元のリ
  ストを拡張する前に引数を一時的なリストへ変換しなくなりました。
  (Raymond Hettinger による貢献です。)

* "list()", "tuple()", "map()", "filter()", and "zip()" now run
  several times faster with non-sequence arguments that supply a
  "__len__()" method.  (Contributed by Raymond Hettinger.)

* The methods "list.__getitem__()", "dict.__getitem__()", and
  "dict.__contains__()" are now implemented as "method_descriptor"
  objects rather than "wrapper_descriptor" objects.  This form of
  access doubles their performance and makes them more suitable for
  use as arguments to functionals: "map(mydict.__getitem__, keylist)".
  (Contributed by Raymond Hettinger.)

* 新しいオペコード "LIST_APPEND" が追加され、リスト内包表記のバイトコ
  ードが単純になり、約 3 分の 1 高速になりました。 (Raymond Hettinger
  による貢献です。)

* バイトコードののぞき穴最適化が改善され、より短く高速なバイトコードを
  生成するようになりました。 注目すべきことに、生成されたバイトコード
  は読みやすくもなっています。 (Raymond Hettinger による改善です。)

* String concatenations in statements of the form "s = s + "abc"" and
  "s += "abc"" are now performed more efficiently in certain
  circumstances.  This optimization won't be present in other Python
  implementations such as Jython, so you shouldn't rely on it; using
  the "join()" method of strings is still recommended when you want to
  efficiently glue a large number of strings together. (Contributed by
  Armin Rigo.)

2.4 での最適化を総合すると、Python 2.4 は pystone ベンチマークを
Python 2.3 より約 5%、Python 2.2 より約 35% 高速に実行します。
(pystone は特に優れたベンチマークではありませんが、Python の性能指標と
して最も広く使われています。 実際のアプリケーションで Python 2.4 がも
たらす効果は、これより大きい場合も小さい場合もあります。)


新たなモジュール、改良されたモジュール、非推奨のモジュール
==========================================================

いつものように、Python の標準ライブラリには数多くの拡張とバグ修正があ
りました。ここでは最も注目に値する変更について、モジュールの辞書順に列
挙します。変更の完全なリストについてはソースツリーの "Misc/NEWS" を調
べるか、あるいは全ての詳細について CVS ログに目を通してみてください。

* "asyncore" モジュールの "loop()" 関数に *count* パラメーターが加わり
  、ポーリングループの実行回数を制限できるようになりました。 デフォル
  トでは、従来どおり無限に繰り返します。

* "base64" モジュールが、Base64、Base32、Base16 のエンコードとデコード
  について **RFC 3548** をより完全にサポートするようになりました。 大
  文字・小文字の同一視や代替文字集合を選択するオプションも含まれます。
  (Barry Warsaw による貢献です。)

* "bisect" モジュールが性能改善のために C 実装を使うようになりました。
  (Contributed by Dmitry Vasiliev.)

* Hye-Shik Chang によって保守されている東アジアのコーデックの
  CJKCodecs コレクションが Python 2.4 に統合されました。新たなエンコー
  ディングは:

* Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz

* Chinese (ROC): big5, cp950

* Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,
     iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext,
     iso-2022-jp-2004, shift-jis, shift-jisx0213, shift-jis-2004

* Korean: cp949, euc-kr, johab, iso-2022-kr

* ほか、新たなエンコーディングが追加されています: HP Roman8,
  ISO_8859-11, ISO_8859-16, PCTP-154, TIS-620.

* The UTF-8 and UTF-16 codecs now cope better with receiving partial
  input. Previously the "StreamReader" class would try to read more
  data, making it impossible to resume decoding from the stream.  The
  "read()" method will now return as much data as it can and future
  calls will resume decoding where previous ones left off.
  (Implemented by Walter Dörwald.)

* There is a new "collections" module for  various specialized
  collection datatypes.  Currently it contains just one type, "deque",
  a double-ended queue that supports efficiently adding and removing
  elements from either end:

     >>> from collections import deque
     >>> d = deque('ghi')        # 3 つの要素を持つ新しい deque を作る
     >>> d.append('j')           # 右側に新しい要素を追加
     >>> d.appendleft('f')       # 左側に新しい要素を追加
     >>> d                       # deque の表現を表示
     deque(['f', 'g', 'h', 'i', 'j'])
     >>> d.pop()                 # 右端の要素を取り除いて返す
     'j'
     >>> d.popleft()             # 左端の要素を取り除いて返す
     'f'
     >>> list(d)                 # deque の内容をリストにする
     ['g', 'h', 'i']
     >>> 'h' in d                # deque を検索
     True

  Several modules, such as the "queue" and "threading" modules, now
  take advantage of "collections.deque" for improved performance.
  (Contributed by Raymond Hettinger.)

* "ConfigParser" のクラスが少し拡張されました。 "read()" メソッドは正
  常に解析できたファイルのリストを返すようになり、"set()" メソッドは
  *value* 引数が文字列でなければ "TypeError" を送出するようになりまし
  た。 (John Belmonte と David Goodger による貢献です。)

* The "curses" module now supports the ncurses extension
  "use_default_colors()".  On platforms where the terminal supports
  transparency, this makes it possible to use a transparent
  background. (Contributed by Jörg Lehmann.)

* The "difflib" module now includes an "HtmlDiff" class that creates
  an HTML table showing a side by side comparison of two versions of a
  text. (Contributed by Dan Gass.)

* The "email" package was updated to version 3.0,  which dropped
  various deprecated APIs and removes support for Python versions
  earlier than 2.3.  The 3.0 version of the package uses a new
  incremental parser for MIME messages, available in the
  "email.FeedParser" module.  The new parser doesn't require reading
  the entire message into memory, and doesn't raise exceptions if a
  message is malformed; instead it records any problems in the
  "defect" attribute of the message.  (Developed by Anthony Baxter,
  Barry Warsaw, Thomas Wouters, and others.)

* The "heapq" module has been converted to C.  The resulting tenfold
  improvement in speed makes the module suitable for handling high
  volumes of data.  In addition, the module has two new functions
  "nlargest()" and "nsmallest()" that use heaps to find the N largest
  or smallest values in a dataset without the expense of a full sort.
  (Contributed by Raymond Hettinger.)

* The "httplib" module now contains constants for HTTP status codes
  defined in various HTTP-related RFC documents.  Constants have names
  such as "OK", "CREATED", "CONTINUE", and "MOVED_PERMANENTLY"; use
  pydoc to get a full list.  (Contributed by Andrew Eland.)

* The "imaplib" module now supports IMAP's THREAD command (contributed
  by Yves Dionne) and new "deleteacl()" and "myrights()" methods
  (contributed by Arnaud Mazin).

* The "itertools" module gained a "groupby(iterable[, *func*])"
  function. *iterable* is something that can be iterated over to
  return a stream of elements, and the optional *func* parameter is a
  function that takes an element and returns a key value; if omitted,
  the key is simply the element itself.  "groupby()" then groups the
  elements into subsequences which have matching values of the key,
  and returns a series of 2-tuples containing the key value and an
  iterator over the subsequence.

  Here's an example to make this clearer.  The *key* function simply
  returns whether a number is even or odd, so the result of
  "groupby()" is to return consecutive runs of odd or even numbers.

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

  "groupby()" is typically used with sorted input.  The logic for
  "groupby()" is similar to the Unix "uniq" filter which makes it
  handy for eliminating, counting, or identifying duplicate elements:

     >>> word = 'abracadabra'
     >>> letters = sorted(word)   # 文字列をソートされた文字のリストにする
     >>> letters
     ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
     >>> for k, g in itertools.groupby(letters):
     ...    print k, list(g)
     ...
     a ['a', 'a', 'a', 'a', 'a']
     b ['b', 'b']
     c ['c']
     d ['d']
     r ['r', 'r']
     >>> # 重複しない文字を列挙
     >>> [k for k, g in groupby(letters)]
     ['a', 'b', 'c', 'd', 'r']
     >>> # 文字の出現回数を数える
     >>> [(k, len(list(g))) for k, g in groupby(letters)]
     [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]

  (Contributed by Hye-Shik Chang.)

* "itertools" には "tee(iterator, N)" という新たな関数も追加されていま
  す。これは *iterator* の、独立した *N* 個の複製イテレータを返します
  。 *N* は省略されればデフォルトは 2 です。:

     >>> L = [1,2,3]
     >>> i1, i2 = itertools.tee(L)
     >>> i1,i2
     (<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
     >>> list(i1)               # 最初のイテレータを最後まで進める
     [1, 2, 3]
     >>> list(i2)               # 2 つ目のイテレータを最後まで進める
     [1, 2, 3]

  Note that "tee()" has to keep copies of the values returned by the
  iterator; in the worst case, it may need to keep all of them.   This
  should therefore be used carefully if the leading iterator can run
  far ahead of the trailing iterator in a long stream of inputs. If
  the separation is large, then you might as well use  "list()"
  instead.  When the iterators track closely with one another, "tee()"
  is ideal.  Possible applications include bookmarking, windowing, or
  lookahead iterators. (Contributed by Raymond Hettinger.)

* A number of functions were added to the "locale"  module, such as
  "bind_textdomain_codeset()" to specify a particular encoding and a
  family of "l*gettext()" functions that return messages in the chosen
  encoding. (Contributed by Gustavo Niemeyer.)

* Some keyword arguments were added to the "logging" package's
  "basicConfig()" function to simplify log configuration.  The default
  behavior is to log messages to standard error, but various keyword
  arguments can be specified to log to a particular file, change the
  logging format, or set the logging level. For example:

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

  Other additions to the "logging" package include a "log(level, msg)"
  convenience method, as well as a "TimedRotatingFileHandler" class
  that rotates its log files at a timed interval.  The module already
  had "RotatingFileHandler", which rotated logs once the file exceeded
  a certain size.  Both classes derive from a new
  "BaseRotatingHandler" class that can be used to implement other
  rotating handlers.

  (Changes implemented by Vinay Sajip.)

* "marshal" モジュールが、データ構造のアンパックで内部化した文字列を共
  有するようになりました。これはある種の pickle 文字列のサイズを切り詰
  めるでしょうが、主要な効能は ".pyc" ファイルが顕著に小さくなることで
  す。(Contributed by Martin von Löwis.)

* The "nntplib" module's "NNTP" class gained "description()" and
  "descriptions()" methods to retrieve newsgroup descriptions for a
  single group or for a range of groups. (Contributed by Jürgen A.
  Erhard.)

* "operator" モジュールに 2 つの関数 "attrgetter(attr)" と
  "itemgetter(index)" が追加されています。両関数ともに、単一引数を取っ
  てそれに対応する属性かアイテムを返す呼び出し可能オブジェクトを返しま
  す。これら呼び出し可能オブジェクトは "map()" や "sorted()" とともに
  使う際の優れたデータ抽出器になります。例えば:

     >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
     >>> map(operator.itemgetter(0), L)
     ['c', 'd', 'a', 'b']
     >>> map(operator.itemgetter(1), L)
     [2, 1, 4, 3]
     >>> sorted(L, key=operator.itemgetter(1)) # タプルの 2 番目の要素でリストをソート
     [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

  (Contributed by Raymond Hettinger.)

* "optparse" モジュールが色々更新されました。モジュールはメッセージを
  "gettext.gettext()" を通して Optik のヘルプとエラーメッセージを国際
  化するのを可能にしています。オプションのヘルプメッセージは文字列
  "'%default'" を含めることが出来るようになっており、これはオプション
  のデフォルト値に置換されます。(Contributed by Greg Ward.)

* 長期的には、将来の Python リリースで "rfc822" モジュールを非推奨にし
  、"email" パッケージへ置き換える計画です。 そのため、
  "email.Utils.formatdate" 関数が "rfc822.formatdate()" の代わりに使え
  るよう変更されました。 新しい電子メール処理のコードは、この点を考慮
  して書くとよいでしょう。 (Anthony Baxter による変更です。)

* "os" モジュールに "urandom(n)" が追加されました。これは *n* バイトの
  乱数データを含む文字列を返します。この関数はプラットフォーム固有の乱
  数発生源にアクセスします。例えば Linux での "/dev/urandom" や
  Windows での CryptoAPI です。 (Contributed by Trevor Perrin.)

* もう一つの新規関数 "os.path.lexists(path)" は *path* によって指定さ
  れたファイルがそれがシンボリックリンクかどうかによらず、存在している
  場合に真を返します。これは、既存の "os.path.exists(path)" 関数が
  *path* がシンボリックリンクでその指し先が存在しない場合に偽を返すの
  とは異なります。 (Contributed by Beni Cherniavsky.)

* A new "getsid()" function was added to the "posix" module that
  underlies the "os" module. (Contributed by J. Raynor.)

* "poplib" モジュールが  POP over SSL をサポートするようになりました.
  (Contributed by Hector Urtubia.)

* "profile" モジュールが C 拡張の関数をプロファイル出来るようになりま
  した。 (Contributed by Nick Bastin.)

* The "random" module has a new method called "getrandbits(N)" that
  returns a long integer *N* bits in length.  The existing
  "randrange()" method now uses "getrandbits()" where appropriate,
  making generation of arbitrarily large random numbers more
  efficient.  (Contributed by Raymond Hettinger.)

* "re" モジュールの正規表現言語が拡張されて、単純な条件式
  "(?(group)A|B)" を書けるようになっています。 *group* は数値グループ
  ID か正規表現内で "(?P<group>...)" で定義したグループ名のどちらかで
  す。指定したグループが合致した場合は、正規表現パターン *A* が文字列
  に対してテストされ、そうでなければパターン *B* が代わりに試されます
  。(Contributed by Gustavo Niemeyer.)

* "re" モジュールはもう再帰をすることはありません。Gustavo Niemeyer に
  よる膨大な量の仕事のおかげです。再帰する正規表現エンジンでは、ある種
  のパターンでは大量の C スタック空間を消費し、スタックのオーバーフロ
  ーを起こすことがありました。例えば表現 "(a|b)+" が文字 "a" から成る
  3 万バイトの文字列に対してマッチすると、一文字ごとに一つのスタックフ
  レームを消費していました。Python 2.3 ではスタックオーバーフローのチ
  ェックを試みて "RuntimeError" を投げようとしましたが、ある種のパター
  ンではチェックをすり抜けてしまって、運が悪いとセグメンテーション違反
  を起こしていました。Python 2.4 の正規表現エンジンではこのパターンと
  問題を起こすことなくマッチ出来ます。

* The "signal" module now performs tighter error-checking on the
  parameters to the "signal.signal()" function.  For example, you
  can't set a handler on the "SIGKILL" signal; previous versions of
  Python would quietly accept this, but 2.4 will raise a
  "RuntimeError" exception.

* Two new functions were added to the "socket" module. "socketpair()"
  returns a pair of connected sockets and "getservbyport(port)" looks
  up the service name for a given port number. (Contributed by Dave
  Cole and Barry Warsaw.)

* The "sys.exitfunc()" function has been deprecated.  Code should be
  using the existing "atexit" module, which correctly handles calling
  multiple exit functions.  Eventually "sys.exitfunc()" will become a
  purely internal interface, accessed only by "atexit".

* "tarfile" モジュールがデフォルトで GNU フォーマットを生成するように
  なっています。 (Contributed by Lars Gustäbel.)

* The "threading" module now has an elegantly simple way to support
  thread-local data.  The module contains a "local" class whose
  attribute values are local to different threads.

     import threading

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

  Other threads can assign and retrieve their own values for the
  "number" and "url" attributes.  You can subclass "local" to
  initialize attributes or to add methods. (Contributed by Jim
  Fulton.)

* "timeit" モジュールはループを計測中は周期的なガーベージコレクション
  を自動で無効化するようになりました。この変更により、繰り返しの計測の
  比較がやりやすくなります。 (Contributed by Raymond Hettinger.)

* "weakref" モジュールがサポートするオブジェクトが非常に幅広くなりまし
  た。これには Python 関数、クラスインスタンス, set, frozenset, deque,
  array と正規表現パターンオブジェクトが含まれます。(Contributed by
  Raymond Hettinger.)

* "xmlrpclib" モジュールが、1 回の HTTP 操作で複数の XML-RPC 呼び出し
  を送る multi-call 拡張に対応しました。 (Brian Quinlan による貢献です
  。)

* The "mpz", "rotor", and "xreadlines" modules have been removed.


cookielib
---------

"cookielib" ライブラリは、"Cookie" モジュールのサーバー側のクッキー処
理に対応する、クライアント側の HTTP クッキー処理をサポートします。 ク
ッキーはクッキージャーに格納されます。 ライブラリは、Web サーバーから
受け取ったクッキーをクッキージャーへ自動的に保存し、サーバーへの接続時
にそこから取り出します。 Web ブラウザーと同じく、クッキーを受け入れる
かどうかはポリシーオブジェクトが制御します。

セッションを跨いでクッキーを記憶するために、2 つのクッキー瓶実装が提供
されています。一つは Netscape フォーマットでクッキーを記憶するのでアプ
リケーションは Mozilla か Lynx のクッキーファイルを使え、もう一つは
Perl の libwww ライブラリと同じフォーマットでクッキーを記憶します。

"urllib2" has been changed to interact with "cookielib":
"HTTPCookieProcessor" manages a cookie jar that is used when accessing
URLs.

このモジュールは John J. Lee により寄稿されました。


doctest
-------

Edward Loper と Tim Peters のおかげにより、 "doctest" モジュールに注目
に値するリファクタリングが入りました。テストはこれまで通り単純に
"doctest.testmod()" を実行するすることで行えますが、リファクタリングは
モジュールの操作をカスタマイズする色々な手段を提供してくれます。

The new "DocTestFinder" class extracts the tests from a given object's
docstrings:

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

   finder = doctest.DocTestFinder()

   # DocTest インスタンスのリストを取得
   tests = finder.find(f)

The new "DocTestRunner" class then runs individual tests and can
produce a summary of the results:

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

   runner.summarize(verbose=1)

上の例はこのような出力を生成します:

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

"DocTestRunner" uses an instance of the "OutputChecker" class to
compare the expected output with the actual output.  This class takes
a number of different flags that customize its behaviour; ambitious
users can also write a completely new subclass of "OutputChecker".

デフォルトの出力チェッカーは多くのお手軽機能を持っています。例えば
"doctest.ELLIPSIS" オプションフラグは、出力の期待値内での省略記号
("...") と任意文字列を一致するとみなし、瑣末な部分が変化するような出力
に簡単に適合するように出来ます:

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

もう一つの特殊文字列 "<BLANKLINE>" は空行に合致します:

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

もう一つの新機能は出力の diff スタイル出力で、オプションフラグに
"doctest.REPORT_UDIFF" (unified diffs), "doctest.REPORT_CDIFF"
(context diffs), "doctest.REPORT_NDIFF" (delta-style) を指定することで
利用出来ます。例えば以下があるとして:

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

上の関数のテストを "doctest.REPORT_UDIFF" を指定して実行すると、次の出
力が得られます。

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


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

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

* 拡張関数からの戻り値として一般的に使うための 3 つの便利なマクロが追
  加されています: "Py_RETURN_NONE", "Py_RETURN_TRUE",
  "Py_RETURN_FALSE" (Contributed by Brett Cannon.)

* もう一つの新しいマクロ "Py_CLEAR" は、*obj* の参照カウントを減らし、
  *obj* をヌルポインターに設定します。 (Jim Fulton による貢献です。)

* 新規関数 "PyTuple_Pack(N, obj1, obj2, ..., objN)" は Python オブジェ
  クトの可変長引数リストからタプルを構築します。 (Contributed by
  Raymond Hettinger.)

* 新規関数 "PyDict_Contains(d, k)" は、処理内で起こる例外のマスキング
  なしでの高速なルックアップを実装しています。 (Contributed by Raymond
  Hettinger.)

* The "Py_IS_NAN" macro returns 1 if its float or double argument *X*
  is a NaN.   (Contributed by Tim Peters.)

* C コードでは、新しい "PyEval_ThreadsInitialized()" 関数でスレッド操
  作が行われたかどうかを調べ、不要なロックを避けられます。 この関数が
  偽を返す場合、ロック操作は不要です。 (Nick Coghlan による貢献です。)

* 新規関数 "PyArg_VaParseTupleAndKeywords()" は
  "PyArg_ParseTupleAndKeywords()" と同じですが、たくさんの引数の代わり
  に "va_list" を取ることだけが違います。(Contributed by Greg
  Chapman.)

* A new method flag, "METH_COEXIST", allows a function defined in
  slots to co-exist with a "PyCFunction" having the same name.  This
  can halve the access time for a method such as "set.__contains__()".
  (Contributed by Raymond Hettinger.)

* Python コアの開発を支援するため、インタープリタ自体の追加のプロファ
  イリング機能を有効にしてビルドできるようになりました。 **configure**
  スクリプトに "--enable-profiling" を指定すると **gprof** でインター
  プリタをプロファイルでき、"--with-tsc" を指定すると Pentium のタイム
  スタンプカウンターレジスターを使ったプロファイリングが有効になります
  。 "--with-tsc" という名前は少し不正確です。 この機能は PowerPC でも
  動作しますが、そのアーキテクチャでは該当するレジスターを「TSC レジス
  ター」とは呼ばないためです。 (Jeremy Hylton による貢献です。)

* The "tracebackobject" type has been renamed to "PyTracebackObject".


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

* Windows ポートは MSVC++ 6 と 7.1 でビルド出来ます。 (Contributed by
  Martin von Löwis.)


Python 2.4 への移植
===================

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

* 大き過ぎる値を持つ左シフトと 16 進/ 8 進定数が "FutureWarning" を引
  き起こした上で 32 ビットまたは 64 ビットに制限される、という振る舞い
  はもうしません。代わりに長整数を返します。

* Integer operations will no longer trigger an "OverflowWarning". The
  "OverflowWarning" warning will disappear in Python 2.5.

* The "zip()" built-in function and "itertools.izip()" now return an
  empty list instead of raising a "TypeError" exception if called with
  no arguments.

* You can no longer compare the "date" and "datetime" instances
  provided by the "datetime" module.  Two  instances of different
  classes will now always be unequal, and  relative comparisons ("<",
  ">") will raise a "TypeError".

* "dircache.listdir()" は、空のリストを返す代わりに、例外を呼び出し側
  へ伝えるようになりました。

* "LexicalHandler.startDTD" used to receive the public and system IDs
  in the wrong order.  This has been corrected; applications relying
  on the wrong order need to be fixed.

* "fcntl.ioctl()" は *mutate_flag* 引数が省略されて問題に関係がある場
  合は警告を出します。

* "tarfile" モジュールがデフォルトで GNU フォーマットを生成するように
  なっています。

* モジュールのインポート中に失敗しても、部分的に初期化されたモジュール
  オブジェクトが "sys.modules" に残らなくなりました。

* "None" が定数になっています。 "None" という名前に新しい値を割り当て
  ようとするコードは、今では構文エラーになります。

* The "signal.signal()" function now raises a "RuntimeError" exception
  for certain illegal values; previously these errors would pass
  silently.  For example, you can no longer set a handler on the
  "SIGKILL" signal.


謝辞
====

著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の
人々に感謝します: Koray Can, Hye-Shik Chang, Michael Dyck, Raymond
Hettinger, Brian Hurt, Hamish Lawson, Fredrik Lundh, Sean
Reifschneider, Sadruddin Rejeb.
