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')              # form a set from a string
   >>> 'z' in a                            # fast membership testing
   False
   >>> a                                   # unique letters in a
   set(['a', 'r', 'b', 'c', 'd'])
   >>> ''.join(a)                          # convert back into a string
   'arbcd'

   >>> b = set('alacazam')                 # form a second set
   >>> a - b                               # letters in a but not in b
   set(['r', 'd', 'b'])
   >>> a | b                               # letters in either a or b
   set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
   >>> a & b                               # letters in both a and b
   set(['a', 'c'])
   >>> a ^ b                               # letters in a or b but not both
   set(['r', 'd', 'b', 'm', 'z', 'l'])

   >>> a.add('z')                          # add a new element
   >>> a.update('wxy')                     # add multiple new elements
   >>> a
   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
   >>> a.remove('x')                       # take one element out
   >>> 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: ジェネレータ式
=======================

The iterator feature introduced in Python 2.2 and the "itertools"
module make it easier to write programs that loop through large data
sets without having the entire data set in memory at one time.  List
comprehensions don't fit into this picture very well because they
produce a Python list object containing all of the items.  This
unavoidably pulls all of the objects into memory, which can be a
problem if your data set is very large.  When trying to write a
functionally styled program, it would be natural to write something
like:

   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)   # Rebind name to wrapped-up class method

メソッドがとても長かったりすると、関数のボディの後ろの "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)))

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

A small related change makes the "func_name" attribute of functions
writable.  This attribute is used to display function names in
tracebacks, so decorators should change the name of any new function
that's constructed and returned.

参考:

  **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 モジュール
=====================================

The standard library provides a number of ways to execute a
subprocess, offering different features and different levels of
complexity. "os.system(command)" is easy to use, but slow (it runs a
shell process which executes the command) and dangerous (you have to
be careful about escaping the shell's metacharacters).  The "popen2"
module offers classes that can capture standard output and standard
error from the subprocess, but the naming is confusing.  The
"subprocess" module cleans  this up, providing a unified interface
that offers all the features you might need.

Instead of "popen2"'s collection of classes, "subprocess" contains a
single class called "subprocess.Popen"  whose constructor supports a
number of different keyword arguments.

   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:
       # Success
       ...
   else:
       # dpkg returned an error
       ...

コマンドはシェルを使うことなく呼び出されます。もしシェルを本当に使いた
いのであればキーワード引数として "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.

Not setting the numeric locale caused trouble for extensions that used
third-party C libraries, however, because they wouldn't have the
correct locale set. The motivating example was GTK+, whose user
interface widgets weren't displaying numbers in the current locale.

この 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)" converts a double
  to an ASCII string.

The code for these functions came from the GLib library (https
://developer-old.gnome.org/glib/2.26/), whose developers kindly
relicensed the relevant functions and donated them to the Python
Software Foundation.  The "locale" module  can now change the numeric
locale, letting extensions such as GTK+  produce the correct results.

参考:

  **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()                 # Case-sensitive sort
     >>> L
     ['A', 'D', 'b', 'c']
     >>> # Using 'key' parameter to sort list
     >>> L.sort(key=lambda x: x.lower())
     >>> L
     ['A', 'b', 'c', 'D']
     >>> # Old-fashioned way
     >>> 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)]       # usable in a list comprehension
     [11, 12, 13, 14, 15, 16, 17, 18, 19]
     >>> L                               # original is left unchanged
     [9,7,8,3,2,4,1,6,5]
     >>> sorted('Monty Python')          # any iterable may be an input
     [' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']

     >>> # List the contents of a dict sorted by key values
     >>> 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.)

* Encountering a failure while importing a module no longer leaves a
  partially initialized module object in "sys.modules".  The
  incomplete module object left behind would fool further imports of
  the same module into succeeding, leading to confusing errors.
  (Fixed by 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.)

* The machinery for growing and shrinking lists was optimized for
  speed and for space efficiency.  Appending and popping from lists
  now runs faster due to more efficient code paths and less frequent
  use of the underlying system "realloc()".  List comprehensions also
  benefit.   "list.extend()" was also optimized and no longer converts
  its argument into a temporary list before extending the base list.
  (Contributed by 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.)

* Added a new opcode, "LIST_APPEND", that simplifies the generated
  bytecode for list comprehensions and speeds them up by about a
  third.  (Contributed by Raymond Hettinger.)

* The peephole bytecode optimizer has been improved to  produce
  shorter, faster bytecode; remarkably, the resulting bytecode is
  more readable.  (Enhanced by 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.)

The net result of the 2.4 optimizations is that Python 2.4 runs the
pystone benchmark around 5% faster than Python 2.3 and 35% faster than
Python 2.2. (pystone is not a particularly good benchmark, but it's
the most commonly used measurement of Python's performance.  Your own
applications may show greater or smaller benefits from Python 2.4.)


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

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

* The "asyncore" module's "loop()" function now has a *count*
  parameter that lets you perform a limited number of passes through
  the polling loop.  The default is still to loop forever.

* The "base64" module now has more complete **RFC 3548** support for
  Base64, Base32, and Base16 encoding and decoding, including optional
  case folding and optional alternative alphabets. (Contributed by
  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')        # make a new deque with three items
     >>> d.append('j')           # add a new entry to the right side
     >>> d.appendleft('f')       # add a new entry to the left side
     >>> d                       # show the representation of the deque
     deque(['f', 'g', 'h', 'i', 'j'])
     >>> d.pop()                 # return and remove the rightmost item
     'j'
     >>> d.popleft()             # return and remove the leftmost item
     'f'
     >>> list(d)                 # list the contents of the deque
     ['g', 'h', 'i']
     >>> 'h' in d                # search the deque
     True

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

* The "ConfigParser" classes have been enhanced slightly. The "read()"
  method now returns a list of the files that were successfully
  parsed, and the "set()" method raises "TypeError" if passed a
  *value* argument that isn't a string.   (Contributed by John
  Belmonte and 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)   # Turn string into a sorted list of letters
     >>> 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']
     >>> # List unique letters
     >>> [k for k, g in groupby(letters)]
     ['a', 'b', 'c', 'd', 'r']
     >>> # Count letter occurrences
     >>> [(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)               # Run the first iterator to exhaustion
     [1, 2, 3]
     >>> list(i2)               # Run the second iterator to exhaustion
     [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)) # Sort list by second tuple item
     [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

  (Contributed by Raymond Hettinger.)

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

* The long-term plan is to deprecate the "rfc822" module in some
  future Python release in favor of the "email" package. To this end,
  the "email.Utils.formatdate" function has been changed to make it
  usable as a replacement for "rfc822.formatdate()".  You may want to
  write new e-mail processing code with this in mind.  (Change
  implemented by 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.)

* The "xmlrpclib" module now supports a multi-call extension for
  transmitting multiple XML-RPC calls in a single HTTP operation.
  (Contributed by Brian Quinlan.)

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


cookielib
---------

The "cookielib" library supports client-side handling for HTTP
cookies, mirroring the "Cookie" module's server-side cookie support.
Cookies are stored in cookie jars; the library transparently stores
cookies offered by the web server in the cookie jar, and fetches the
cookie from the jar when connecting to the server. As in web browsers,
policy objects control whether cookies are accepted or not.

セッションを跨いでクッキーを記憶するために、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()

   # Get list of DocTest instances
   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

Running the above function's tests with "doctest.REPORT_UDIFF"
specified, you get the following output:

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

* Another new macro, "Py_CLEAR",  decreases the reference count of
  *obj* and sets *obj* to the null pointer.  (Contributed by 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 code can avoid unnecessary locking by using the new
  "PyEval_ThreadsInitialized()" function to tell  if any thread
  operations have been performed.  If this function  returns false, no
  lock operations are needed. (Contributed by 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 can now be built with additional profiling for the
  interpreter itself, intended as an aid to people developing the
  Python core.  Providing "--enable-profiling" to the **configure**
  script will let you profile the interpreter with **gprof**, and
  providing the "--with-tsc" switch enables profiling using the
  Pentium's Time-Stamp-Counter register.  Note that the "--with-tsc"
  switch is slightly misnamed, because the profiling feature also
  works on the PowerPC platform, though that processor architecture
  doesn't call that register "the TSC register".  (Contributed by
  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()" now passes exceptions to the caller instead of
  returning empty lists.

* "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 フォーマットを生成するように
  なっています。

* Encountering a failure while importing a module no longer leaves a
  partially initialized module object in "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.
