What's New In Python 3.5
************************

エディタ:
   Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov
   <yury@magic.io>

この記事では 3.4 と比較した Python 3.5 の新機能を解説します。 Python
3.5 は2015年9月13日にリリースされました。 全詳細については 変更履歴 を
ご覧ください。

参考: **PEP 478** - Python 3.5 リリーススケジュール


概要 -- リリースハイライト
==========================

新たな文法機能:

* PEP 492、コルーチン、async 構文と await 構文。

* PEP 465、新たな行列乗算演算子 "a @ b"。

* PEP 448、追加可能なアンパックへの一般化。

新たなライブラリモジュール:

* "typing": PEP 484 -- 型ヒント。

* "zipapp": PEP 441 Python ZIP アプリケーションのサポートの改善。

新たな組み込み機能:

* "bytes % args", "bytearray % args": PEP 461 -- bytes と bytearray に
  "%" 書式化を追加。

* 新たな "bytes.hex()", "bytearray.hex()" "memoryview.hex()" メソッド
  。 (Contributed by Arnon Yaari in bpo-9951.)

* "memoryview" クラスが、(複数次元の場合を含んだ) タプルの添字をサポー
  トするようになりました。 (bpo-23632 におけるAntoine Pitrouによる貢献
  です。)

* ジェネレータに "gi_yieldfrom" 属性が新しく追加され、これは "yield
  from" 式で反復処理されるオブジェクトを返します。 (Contributed by
  Benno Leslie and Yury Selivanov in bpo-24450.)

* 新たな例外 "RecursionError" が最長再帰深度に到達した際に送出されるよ
  うになりました。   (Contributed by Georg Brandl in bpo-19235.)

CPython の実装の改善:

* "LC_TYPE" ロケールが POSIX ロケール ("C" ロケール) のとき、
  "sys.stdin" および "sys.stdout" は "strict" エラーハンドラではなく
  "surrogateescape" を使うようになりました。 (Contributed by Victor
  Stinner in bpo-19977.)

* ".pyo" ファイルは使われなくなり、".pyc" ファイル名に最適化レベルが明
  示される、より柔軟な仕組みに置き換えられました。(PEP 488 の概要 を参
  照してください。)

* 組み込みおよび拡張モジュールが多段階で初期化されるようになりました。
  これは Python モジュールのロード方法と同じです。 (PEP 489 の概要 を
  参照してください。)

標準ライブラリーの顕著な改善

* "collections.OrderedDict" が C で実装されました。 これにより 4 倍か
  ら 100 倍高速になりました。

* "ssl" モジュールに メモリ BIO サポート が追加されました。これにより
  SSL プロトコルの処理と ネットワーク IO が分離されました。

* 新たな関数 "os.scandir()" はディレクトリー走査の 改良され非常に速い
  方法 を提供します。

* "functools.lru_cache()" の大部分が C で再実装 され、性能が大幅に向上
  しました。

* 新たな関数 "subprocess.run()" は サブプロセスを実行する合理的な方法
  を提供します。

* "traceback" モジュールは性能と開発者の利便性が向上し、大いに 強化さ
  れ ました。

セキュリティの改善:

* SSLv3 が標準ライブラリ全体を通じて無効化されました。ただし
  "ssl.SSLContext" を手動でインスタンス化することによってなら今でも有
  効には出来ます。  (詳細に関しては bpo-22638 を参照してください。この
  変更は CPython 3.4 と 2.7 にもバックポートされました。)

* 潜在的なインジェクション攻撃からの防御のために、HTTP クッキーの解析
  がより厳密に行われるようになりました。 (Contributed by Antoine
  Pitrou in bpo-22796.)

Windows の改善:

* Windows のインストーラが新しくなり古い MSI を置き換えました。さらに
  詳しい情報は Windows で Python を使う をご覧ください。

* Windows のビルドに Microsoft Visual C++ 14.0 を使うようになっていま
  す。拡張モジュールも同じものを使うべきです。

以降は、たくさんのほかの小さな改善、CPython での最適化、非推奨リスト、
潜在的な移植性問題を含む、ユーザ向けの変更の包括的なリストになっていま
す。


新しい機能
==========


PEP 492 - コルーチン、 async と await 構文
------------------------------------------

**PEP 492** で *待機可能オブジェクト*、*コルーチン関数*、*非同期イテレ
ーション*、*非同期コンテキストマネージャ* が追加され、Python における
非同期プログラミングを大幅に向上しました。

コルーチン関数は新たな構文 "async def" を用いて定義されます:

   >>> async def coro():
   ...     return 'spam'

コルーチン関数内で、新たな "await" 式を用いることで結果が利用可能にな
るまでコルーチンの実行を停止することが出来ます。"__await__()" メソッド
を定義して *awaitable* プロトコルを実装する限り、あらゆるオブジェクト
は *待機可能* です。

PEP 492 により "async for" 文も追加されました。非同期イテラブルを反復
するのに便利です。

新たな構文を用いた初歩的な HTTP クライアントの例です:

   import asyncio

   async def http_get(domain):
       reader, writer = await asyncio.open_connection(domain, 80)

       writer.write(b'\r\n'.join([
           b'GET / HTTP/1.1',
           b'Host: %b' % domain.encode('latin-1'),
           b'Connection: close',
           b'', b''
       ]))

       async for line in reader:
           print('>>>', line)

       writer.close()

   loop = asyncio.get_event_loop()
   try:
       loop.run_until_complete(http_get('example.com'))
   finally:
       loop.close()

非同期イテレーションと同様に、非同期なコンテキストマネージャの新たな構
文があります。以下のスクリプト:

   import asyncio

   async def coro(name, lock):
       print('coro {}: waiting for lock'.format(name))
       async with lock:
           print('coro {}: holding the lock'.format(name))
           await asyncio.sleep(1)
           print('coro {}: releasing the lock'.format(name))

   loop = asyncio.get_event_loop()
   lock = asyncio.Lock()
   coros = asyncio.gather(coro(1, lock), coro(2, lock))
   try:
       loop.run_until_complete(coros)
   finally:
       loop.close()

の出力は:

   coro 2: waiting for lock
   coro 2: holding the lock
   coro 1: waiting for lock
   coro 2: releasing the lock
   coro 1: holding the lock
   coro 1: releasing the lock

"async for" と "async with" は両方とも、 "async def" で宣言されたコル
ーチン関数内でのみ使えることに注意してください。

コルーチン関数は asyncio loop のような適したイベントループ内で実行させ
るためのものです。

注釈:

  バージョン 3.5.2 で変更: CPython 3.5.2 以降では、 "__aiter__" は *非
  同期イテレータ* を直接返せます。 *awaitable* オブジェクトを返すと
  "PendingDeprecationWarning" が送出されます。より詳細なことはドキュメ
  ントの 非同期イテレータ (Asynchronous Iterator) 節を参照してください
  。

参考:

  **PEP 492** -- コルーチン、 async 構文と await 構文
     PEP written and implemented by Yury Selivanov.


PEP 465 - 行列の乗算専用の中置演算子
------------------------------------

**PEP 465** により "@" 行列の乗算のための中置演算子が追加されました。
現在のところ Python の型はこの演算子を実装していませんが、
"__matmul__()"、"__rmatmul__()"、"__imatmul__()" (それぞれ通常の乗算、
反射した乗算、インプレースの乗算) を定義することで実装することが出来ま
す。 これらのメソッドのセマンティクスは他の中置算術演算子のものと類似
です。

行列の乗算は数学、科学、工学の多くの分野では非常に一般的です。 "@" の
追加によりコードをより綺麗に書くことが出来ます:

   S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

これはたとえば NumPy を使っても、以下のように書く必要がありました:

   S = dot((dot(H, beta) - r).T,
           dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

NumPy 1.10 はこの新たな演算子をサポートしています:

   >>> import numpy

   >>> x = numpy.ones(3)
   >>> x
   array([ 1., 1., 1.])

   >>> m = numpy.eye(3)
   >>> m
   array([[ 1., 0., 0.],
          [ 0., 1., 0.],
          [ 0., 0., 1.]])

   >>> x @ m
   array([ 1., 1., 1.])

参考:

  **PEP 465** -- 行列乗算専用の中置演算子
     PEP written by Nathaniel J. Smith; implemented by Benjamin
     Peterson.


PEP 448 - 追加可能なアンパックへの一般化
----------------------------------------

**PEP 448** によって、 "*" イテラブルアンパック演算子と "**" 辞書アン
パック演算子の利用方法が拡張されました。 関数呼び出し で任意の数のアン
パックで使えるようになりました:

   >>> print(*[1], *[2], 3, *[4, 5])
   1 2 3 4 5

   >>> def fn(a, b, c, d):
   ...     print(a, b, c, d)
   ...

   >>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
   1 2 3 4

同様に、タプル、リスト、集合、辞書表現でも複数のアンパックが使えます (
式のリスト および 辞書表示 を参照してください):

   >>> *range(4), 4
   (0, 1, 2, 3, 4)

   >>> [*range(4), 4]
   [0, 1, 2, 3, 4]

   >>> {*range(4), 4, *(5, 6, 7)}
   {0, 1, 2, 3, 4, 5, 6, 7}

   >>> {'x': 1, **{'y': 2}}
   {'x': 1, 'y': 2}

参考:

  **PEP 448** -- 追加可能なアンパックへの一般化
     PEP written by Joshua Landau; implemented by Neil Girdhar, Thomas
     Wouters, and Joshua Landau.


PEP 461 - bytes および bytearray のパーセント書式化サポート
-----------------------------------------------------------

**PEP 461** によって、 "bytes" と "bytearray" に "%" 補間演算子 のサポ
ートが追加されます。

補間は通常は文字列演算だと考えられていますが、 "bytes" や "bytearrays"
上の補間が意味を持つ場合もあって、この機能が無いと余計な作業が必要にな
りコードの全体の可読性が損なわれます。 この問題は特にワイヤフォーマッ
トプロトコルの取り扱いにおいて重要で、バイナリとASCII互換のテキストが
入り交じったものがよく出てきます。

例:

   >>> b'Hello %b!' % b'World'
   b'Hello World!'

   >>> b'x=%i y=%f' % (1, 2.5)
   b'x=1 y=2.500000'

Unicode に対して "%b" は使えませんが、 "%a" であれば使えます
("repr(obj).encode('ascii', 'backslashreplace')" と同等):

   >>> b'Hello %b!' % 'World'
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'

   >>> b'price: %a' % '10€'
   b"price: '10\\u20ac'"

"%s" および "%r" 変換型はサポートはされますが、 Python 2 との互換性を
持たせる必要のあるコードベースでのみ使われるべきだということに注意して
ください。

参考:

  **PEP 461** -- bytes と bytearray への % 書式化の追加
     PEP written by Ethan Furman; implemented by Neil Schemenauer and
     Ethan Furman.


PEP 484 - 型ヒント
------------------

関数アノテーション構文はバージョン 3.0 (**PEP 3107**) から Python の仕
様になりましたが、アノテーションのセマンティクスは未定義のままでした。

経験的に、関数アノテーションの使用の大半は関数の引数と返り値の型ヒント
を提供するためのものです。 標準ライブラリーが型アノテーションの基本的
な定義とツールを持てば、Python ユーザに有益であることは明白となりまし
た。

**PEP 484** introduces a *provisional module* to provide these
standard definitions and tools, along with some conventions for
situations where annotations are not available.

例えば、こちらは引数と返り値の型がアノテーションで定義されている簡単な
関数です:

   def greeting(name: str) -> str:
       return 'Hello ' + name

これらのアノテーションは実行時に通常の "__annotations__" 属性より利用
出来ますが、 *実行時に型を自動的にチェックすることはありません*。 その
代わり、独立したオフラインの型チェッカ (例えば mypy) を使って要望通り
にソースコードの解析を行うことが出来るでしょう。

型システムはユニオン、一般型、そして "Any" という全ての型と互換な (す
なわち代入可能) 特殊型をサポートしています。

参考:

  * "typing" モジュールのドキュメント

  * **PEP 484** -- 型ヒント
       PEP 著 Guido van Rossum, Jukka Lehtosalo, Łukasz Langa; 実装
       Guido van Rossum。

  * **PEP 483** -- 型ヒントの理論
       PEP written by Guido van Rossum


PEP 471 - os.scandir() 関数 -- より良く、速いディレクトリイテレータ
-------------------------------------------------------------------

**PEP 471** により新しいディレクトリ反復関数 "os.scandir()" が標準ライ
ブラリへ追加されました。 さらに、 "scandir" を使い "os.walk()" が実装
され、 POSIX システムで3倍から5倍、 Windows システムで7倍から20倍高速
になりました。 これは主に、ディレクトリツリーを走査するのに必要な
"os.stat()" の呼び出し回数をかなり減らしたことによるものです。

これの他にも、  "scandir"  ファイル名のリストではなくイテレータを返す
ようになり、非常に大きなディレクトリ群の走査をするときのメモリ効率が改
善されました。

次の例では、 "os.scandir()" を使用して、与えられた *path* 内の先頭が
"'.'" でないすべてのファイル (ディレクトリを除く) を表示します。
"entry.is_file()" を呼び出しても、通常は追加のシステムコールは行われま
せん:

   for entry in os.scandir(path):
       if not entry.name.startswith('.') and entry.is_file():
           print(entry.name)

参考:

  **PEP 471** -- os.scandir() 関数 -- より良く、速いディレクトリイテレ
  ータ
     PEP 著・実装 Ben Hoyt 補佐 Victor Stinner。


PEP 475: EINTR で失敗したシステムコールの再試行
-----------------------------------------------

システムコール、すなわち I/O の待機がシグナルによって中断される際は常
に、エラーコード "errno.EINTR" で戻ります。 以前は、 Python はそのよう
な場合には "InterruptedError" を送出していました。 つまり、Python アプ
リケーションを書く際には、開発者には二つの選択肢がありました:

1. "InterruptedError" を無視する。

2. 呼び出し箇所の全てで "InterruptedError" を処理し、中断されたシステ
   ムコールの再開を試みる。

最初の選択肢では、アプリケーションは断続的に失敗します。 二つ目の選択
肢では、定型処理を大量に追加せねばならず、コードの可読性が著しく下がり
ます。 次の2つを比べてみてください:

   print("Hello World")

および:

   while True:
       try:
           print("Hello World")
           break
       except InterruptedError:
           continue

**PEP 475** は "EINTR" を受けた場合のシステムコールの自動再試行を実装
しています。 これはほとんどの場合ユーザコードでの "EINTR" や
"InterruptedError" を扱う負担をなくし、標準ライブラリを含む Python プ
ログラムをより堅牢にします。 シグナルハンドラが例外を投げない場合にの
みシステムコールを再試行することに注意してください。

下記は、シグナルで中断された際に再試行をするようになった関数のリストで
す:

* "open()" および "io.open()";

* "faulthandler" モジュールの関数;

* "os" モジュールの関数: "fchdir()", "fchmod()", "fchown()",
  "fdatasync()", "fstat()", "fstatvfs()", "fsync()", "ftruncate()",
  "mkfifo()", "mknod()", "open()", "posix_fadvise()",
  "posix_fallocate()", "pread()", "pwrite()", "read()", "readv()",
  "sendfile()", "wait3()", "wait4()", "wait()", "waitid()",
  "waitpid()", "write()", "writev()";

* 特殊ケース: "os.close()" と "os.dup2()" は "EINTR" エラーを無視する
  ようになりました; そのシステムコールは再試行されません (この論拠につ
  いては PEP を参照してください);

* "select" モジュール関数: "devpoll.poll()", "epoll.poll()",
  "kqueue.control()", "poll.poll()", "select()";

* "socket" クラスのメソッド: "accept()", "connect()" (ノンブロッキング
  ソケットを除く), "recv()", "recvfrom()", "recvmsg()", "send()",
  "sendall()", "sendmsg()", "sendto()";

* "signal.sigtimedwait()" および "signal.sigwaitinfo()";

* "time.sleep()".

参考:

  **PEP 475** -- EINTR で失敗したシステムコールの再試行
     Antoine Pitrou の協力のもと、 PEP および実装は Charles-François
     Natali と Victor Stinner によって書かれました (『フレンチ・コネク
     ション』)。


PEP 479: ジェネレータ内の StopIteration の処理の変更
----------------------------------------------------

Python 3.4 以前では、ジェネレータと "StopIteration" の組み合わせが驚く
ような動作をし、分かりづらいバグを隠すことがありました。 以前は、ジェ
ネレータ関数内でうっかり "StopIteration" が送出されると、そのジェネレ
ータの反復処理をしているループ構造が終端に達したと解釈されていました。

**PEP 479** によってジェネレータのこの振る舞いが変更されました: ジェネ
レータ内部で "StopIteration" 例外が送出されたときは、ジェネレータのフ
レームを抜ける前に "RuntimeError" に置き換えられます。 この変更の一番
の目的は、保護されていない "next()" の呼び出しが "StopIteration" を送
出し、ジェネレータを回している反復処理が黙って終了してしまうような状況
で、デバッグをしやすくすることです。 これは "yield from" 構造と組み合
わさったとき特に有害になります。

これは後方互換性の無い変更ですので、この新しい振る舞いを有効にするには
*__future__* のインポートが必要です:

   >>> from __future__ import generator_stop

   >>> def gen():
   ...     next(iter([]))
   ...     yield
   ...
   >>> next(gen())
   Traceback (most recent call last):
     File "<stdin>", line 2, in gen
   StopIteration

   The above exception was the direct cause of the following exception:

   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   RuntimeError: generator raised StopIteration

"__future__" をインポートしておらず、ジェネレータの内部で
"StopIteration" 例外が送出されたときには "PendingDeprecationWarning"
が送出されます。

参考:

  **PEP 479** -- ジェネレータ内の StopIteration の処理の変更
     PEP written by Chris Angelico and Guido van Rossum. Implemented
     by Chris Angelico, Yury Selivanov and Nick Coghlan.


PEP 485: 近似的に等しいことを調べる関数
---------------------------------------

**PEP 485** により、2値が互いに近似的に等しいか "近い" ことを調べる関
数 "math.isclose()" 及び "cmath.isclose()" が追加されました。 2値が近
いと判断されるかどうかは与えられた絶対及び相対許容差で決まります。 相
対許容差は "isclose" 引数間で許される、絶対値の大きい方に対する最大の
差です:

   >>> import math
   >>> a = 5.0
   >>> b = 4.99998
   >>> math.isclose(a, b, rel_tol=1e-5)
   True
   >>> math.isclose(a, b, rel_tol=1e-6)
   False

2値を絶対許容差で比較することも出来ます。絶対許容差は非負数でなければ
なりません:

   >>> import math
   >>> a = 5.0
   >>> b = 4.99998
   >>> math.isclose(a, b, abs_tol=0.00003)
   True
   >>> math.isclose(a, b, abs_tol=0.00001)
   False

参考:

  **PEP 485** -- A function for testing approximate equality
     PEP written by Christopher Barker; implemented by Chris Barker
     and Tal Einat.


PEP 486: Python ランチャーが仮想環境を認識する
----------------------------------------------

**PEP 486** により、 Windows ランチャー (**PEP 397** を参照してくださ
い) が有効になっている仮想環境を認識するようになりました。 デフォルト
のインタプリタを使っていて、 "VIRTUAL_ENV" 環境変数が設定されていると
きは、仮想環境のインタプリタが使われます。

参考:

  **PEP 486** -- Python ランチャーが仮想環境を認識する
     PEP written and implemented by Paul Moore.


PEP 488: PYO ファイルの廃止
---------------------------

**PEP 488** は ".pyo" ファイルという概念を廃止しました。 つまり、
".pyc" ファイルは最適化されていないバイトコードと最適化されたバイトコ
ードの両方を指すということです。 バイトコードファイルを何度も再生成す
る必要がないよう、バイトコードが最適化されたときは ".pyc" ファイルは任
意の "opt-" タグを名前に持つようになりました。 この副作用で、"-O" と
"-OO" のいずれかで実行した場合でも、バイトコードのファイル名が衝突しな
いようになりました。 それにより、"-O" および "-OO" で生成したバイトコ
ードは同時に存在できるようになりました。
"importlib.util.cache_from_source()" にの API は更新され、この変更に役
立ちます。

参考:

  **PEP 488** -- PYO ファイルの廃止
     PEP written and implemented by Brett Cannon.


PEP 489: 拡張モジュールの多段階初期化
-------------------------------------

**PEP 489** により拡張モジュールの初期化方式が更新され、 Python 3.4 で
**PEP 451** によって導入された2段階でモジュールを読み込む仕組みが活用
できるようになりました。

この変更によって、新しい仕組みを使うことを選択した拡張モジュールのイン
ポートの動作が、 Python のソースコードやバイトコードでできたモジュール
にかなり近くなり、これまで ASCII に制限されていたモジュール名に任意の
識別子が使えるようになりました。

参考:

  **PEP 489** -- 拡張モジュールの多段階初期化
     PEP 著 Petr Viktorin, Stefan Behnel, Nick Coghlan; 実装 Petr
     Viktorin.


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

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

* ""namereplace"" エラーハンドラが追加されました。""backslashreplace""
  エラーハンドラはデコードと変換で動くようになりました。 (Contributed
  by Serhiy Storchaka in bpo-19676 and bpo-22286.)

* "-b" オプションが "bytes" と "int" の比較に影響するようになりました
  。 (Contributed by Serhiy Storchaka in bpo-23681.)

* 新たなカザフ語 "kz1048" 及びタジク語 "koi8_t" コーデックス。
  (Contributed by Serhiy Storchaka in bpo-22682 and bpo-22681.)

* プロパティのドキュメンテーション文字列が書き込み可能になりました。こ
  れは特に "collections.namedtuple()" のドキュメンテーション文字列で有
  用です。 (Contributed by Berker Peksag in bpo-24064.)

* 相対インポートに関する循環インポートがサポートされました。
  (Contributed by Brett Cannon and Antoine Pitrou in bpo-17636.)


新たなモジュール
================


typing
------

The new "typing" *provisional* module provides standard definitions
and tools for function type annotations. See Type Hints for more
information.


zipapp
------

新たな "zipapp" モジュール (**PEP 441** で仕様定義) は実行可能な
Python Zip アプリケーションを作成するための API とコマンドラインツール
を提供します。 Python Zip アプリケーションは Python 2.6 の bpo-1739468
で導入されましたが、それ以降もあまり知られていませんでした。

この新しいモジュールを使ったアプリケーションのバンドル方法は単純で、
"__main__.py" ファイルを含む全てのファイルをディレクトリ "myapp" に置
き、次のように実行します:

   $ python -m zipapp myapp
   $ python myapp.pyz

モジュールの実装は bpo-23491 の Paul Moore による貢献です。

参考: **PEP 441** -- Python ZIP アプリケーションのサポートの改善
    <whatsnew-zipapp>`


改良されたモジュール
====================


argparse
--------

"ArgumentParser" クラスは、allow_abbrev を "False" に設定することでロ
ングオプションの 短縮使用 を無効化できるようになりました。
(Contributed by Jonathan Paugh, Steven Bethard, paul j3 and Daniel
Eriksson in bpo-14910.)


asyncio
-------

Since the "asyncio" module is *provisional*, all changes introduced in
Python 3.5 have also been backported to Python 3.4.x.

Python 3.4.0 以後の "asyncio" モジュールの重要な変更点:

* 新たなデバッグ API: "loop.set_debug()" と "loop.get_debug()" メソッ
  ド。 (Contributed by Victor Stinner.)

* proactor イベントループが SSL をサポートしました。 (Contributed by
  Antoine Pitrou and Victor Stinner in bpo-22560.)

* イベントループが閉じているかどうか調べる新たな "loop.is_closed()" メ
  ソッド。 (Contributed by Victor Stinner in bpo-21326.)

* コルーチンの新しい "Task" を便利に作成しスケジュールするための新たな
  "loop.create_task()"。 "create_task" メソッドは コルーチンをタスクに
  ラップする全ての asyncio 関数、たとえば "asyncio.wait()",
  "asyncio.gather()"、にも使われます。 (Contributed by Victor
  Stinner.)

* A new "transport.get_write_buffer_limits()" method to inquire for
  *high-* and *low-* water limits of the flow control. (Contributed by
  Victor Stinner.)

* "async()" 関数は "ensure_future()" により非推奨になりました。
  (Contributed by Yury Selivanov.)

* "loop.create_task()" メソッドが使うタスクファクトリーをカスタマイズ
  するための新たな "loop.set_task_factory()" メソッドと
  "loop.get_task_factory()" メソッド。 (Yury Selivanovによる貢献。)

* 新たな "Queue.join()" および "Queue.task_done()" キューメソッド。
  (Contributed by Victor Stinner.)

* "JoinableQueue" クラスは "asyncio.Queue" クラスにより削除されました
  。 (Contributed by Victor Stinner.)

3.5.1 での変更:

* The "ensure_future()" function and all functions that use it, such
  as "loop.run_until_complete()", now accept all kinds of *awaitable
  objects*. (Contributed by Yury Selivanov.)

* 他のスレッドからコルーチンをイベントループに送信するための新たな
  "run_coroutine_threadsafe()" 関数。 (Contributed by Vincent Michel.)

* New "Transport.is_closing()" method to check if the transport is
  closing or closed. (Contributed by Yury Selivanov.)

* The "loop.create_server()" method can now accept a list of hosts.
  (Contributed by Yann Sionneau.)

3.5.2 での変更:

* New "loop.create_future()" method to create Future objects.  This
  allows alternative event loop implementations, such as uvloop, to
  provide a faster "asyncio.Future" implementation. (Contributed by
  Yury Selivanov.)

* New "loop.get_exception_handler()" method to get the current
  exception handler. (Contributed by Yury Selivanov.)

* 新しい "StreamReader.readuntil()" メソッドで、区切りとなるバイトの並
  びが出てくるまでストリームからデータを読み取れるようになりました。
  (Contributed by Mark Korenberg.)

* The "loop.create_connection()" and "loop.create_server()" methods
  are optimized to avoid calling the system "getaddrinfo" function if
  the address is already resolved. (Contributed by A. Jesse Jiryu
  Davis.)

* The "loop.sock_connect(sock, address)" no longer requires the
  *address* to be resolved prior to the call. (Contributed by A. Jesse
  Jiryu Davis.)


bz2
---

"BZ2Decompressor.decompress" メソッドがオプション引数 *max_length* を
取れるようになり、展開されたデータの最大サイズが制限できるようになりま
した。 (Contributed by Nikolaus Rath in bpo-15955.)


cgi
---

"FieldStorage" クラスが *context manager* プロトコルをサポートするよう
になりました。  (Contributed by Berker Peksag in bpo-20289.)


cmath
-----

新たな関数 "isclose()" は近似的に等しいかどうかを判断する方法を提供し
ます。 (Contributed by Chris Barker and Tal Einat in bpo-24270.)


コード
------

"InteractiveInterpreter.showtraceback()" メソッドが、対話的インタープ
リタのように連なったスタックトレース全体を表示するようになりました。
(Contributed by Claudiu Popa in bpo-17442.)


collections
-----------

"collections.OrderedDict" が C で実装されました。 これにより 4倍 から
100 倍高速になりました。 (Contributed by Eric Snow in bpo-16991.)

"OrderedDict.items()", "OrderedDict.keys()", "OrderedDict.values()" ビ
ューが "reversed()" イテレーションをサポートしました。 (Contributed by
Serhiy Storchaka in bpo-19505.)

"deque" クラスが "index()"、 "insert()"、 "copy()" を定義し、"+" と
"*" 演算をサポートしました。 これにより deque インスタンスは
"MutableSequence" と認識され、list との代替性が向上しました。
(Contributed by Raymond Hettinger in bpo-23704.)

"namedtuple()" で生成されたドキュメンテーション文字列が更新可能となり
ました:

   Point = namedtuple('Point', ['x', 'y'])
   Point.__doc__ += ': Cartesian coodinate'
   Point.x.__doc__ = 'abscissa'
   Point.y.__doc__ = 'ordinate'

(Contributed by Berker Peksag in bpo-24064.)

The "UserString" class now implements the "__getnewargs__()",
"__rmod__()", "casefold()", "format_map()", "isprintable()", and
"maketrans()" methods to match the corresponding methods of "str".
(Contributed by Joe Jevnik in bpo-22189.)


collections.abc
---------------

The "Sequence.index()" method now accepts *start* and *stop* arguments
to match the corresponding methods of "tuple", "list", etc.
(Contributed by Devin Jeanpierre in bpo-23086.)

新たに "Generator" 抽象基底クラスが追加されました。 (Contributed by
Stefan Behnel in bpo-24018.)

新たに "Awaitable", "Coroutine", "AsyncIterator", "AsyncIterable" 抽象
基底クラスが追加されました。 (Contributed by Yury Selivanov in
bpo-24184.)

古い Python のバージョンでは、新しい ABC のバックポートが外部の PyPI
パッケージ で利用出来ます。


compileall
----------

A new "compileall" option, "-j *N*", allows running *N* workers
simultaneously to perform parallel bytecode compilation. The
"compile_dir()" function has a corresponding "workers" parameter.
(Contributed by Claudiu Popa in bpo-16104.)

Another new option, "-r", allows controlling the maximum recursion
level for subdirectories.  (Contributed by Claudiu Popa in bpo-19628.)

The "-q" command line option can now be specified more than once, in
which case all output, including errors, will be suppressed.  The
corresponding "quiet" parameter in "compile_dir()", "compile_file()",
and "compile_path()" can now accept an integer value indicating the
level of output suppression. (Contributed by Thomas Kluyver in
bpo-21338.)


concurrent.futures
------------------

The "Executor.map()" method now accepts a *chunksize* argument to
allow batching of tasks to improve performance when
"ProcessPoolExecutor()" is used. (Contributed by Dan O'Reilly in
bpo-11271.)

The number of workers in the "ThreadPoolExecutor" constructor is
optional now.  The default value is 5 times the number of CPUs.
(Contributed by Claudiu Popa in bpo-21527.)


configparser
------------

"configparser" now provides a way to customize the conversion of
values by specifying a dictionary of converters in the "ConfigParser"
constructor, or by defining them as methods in "ConfigParser"
subclasses.  Converters defined in a parser instance are inherited by
its section proxies.

以下はプログラム例です:

   >>> import configparser
   >>> conv = {}
   >>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]
   >>> cfg = configparser.ConfigParser(converters=conv)
   >>> cfg.read_string("""
   ... [s]
   ... list = a b c d e f g
   ... """)
   >>> cfg.get('s', 'list')
   'a b c d e f g'
   >>> cfg.getlist('s', 'list')
   ['a', 'b', 'c', 'd', 'e', 'f', 'g']
   >>> section = cfg['s']
   >>> section.getlist('list')
   ['a', 'b', 'c', 'd', 'e', 'f', 'g']

(Contributed by Łukasz Langa in bpo-18159.)


contextlib
----------

新規 *context manager* の "contextlib.redirect_stderr()" は、ユーティ
リティスクリプトにて、その出力を "sys.stderr" に書き出す一方でその向き
先を変えれない頑固な API の扱いを簡単にしてくれます
("redirect_stdout()" と対となるものです)。:

   >>> import contextlib, io, logging
   >>> f = io.StringIO()
   >>> with contextlib.redirect_stderr(f):
   ...     logging.warning('warning')
   ...
   >>> f.getvalue()
   'WARNING:root:warning\n'

(Contributed by Berker Peksag in bpo-22389.)


csv
---

"writerow()" メソッドは、シーケンスだけでなく、 任意のイテラブルをサポ
ートしました。(Contributed by Serhiy Storchaka in bpo-23171.)


curses
------

The new "update_lines_cols()" function updates the "LINES" and "COLS"
environment variables.  This is useful for detecting manual screen
resizing.  (Contributed by Arnon Yaari in bpo-4254.)


dbm
---

"dumb.open" always creates a new database when the flag has the value
""n"".  (Contributed by Claudiu Popa in bpo-18039.)


difflib
-------

The charset of HTML documents generated by "HtmlDiff.make_file()" can
now be customized by using a new *charset* keyword-only argument. The
default charset of HTML document changed from ""ISO-8859-1"" to
""utf-8"". (Contributed by Berker Peksag in bpo-2052.)

The "diff_bytes()" function can now compare lists of byte strings.
This fixes a regression from Python 2. (Contributed by Terry J. Reedy
and Greg Ward in bpo-17445.)


distutils
---------

Both the "build" and "build_ext" commands now accept a "-j" option to
enable parallel building of extension modules. (Contributed by Antoine
Pitrou in bpo-5309.)

The "distutils" module now supports "xz" compression, and can be
enabled by passing "xztar" as an argument to "bdist --format".
(Contributed by Serhiy Storchaka in bpo-16314.)


doctest
-------

"DocTestSuite()" 関数が、 *module* がドキュメンテーション文字列
(docstrings)を含まない場合に "ValueError" を送出するのではなく空の
"unittest.TestSuite" を返すようになりました。 (Contributed by Glenn
Jones in bpo-15916.)


email
-----

A new policy option "Policy.mangle_from_" controls whether or not
lines that start with ""From "" in email bodies are prefixed with a
"">"" character by generators.  The default is "True" for "compat32"
and "False" for all other policies. (Contributed by Milan Oberkirch in
bpo-20098.)

A new "Message.get_content_disposition()" method provides easy access
to a canonical value for the *Content-Disposition* header.
(Contributed by Abhilash Raj in bpo-21083.)

A new policy option "EmailPolicy.utf8" can be set to "True" to encode
email headers using the UTF-8 charset instead of using encoded words.
This allows "Messages" to be formatted according to **RFC 6532** and
used with an SMTP server that supports the **RFC 6531** "SMTPUTF8"
extension.  (Contributed by R. David Murray in bpo-24211.)

The "mime.text.MIMEText" constructor now accepts a "charset.Charset"
instance. (Contributed by Claude Paroz and Berker Peksag in
bpo-16324.)


enum
----

"Enum" 呼び出し可能オブジェクトは、*names* のみが与えられた場合に enum
値の初期値を指定する新たな引数 *start* を持ちます:

   >>> Animal = enum.Enum('Animal', 'cat dog', start=10)
   >>> Animal.cat
   <Animal.cat: 10>
   >>> Animal.dog
   <Animal.dog: 11>

(Contributed by Ethan Furman in bpo-21706.)


faulthandler
------------

関数 "enable()", "register()", "dump_traceback()",
"dump_traceback_later()" が、ファイル様オブジェクトだけでなくファイル
記述子を受け取るようになりました。 (Contributed by Wei Wu in
bpo-23566.)


functools
---------

"lru_cache()" 機構の多くが C で実装されました。これにより速度が大幅に
向上しました。 (Contributed by Matt Joiner, Alexey Kachayev, and
Serhiy Storchaka in bpo-14373.)


glob
----

"iglob()" 関数と "glob()" 関数は、 ""**"" パターンを使ったサブディレク
トリの再帰的な検索をサポートしました。(Contributed by Serhiy Storchaka
in bpo-13968.)


gzip
----

"GzipFile" コンストラクタの *mode* 引数が排他的作成を要求する ""x""
を受け取るようになりました。 (Contributed by Tim Heaney in bpo-19222.)


heapq
-----

Element comparison in "merge()" can now be customized by passing a
*key function* in a new optional *key* keyword argument, and a new
optional *reverse* keyword argument can be used to reverse element
comparison:

   >>> import heapq
   >>> a = ['9', '777', '55555']
   >>> b = ['88', '6666']
   >>> list(heapq.merge(a, b, key=len))
   ['9', '88', '777', '6666', '55555']
   >>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))
   ['55555', '6666', '777', '88', '9']

(Contributed by Raymond Hettinger in bpo-13742.)


http
----

新しい "HTTPStatus" のenum は、HTTPステータスコードのセットで、その理
由句と詳細な説明は、英語で記載されています。(Contributed by Demian
Brecht in bpo-21793.)


http.client
-----------

"HTTPConnection.getresponse()" now raises a "RemoteDisconnected"
exception when a remote server connection is closed unexpectedly.
Additionally, if a "ConnectionError" (of which "RemoteDisconnected" is
a subclass) is raised, the client socket is now closed automatically,
and will reconnect on the next request:

   import http.client
   conn = http.client.HTTPConnection('www.python.org')
   for retries in range(3):
       try:
           conn.request('GET', '/')
           resp = conn.getresponse()
       except http.client.RemoteDisconnected:
           pass

(Contributed by Martin Panter in bpo-3566.)


idlelib と IDLE
---------------

idlelib は IDLE シェルとエディタを実装するものであってほかのプログラム
からインポートされることを意図してはいないので、改善は毎度のリリースご
とに行われます。3.4.0 から始まり、また将来の 3.5.x リリースになされる
累積的な変更リストは "Lib/idlelib/NEWS.txt" で読むことが出来ます。この
ファイルは IDLE で Help ‣ About IDLE からも辿り着けます。


imaplib
-------

"IMAP4" クラスが *context manager* プロトコルをサポートするようになり
ました。 "with" 文とともに使うと、 IMAP4 "LOGOUT" コマンドがブロックの
終了時に自動的に呼び出されます。 (Contributed by Tarek Ziadé and
Serhiy Storchaka in bpo-4972.)

The "imaplib" module now supports **RFC 5161** (ENABLE Extension) and
**RFC 6855** (UTF-8 Support) via the "IMAP4.enable()" method.  A new
"IMAP4.utf8_enabled" attribute tracks whether or not **RFC 6855**
support is enabled. (Contributed by Milan Oberkirch, R. David Murray,
and Maciej Szulik in bpo-21800.)

The "imaplib" module now automatically encodes non-ASCII string
usernames and passwords using UTF-8, as recommended by the RFCs.
(Contributed by Milan Oberkirch in bpo-21800.)


imghdr
------

The "what()" function now recognizes the OpenEXR format (contributed
by Martin Vignali and Claudiu Popa in bpo-20295), and the WebP format
(contributed by Fabrice Aneche and Claudiu Popa in bpo-20197.)


importlib
---------

The "util.LazyLoader" class allows for lazy loading of modules in
applications where startup time is important. (Contributed by Brett
Cannon in bpo-17621.)

The "abc.InspectLoader.source_to_code()" method is now a static
method.  This makes it easier to initialize a module object with code
compiled from a string by running "exec(code, module.__dict__)".
(Contributed by Brett Cannon in bpo-21156.)

The new "util.module_from_spec()" function is now the preferred way to
create a new module.  As opposed to creating a "types.ModuleType"
instance directly, this new function will set the various import-
controlled attributes based on the passed-in spec object.
(Contributed by Brett Cannon in bpo-20383.)


inspect
-------

Both the "Signature" and "Parameter" classes are now picklable and
hashable.  (Contributed by Yury Selivanov in bpo-20726 and bpo-20334.)

A new "BoundArguments.apply_defaults()" method provides a way to set
default values for missing arguments:

   >>> def foo(a, b='ham', *args): pass
   >>> ba = inspect.signature(foo).bind('spam')
   >>> ba.apply_defaults()
   >>> ba.arguments
   OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])

(Contributed by Yury Selivanov in bpo-24190.)

A new class method "Signature.from_callable()" makes subclassing of
"Signature" easier.  (Contributed by Yury Selivanov and Eric Snow in
bpo-17373.)

The "signature()" function now accepts a *follow_wrapped* optional
keyword argument, which, when set to "False", disables automatic
following of "__wrapped__" links. (Contributed by Yury Selivanov in
bpo-20691.)

A set of new functions to inspect *coroutine functions* and *coroutine
objects* has been added: "iscoroutine()", "iscoroutinefunction()",
"isawaitable()", "getcoroutinelocals()", and "getcoroutinestate()".
(Contributed by Yury Selivanov in bpo-24017 and bpo-24400.)

The "stack()", "trace()", "getouterframes()", and "getinnerframes()"
functions now return a list of named tuples. (Contributed by Daniel
Shahaf in bpo-16808.)


io
--

A new "BufferedIOBase.readinto1()" method, that uses at most one call
to the underlying raw stream's "RawIOBase.read()" or
"RawIOBase.readinto()" methods. (Contributed by Nikolaus Rath in
bpo-20578.)


ipaddress
---------

Both the "IPv4Network" and "IPv6Network" classes now accept an
"(address, netmask)" tuple argument, so as to easily construct network
objects from existing addresses:

   >>> import ipaddress
   >>> ipaddress.IPv4Network(('127.0.0.0', 8))
   IPv4Network('127.0.0.0/8')
   >>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))
   IPv4Network('127.0.0.0/8')

(Contributed by Peter Moody and Antoine Pitrou in bpo-16531.)

A new "reverse_pointer" attribute for the "IPv4Network" and
"IPv6Network" classes returns the name of the reverse DNS PTR record:

   >>> import ipaddress
   >>> addr = ipaddress.IPv4Address('127.0.0.1')
   >>> addr.reverse_pointer
   '1.0.0.127.in-addr.arpa'
   >>> addr6 = ipaddress.IPv6Address('::1')
   >>> addr6.reverse_pointer
   '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'

(Contributed by Leon Weber in bpo-20480.)


json
----

The "json.tool" command line interface now preserves the order of keys
in JSON objects passed in input.  The new "--sort-keys" option can be
used to sort the keys alphabetically. (Contributed by Berker Peksag in
bpo-21650.)

JSON decoder now raises "JSONDecodeError" instead of "ValueError" to
provide better context information about the error. (Contributed by
Serhiy Storchaka in bpo-19361.)


linecache
---------

A new "lazycache()" function can be used to capture information about
a non-file-based module to permit getting its lines later via
"getline()". This avoids doing I/O until a line is actually needed,
without having to carry the module globals around indefinitely.
(Contributed by Robert Collins in bpo-17911.)


locale
------

A new "delocalize()" function can be used to convert a string into a
normalized number string, taking the "LC_NUMERIC" settings into
account:

   >>> import locale
   >>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
   'de_DE.UTF-8'
   >>> locale.delocalize('1.234,56')
   '1234.56'
   >>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
   'en_US.UTF-8'
   >>> locale.delocalize('1,234.56')
   '1234.56'

(Contributed by Cédric Krier in bpo-13918.)


logging
-------

All logging methods ("Logger" "log()", "exception()", "critical()",
"debug()", etc.), now accept exception instances as an *exc_info*
argument, in addition to boolean values and exception tuples:

   >>> import logging
   >>> try:
   ...     1/0
   ... except ZeroDivisionError as ex:
   ...     logging.error('exception', exc_info=ex)
   ERROR:root:exception

(Contributed by Yury Selivanov in bpo-20537.)

The "handlers.HTTPHandler" class now accepts an optional
"ssl.SSLContext" instance to configure SSL settings used in an HTTP
connection. (Contributed by Alex Gaynor in bpo-22788.)

The "handlers.QueueListener" class now takes a *respect_handler_level*
keyword argument which, if set to "True", will pass messages to
handlers taking handler levels into account. (Contributed by Vinay
Sajip.)


lzma
----

The "LZMADecompressor.decompress()" method now accepts an optional
*max_length* argument to limit the maximum size of decompressed data.
(Contributed by Martin Panter in bpo-15955.)


math
----

"math" モジュールに定数 "inf" および "nan" が追加されました。
(Contributed by Mark Dickinson in bpo-23185.)

新たな関数 "isclose()" は近似的に等しいことを調べる方法を提供します。
(Contributed by Chris Barker and Tal Einat in bpo-24270.)

新たに関数 "gcd()" が追加されました。 関数 "fractions.gcd()" は非推奨
です。 (Contributed by Mark Dickinson and Serhiy Storchaka in
bpo-22486.)


multiprocessing
---------------

"sharedctypes.synchronized()" オブジェクトが *コンテキストマネージャ*
プロトコルをサポートするようになりました。 (Contributed by Charles-
François Natali in bpo-21565.)


operator
--------

"attrgetter()", "itemgetter()", and "methodcaller()" objects now
support pickling. (Contributed by Josh Rosenberg and Serhiy Storchaka
in bpo-22955.)

行列乗算を行う "matmul()" 関数と "imatmul()" 関数が新しく追加されまし
た。 (Contributed by Benjamin Peterson in bpo-21176.)


os
--

The new "scandir()" function returning an iterator of "DirEntry"
objects has been added.  If possible, "scandir()" extracts file
attributes while scanning a directory, removing the need to perform
subsequent system calls to determine file type or attributes, which
may significantly improve performance.  (Contributed by Ben Hoyt with
the help of Victor Stinner in bpo-22524.)

Windows において、新たに "stat_result.st_file_attributes" 属性が利用可
能です。これは Windows API の "GetFileInformationByHandle()" から返る
"BY_HANDLE_FILE_INFORMATION" 構造体のメンバ "dwFileAttributes" に対応
します。 (Contributed by Ben Hoyt in bpo-21719.)

"urandom()" 関数が、Linux 3.17 以降ではシステムコール "getrandom()" を
、OpenBSD 5.6 以降ではシステムコール "getentropy()" を使うようになりま
した。これは "/dev/urandom" を使う必要性をなくし、潜在的には起こり得た
ファイル記述子を使い果たすことによる失敗を避けることに繋がります。
(Contributed by Victor Stinner in bpo-22181.)

新たな関数 "get_blocking()" および "set_blocking()" により、ファイル記
述子のブロッキングモード ("O_NONBLOCK") の取得と設定が出来るようになり
ました。 (Contributed by Victor Stinner in bpo-22054.)

"truncate()" と "ftruncate()" が Windows でサポートされるようになりま
した。 (Contributed by Steve Dower in bpo-23668.)

There is a new "os.path.commonpath()" function returning the longest
common sub-path of each passed pathname.  Unlike the
"os.path.commonprefix()" function, it always returns a valid path:

   >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
   '/usr/l'

   >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
   '/usr'

(Contributed by Rafik Draoui and Serhiy Storchaka in bpo-10395.)


pathlib
-------

The new "Path.samefile()" method can be used to check whether the path
points to the same file as another path, which can be either another
"Path" object, or a string:

   >>> import pathlib
   >>> p1 = pathlib.Path('/etc/hosts')
   >>> p2 = pathlib.Path('/etc/../etc/hosts')
   >>> p1.samefile(p2)
   True

(Contributed by Vajrasky Kok and Antoine Pitrou in bpo-19775.)

The "Path.mkdir()" method now accepts a new optional *exist_ok*
argument to match "mkdir -p" and "os.makedirs()" functionality.
(Contributed by Berker Peksag in bpo-21539.)

There is a new "Path.expanduser()" method to expand "~" and "~user"
prefixes.  (Contributed by Serhiy Storchaka and Claudiu Popa in
bpo-19776.)

A new "Path.home()" class method can be used to get a "Path" instance
representing the user’s home directory. (Contributed by Victor Salgado
and Mayank Tripathi in bpo-19777.)

New "Path.write_text()", "Path.read_text()", "Path.write_bytes()",
"Path.read_bytes()" methods to simplify read/write operations on
files.

The following code snippet will create or rewrite existing file
"~/spam42":

   >>> import pathlib
   >>> p = pathlib.Path('~/spam42')
   >>> p.expanduser().write_text('ham')
   3

(Contributed by Christopher Welborn in bpo-20218.)


pickle
------

Nested objects, such as unbound methods or nested classes, can now be
pickled using pickle protocols older than protocol version 4. Protocol
version 4 already supports these cases.  (Contributed by Serhiy
Storchaka in bpo-23611.)


poplib
------

A new "POP3.utf8()" command enables **RFC 6856** (Internationalized
Email) support, if a POP server supports it. (Contributed by Milan
OberKirch in bpo-21804.)


re
--

References and conditional references to groups with fixed length are
now allowed in lookbehind assertions:

   >>> import re
   >>> pat = re.compile(r'(a|b).(?<=\1)c')
   >>> pat.match('aac')
   <_sre.SRE_Match object; span=(0, 3), match='aac'>
   >>> pat.match('bbc')
   <_sre.SRE_Match object; span=(0, 3), match='bbc'>

(Contributed by Serhiy Storchaka in bpo-9179.)

The number of capturing groups in regular expressions is no longer
limited to 100.  (Contributed by Serhiy Storchaka in bpo-22437.)

The "sub()" and "subn()" functions now replace unmatched groups with
empty strings instead of raising an exception. (Contributed by Serhiy
Storchaka in bpo-1519638.)

The "re.error" exceptions have new attributes, "msg", "pattern",
"pos", "lineno", and "colno", that provide better context information
about the error:

   >>> re.compile("""
   ...     (?x)
   ...     .++
   ... """)
   Traceback (most recent call last):
      ...
   sre_constants.error: multiple repeat at position 16 (line 3, column 7)

(Contributed by Serhiy Storchaka in bpo-22578.)


readline
--------

A new "append_history_file()" function can be used to append the
specified number of trailing elements in history to the given file.
(Contributed by Bruno Cauet in bpo-22940.)


selectors
---------

The new "DevpollSelector" supports efficient "/dev/poll" polling on
Solaris. (Contributed by Giampaolo Rodola' in bpo-18931.)


shutil
------

The "move()" function now accepts a *copy_function* argument,
allowing, for example, the "copy()" function to be used instead of the
default "copy2()" if there is a need to ignore file metadata when
moving. (Contributed by Claudiu Popa in bpo-19840.)

The "make_archive()" function now supports the *xztar* format.
(Contributed by Serhiy Storchaka in bpo-5411.)


signal
------

Windows において、 "set_wakeup_fd()" 関数がソケットハンドルもサポート
するようになりました。  (Contributed by Victor Stinner in bpo-22018.)

Various "SIG*" constants in the "signal" module have been converted
into "Enums".  This allows meaningful names to be printed during
debugging, instead of integer "magic numbers". (Contributed by
Giampaolo Rodola' in bpo-21076.)


smtpd
-----

Both the "SMTPServer" and "SMTPChannel" classes now accept a
*decode_data* keyword argument to determine if the "DATA" portion of
the SMTP transaction is decoded using the ""utf-8"" codec or is
instead provided to the "SMTPServer.process_message()" method as a
byte string.  The default is "True" for backward compatibility
reasons, but will change to "False" in Python 3.6.  If *decode_data*
is set to "False", the "process_message" method must be prepared to
accept keyword arguments. (Contributed by Maciej Szulik in bpo-19662.)

The "SMTPServer" class now advertises the "8BITMIME" extension (**RFC
6152**) if *decode_data* has been set "True".  If the client specifies
"BODY=8BITMIME" on the "MAIL" command, it is passed to
"SMTPServer.process_message()" via the *mail_options* keyword.
(Contributed by Milan Oberkirch and R.  David Murray in bpo-21795.)

The "SMTPServer" class now also supports the "SMTPUTF8" extension
(**RFC 6531**: Internationalized Email).  If the client specified
"SMTPUTF8 BODY=8BITMIME" on the "MAIL" command, they are passed to
"SMTPServer.process_message()" via the *mail_options* keyword.  It is
the responsibility of the "process_message" method to correctly handle
the "SMTPUTF8" data. (Contributed by Milan Oberkirch in bpo-21725.)

It is now possible to provide, directly or via name resolution, IPv6
addresses in the "SMTPServer" constructor, and have it successfully
connect.  (Contributed by Milan Oberkirch in bpo-14758.)


smtplib
-------

A new "SMTP.auth()" method provides a convenient way to implement
custom authentication mechanisms. (Contributed by Milan Oberkirch in
bpo-15014.)

The "SMTP.set_debuglevel()" method now accepts an additional
debuglevel (2), which enables timestamps in debug messages.
(Contributed by Gavin Chappell and Maciej Szulik in bpo-16914.)

Both the "SMTP.sendmail()" and "SMTP.send_message()" methods now
support **RFC 6531** (SMTPUTF8). (Contributed by Milan Oberkirch and
R. David Murray in bpo-22027.)


sndhdr
------

関数 "what()" と "whathdr()" が "namedtuple()" で返すようになりました
。  (Contributed by Claudiu Popa in bpo-18615.)


socket
------

Functions with timeouts now use a monotonic clock, instead of a system
clock. (Contributed by Victor Stinner in bpo-22043.)

A new "socket.sendfile()" method allows sending a file over a socket
by using the high-performance "os.sendfile()" function on UNIX,
resulting in uploads being from 2 to 3 times faster than when using
plain "socket.send()". (Contributed by Giampaolo Rodola' in
bpo-17552.)

The "socket.sendall()" method no longer resets the socket timeout
every time bytes are received or sent.  The socket timeout is now the
maximum total duration to send all data. (Contributed by Victor
Stinner in bpo-23853.)

The *backlog* argument of the "socket.listen()" method is now
optional.  By default it is set to "SOMAXCONN" or to "128", whichever
is less. (Contributed by Charles-François Natali in bpo-21455.)


ssl
---


メモリ BIO サポート
~~~~~~~~~~~~~~~~~~~

(Contributed by Geert Jansen in bpo-21965.)

The new "SSLObject" class has been added to provide SSL protocol
support for cases when the network I/O capabilities of "SSLSocket" are
not necessary or are suboptimal.  "SSLObject" represents an SSL
protocol instance, but does not implement any network I/O methods, and
instead provides a memory buffer interface.  The new "MemoryBIO" class
can be used to pass data between Python and an SSL protocol instance.

The memory BIO SSL support is primarily intended to be used in
frameworks implementing asynchronous I/O for which "SSLSocket"'s
readiness model ("select/poll") is inefficient.

A new "SSLContext.wrap_bio()" method can be used to create a new
"SSLObject" instance.


Application-Layer Protocol Negotiation Support
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(Contributed by Benjamin Peterson in bpo-20188.)

Where OpenSSL support is present, the "ssl" module now implements the
*Application-Layer Protocol Negotiation* TLS extension as described in
**RFC 7301**.

The new "SSLContext.set_alpn_protocols()" can be used to specify which
protocols a socket should advertise during the TLS handshake.

The new "SSLSocket.selected_alpn_protocol()" returns the protocol that
was selected during the TLS handshake. The "HAS_ALPN" flag indicates
whether ALPN support is present.


その他の変更
~~~~~~~~~~~~

There is a new "SSLSocket.version()" method to query the actual
protocol version in use. (Contributed by Antoine Pitrou in bpo-20421.)

The "SSLSocket" class now implements a "SSLSocket.sendfile()" method.
(Contributed by Giampaolo Rodola' in bpo-17552.)

The "SSLSocket.send()" method now raises either the
"ssl.SSLWantReadError" or "ssl.SSLWantWriteError" exception on a non-
blocking socket if the operation would block. Previously, it would
return "0".  (Contributed by Nikolaus Rath in bpo-20951.)

The "cert_time_to_seconds()" function now interprets the input time as
UTC and not as local time, per **RFC 5280**.  Additionally, the return
value is always an "int". (Contributed by Akira Li in bpo-19940.)

New "SSLObject.shared_ciphers()" and "SSLSocket.shared_ciphers()"
methods return the list of ciphers sent by the client during the
handshake. (Contributed by Benjamin Peterson in bpo-23186.)

The "SSLSocket.do_handshake()", "SSLSocket.read()",
"SSLSocket.shutdown()", and "SSLSocket.write()" methods of the
"SSLSocket" class no longer reset the socket timeout every time bytes
are received or sent. The socket timeout is now the maximum total
duration of the method. (Contributed by Victor Stinner in bpo-23853.)

The "match_hostname()" function now supports matching of IP addresses.
(Contributed by Antoine Pitrou in bpo-23239.)


sqlite3
-------

The "Row" class now fully supports the sequence protocol, in
particular "reversed()" iteration and slice indexing. (Contributed by
Claudiu Popa in bpo-10203; by Lucas Sinclair, Jessica McKellar, and
Serhiy Storchaka in bpo-13583.)


subprocess
----------

新たに "run()" 関数が追加されました。 "run()" は指定されたコマンドを実
行し "CompletedProcess" オブジェクトを返します。 オブジェクトは終了し
たプロセスを記述します。 新たな API はより一貫的で、古いバージョンとの
互換性を必要としない Python コードでサブプロセスを起動するのに推奨され
る方法です。 (Contributed by Thomas Kluyver in bpo-23342.)

例:

   >>> subprocess.run(["ls", "-l"])  # doesn't capture output
   CompletedProcess(args=['ls', '-l'], returncode=0)

   >>> subprocess.run("exit 1", shell=True, check=True)
   Traceback (most recent call last):
     ...
   subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

   >>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
   CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
   stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')


sys
---

A new "set_coroutine_wrapper()" function allows setting a global hook
that will be called whenever a *coroutine object* is created by an
"async def" function.  A corresponding "get_coroutine_wrapper()" can
be used to obtain a currently set wrapper.  Both functions are
*provisional*, and are intended for debugging purposes only.
(Contributed by Yury Selivanov in bpo-24017.)

A new "is_finalizing()" function can be used to check if the Python
interpreter is *shutting down*. (Contributed by Antoine Pitrou in
bpo-22696.)


sysconfig
---------

The name of the user scripts directory on Windows now includes the
first two components of the Python version. (Contributed by Paul Moore
in bpo-23437.)


tarfile
-------

"open()" 関数の *mode* 引数が排他的作成を要求する ""x""  を受け取るよ
うになりました。 (Contributed by Berker Peksag in bpo-21717.)

The "TarFile.extractall()" and "TarFile.extract()" methods now take a
keyword argument *numeric_owner*.  If set to "True", the extracted
files and directories will be owned by the numeric "uid" and "gid"
from the tarfile. If set to "False" (the default, and the behavior in
versions prior to 3.5), they will be owned by the named user and group
in the tarfile. (Contributed by Michael Vogt and Eric Smith in
bpo-23193.)

The "TarFile.list()" now accepts an optional *members* keyword
argument that can be set to a subset of the list returned by
"TarFile.getmembers()". (Contributed by Serhiy Storchaka in
bpo-21549.)


threading
---------

"Lock.acquire()" と "RLock.acquire()" の両メソッドがタイムアウトの管理
に単調時計を使用するようになりました。 (Contributed by Victor Stinner
in bpo-22043.)


time
----

"monotonic()" 関数が常に利用出来るようになりました。 (Contributed by
Victor Stinner in bpo-22043.)


timeit
------

新たなコマンドラインオプション "-u" 又は "--unit=*U*" を使用してタイマ
ーの出力の単位を指定できます。 サポートされたオプションは "usec",
"msec",  "sec" です。 (Contributed by Julian Gindi in bpo-18983.)

"timeit()" 関数に引数 *globals* が追加されました。 これによりコードが
実行される名前空間を指定します。 (Contributed by Ben Roberts in
bpo-2527.)


tkinter
-------

The "tkinter._fix" module used for setting up the Tcl/Tk environment
on Windows has been replaced by a private function in the "_tkinter"
module which makes no permanent changes to environment variables.
(Contributed by Zachary Ware in bpo-20035.)


traceback
---------

New "walk_stack()" and "walk_tb()" functions to conveniently traverse
frame and traceback objects. (Contributed by Robert Collins in
bpo-17911.)

New lightweight classes: "TracebackException", "StackSummary", and
"FrameSummary". (Contributed by Robert Collins in bpo-17911.)

Both the "print_tb()" and "print_stack()" functions now support
negative values for the *limit* argument. (Contributed by Dmitry
Kazakov in bpo-22619.)


types
-----

新たに "coroutine()" 関数が追加されました。 *ジェネレータ* と "ジェネ
レータ様" オブジェクトを *awaitable* に変換します。 (Contributed by
Yury Selivanov in bpo-24017.)

新たに型 "CoroutineType" が追加されました。 "async def" 関数で作られた
*coroutine* オブジェクトに使われます。 (Contributed by Yury Selivanov
in bpo-24400.)


unicodedata
-----------

"unicodedata" モジュールは Unicode 8.0.0 のデータを使うようになりまし
た。


unittest
--------

The "TestLoader.loadTestsFromModule()" method now accepts a keyword-
only argument *pattern* which is passed to "load_tests" as the third
argument.  Found packages are now checked for "load_tests" regardless
of whether their path matches *pattern*, because it is impossible for
a package name to match the default pattern. (Contributed by Robert
Collins and Barry A. Warsaw in bpo-16662.)

Unittest discovery errors now are exposed in the "TestLoader.errors"
attribute of the "TestLoader" instance. (Contributed by Robert Collins
in bpo-19746.)

A new command line option "--locals" to show local variables in
tracebacks.  (Contributed by Robert Collins in bpo-22936.)


unittest.mock
-------------

"Mock" クラスは、次の改善が行われました。

* The class constructor has a new *unsafe* parameter, which causes
  mock objects to raise "AttributeError" on attribute names starting
  with ""assert"". (Contributed by Kushal Das in bpo-21238.)

* A new "Mock.assert_not_called()" method to check if the mock object
  was called. (Contributed by Kushal Das in bpo-21262.)

The "MagicMock" class now supports "__truediv__()", "__divmod__()" and
"__matmul__()" operators. (Contributed by Johannes Baiter in
bpo-20968, and Håkan Lövdahl in bpo-23581 and bpo-23568.)

It is no longer necessary to explicitly pass "create=True" to the
"patch()" function when patching builtin names. (Contributed by Kushal
Das in bpo-17660.)


urllib
------

A new "request.HTTPPasswordMgrWithPriorAuth" class allows HTTP Basic
Authentication credentials to be managed so as to eliminate
unnecessary "401" response handling, or to unconditionally send
credentials on the first request in order to communicate with servers
that return a "404" response instead of a "401" if the "Authorization"
header is not sent. (Contributed by Matej Cepl in bpo-19494 and Akshit
Khurana in bpo-7159.)

A new *quote_via* argument for the "parse.urlencode()" function
provides a way to control the encoding of query parts if needed.
(Contributed by Samwyse and Arnon Yaari in bpo-13866.)

The "request.urlopen()" function accepts an "ssl.SSLContext" object as
a *context* argument, which will be used for the HTTPS connection.
(Contributed by Alex Gaynor in bpo-22366.)

The "parse.urljoin()" was updated to use the **RFC 3986** semantics
for the resolution of relative URLs, rather than **RFC 1808** and
**RFC 2396**. (Contributed by Demian Brecht and Senthil Kumaran in
bpo-22118.)


wsgiref
-------

The *headers* argument of the "headers.Headers" class constructor is
now optional. (Contributed by Pablo Torres Navarrete and SilentGhost
in bpo-5800.)


xmlrpc
------

"client.ServerProxy" クラスが *コンテキストマネージャ* プロトコルをサ
ポートするようになりました。 (Contributed by Claudiu Popa in
bpo-20627.)

"client.ServerProxy" コンストラクタは任意の "ssl.SSLContext" インスタ
ンスを受け取るようになりました。 (Contributed by Alex Gaynor in
bpo-22960.)


xml.sax
-------

SAX パーサは "xmlreader.InputSource" オブジェクトの文字ストリームをサ
ポートしました。 (Contributed by Serhiy Storchaka in bpo-2175.)

"parseString()" が "str" インスタンスを受け取るようになりました。
(Contributed by Serhiy Storchaka in bpo-10590.)


zipfile
-------

ZIP output can now be written to unseekable streams. (Contributed by
Serhiy Storchaka in bpo-23252.)

"ZipFile.open()" メソッドの *mode* 引数が排他的作成を要求する ""x""
を受け取るようになりました。 (Contributed by Serhiy Storchaka in
bpo-21717.)


その他のモジュールレベルの変更
==============================

モジュール "mmap", "ossaudiodev", "socket", "ssl",  "codecs" 内の多く
の関数が、書き込み可能な *bytes 様オブジェクト* を受け付けるようになり
ました。 (Contributed by Serhiy Storchaka in bpo-23001.)


最適化
======

The "os.walk()" function has been sped up by 3 to 5 times on POSIX
systems, and by 7 to 20 times on Windows.  This was done using the new
"os.scandir()" function, which exposes file information from the
underlying "readdir" or "FindFirstFile"/"FindNextFile" system calls.
(Contributed by Ben Hoyt with help from Victor Stinner in bpo-23605.)

Construction of "bytes(int)" (filled by zero bytes) is faster and uses
less memory for large objects. "calloc()" is used instead of
"malloc()" to allocate memory for these objects. (Contributed by
Victor Stinner in bpo-21233.)

Some operations on "ipaddress" "IPv4Network" and "IPv6Network" have
been massively sped up, such as "subnets()", "supernet()",
"summarize_address_range()", "collapse_addresses()". The speed up can
range from 3 to 15 times. (Contributed by Antoine Pitrou, Michel
Albert, and Markus in bpo-21486, bpo-21487, bpo-20826, bpo-23266.)

Pickling of "ipaddress" objects was optimized to produce significantly
smaller output.  (Contributed by Serhiy Storchaka in bpo-23133.)

"io.BytesIO" の多くの操作が 50% から 100% 速くなりました。
(Contributed by Serhiy Storchaka in bpo-15381 and David Wilson in
bpo-22003.)

The "marshal.dumps()" function is now faster: 65--85% with versions 3
and 4, 20--25% with versions 0 to 2 on typical data, and up to 5 times
in best cases. (Contributed by Serhiy Storchaka in bpo-20416 and
bpo-23344.)

UTF-32 エンコーダが 3 から 7 倍速くなりました。 (Contributed by Serhiy
Storchaka in bpo-15027.)

正規表現のパースが最高で 10% 速くなりました。 (Contributed by Serhiy
Storchaka in bpo-19380.)

The "json.dumps()" function was optimized to run with
"ensure_ascii=False" as fast as with "ensure_ascii=True". (Contributed
by Naoki Inada in bpo-23206.)

The "PyObject_IsInstance()" and "PyObject_IsSubclass()" functions have
been sped up in the common case that the second argument has "type" as
its metaclass. (Contributed Georg Brandl by in bpo-22540.)

メソッドのキャッシュが少し改良されました。ベンチマークによっては性能が
最高で 5% 向上しました。 (Contributed by Antoine Pitrou in bpo-22847.)

"random" モジュールのオブジェクトのメモリ使用量が 64-bit ビルドで 50%
減少しました。 (Contributed by Serhiy Storchaka in bpo-23488.)

"property()" ゲッタの呼び出しが最高で 25% 速くなりました。
(Contributed by Joe Jevnik in bpo-23910.)

"fractions.Fraction" のインスタンス化が最高で 30% 速くなりました。
(Contributed by Stefan Behnel in bpo-22464.)

String methods "find()", "rfind()", "split()", "partition()" and the
"in" string operator are now significantly faster for searching
1-character substrings. (Contributed by Serhiy Storchaka in
bpo-23573.)


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

新たな "calloc" 関数が追加されました:

* "PyMem_RawCalloc()",

* "PyMem_Calloc()",

* "PyObject_Calloc()".

(Contributed by Victor Stinner in bpo-21233.)

新たなエンコーディング/デコーディングヘルパ関数:

* "Py_DecodeLocale()" ("_Py_char2wchar()" の代わり),

* "Py_EncodeLocale()" ("_Py_wchar2char()" の代わり).

(Contributed by Victor Stinner in bpo-18395.)

A new "PyCodec_NameReplaceErrors()" function to replace the unicode
encode error with "\N{...}" escapes. (Contributed by Serhiy Storchaka
in bpo-19676.)

A new "PyErr_FormatV()" function similar to "PyErr_Format()", but
accepts a "va_list" argument. (Contributed by Antoine Pitrou in
bpo-18711.)

A new "PyExc_RecursionError" exception. (Contributed by Georg Brandl
in bpo-19235.)

New "PyModule_FromDefAndSpec()", "PyModule_FromDefAndSpec2()", and
"PyModule_ExecDef()" functions introduced by **PEP 489** -- multi-
phase extension module initialization. (Contributed by Petr Viktorin
in bpo-24268.)

New "PyNumber_MatrixMultiply()" and "PyNumber_InPlaceMatrixMultiply()"
functions to perform matrix multiplication. (Contributed by Benjamin
Peterson in bpo-21176.  See also **PEP 465** for details.)

The "PyTypeObject.tp_finalize" slot is now part of the stable ABI.

Windows でのビルドには今では Microsoft Visual C++ 14.0 が必要です。
Visual Studio 2015 の一部として入手できます。

いくつかのプラットフォームにおいて、拡張モジュールのファイル名にプラッ
トフォームについての情報をタグとして含むようになりました (タグはオプシ
ョナルであり、CPython は、タグが含まれていて実行しようとしているプラッ
トフォームとミスマッチな場合にその拡張をロードしようとしない一方で、拡
張をそれが含まれていなくてもインポートします):

* Linux では拡張モジュールのファイル名は
  ".cpython-<major><minor>m-<architecture>-<os>.pyd" で終わります:

  * "<major>" は Python バージョンのメジャー番号です。Python 3.5 では
    "3" です。

  * "<minor>" は Python バージョンのマイナー番号です。Python 3.5 では
    "5" です。

  * "<architecture>" は拡張モジュールがどのハードウェアアーキテクチャ
    向けに動作するようビルドされたのかを表します。32-bit Intel プラッ
    トフォーム向けの "i386" か 64-bit Intel (及び AMD) プラットフォー
    ム向けの "x86_64" がもっとも一般的です。

  * "<os>" は原則として "linux-gnu" ですが、64-bit プラットフォームに
    おいて 32-bit ABI で動作するようビルドされた拡張モジュールの場合は
    "linux-gnu32" になります (この場合 "<architecture>" は "x86_64" と
    なるでしょう)。

* Windows では拡張モジュールのファイル名は
  "<debug>.cp<major><minor>-<platform>.pyd" で終わります:

  * "<major>" は Python バージョンのメジャー番号です。Python 3.5 では
    "3" です。

  * "<minor>" は Python バージョンのマイナー番号です。Python 3.5 では
    "5" です。

  * "<platform>" は拡張モジュールがどのプラットフォーム向けにビルドさ
    れたものなのかを表し、 Win32 用の "win32" , Win64 用の "win_amd64"
    , Windows Itanium 64 用の "win_ia64" , Windows on ARM 用の
    "win_arm" のいずれかです。

  * デバッグモードでビルドされた場合は "<debug>" は "_d" となり、それ
    以外の場合はブランクです。

* OS X プラットフォームでは拡張モジュールのファイル名は "-darwin.so"
  で終わります。

* 他のすべてのプラットフォームでは、拡張モジュールのファイル名は
  Python 3.4 でのものと同じです。


非推奨
======


新たなキーワード
----------------

"async" および "await" を変数、クラス、関数、ならびにモジュールの名前
に使用することは推奨されません。 それらは Python 3.5 で **PEP 492** に
より導入され、Python 3.7 で正式にキーワードになります。


非推奨の Python の挙動
----------------------

ジェネレータ内で "StopIteration" 例外を送出すると現在は静かな
"PendingDeprecationWarning" が発生します。 これは、Python 3.6 では静か
でない非推奨の警告となり、Python 3.7 では "RuntimeError" を起こします
。 詳細は PEP 479: Change StopIteration handling inside generators を
参照してください。


サポートされないオペレーティングシステム
----------------------------------------

Windows XP は Microsoft によって既にサポートされていません。このため
**PEP 11** により、CPython 3.5 ではこの OS をもはや公式にはサポートし
ません。


非推奨の Python モジュール、関数、メソッド
------------------------------------------

"formatter" モジュールは完全に非推奨になり、Python 3.6 で削除される予
定です。

"asyncio.async()" 関数は "ensure_future()" により非推奨になりました。

"smtpd" モジュールは過去において、常に email メッセージの DATA 部を
"utf-8" コーデックを使ってデコードしてきました。この振る舞いは今では
"SMTPServer" への新しい *decode_data* キーワード引数で制御出来ます。こ
の引数のデフォルトは "True" となっていますが、デフォルト値の使用は非推
奨です。この警告メッセージを避けるために *decode_data* の値として適切
な値を明示してください。

"http.cookies.Morsel" オブジェクトの "key", "value", "coded_value" に
対して直接代入することは非推奨です。 "set()" メソッドを使うようにして
ください。また、 "set()" のドキュメントされていなかった *LegalChars*
パラメータは非推奨となり、無視されます。

"string.Formatter" クラスの "format()" メソッドに対し、キーワード引数
*format_string* としてフォーマット文字列を渡すことは非推奨となりました
。 (Contributed by Serhiy Storchaka in bpo-23671.)

関数 "platform.dist()" と "platform.linux_distribution()" が非推奨とな
りました。Linux ディストリビューションが自分自身を記述する方法があまり
にも多様なため、この機能は外部パッケージに任せることとなりました(訳注:
ここでは distro のことを指している)。  (Contributed by Vajrasky Kok
and Berker Peksag in bpo-1322.)

"inspect.Signature" の、以前からドキュメントされていなかったメソッド
"from_function" と "from_builtin" は非推奨です。新しい
"Signature.from_callable()" を代わりに使ってください。 (Contributed by
Yury Selivanov in bpo-24248.)

"inspect.getargspec()" 関数は非推奨となり、Python 3.6 で削除されること
が予定されています。  (See bpo-20438 for details.)

The "inspect" "getfullargspec()", "getcallargs()", and
"formatargspec()" functions are deprecated in favor of the
"inspect.signature()" API. (Contributed by Yury Selivanov in
bpo-20438.)

"getargvalues()" and "formatargvalues()" functions were inadvertently
marked as deprecated with the release of Python 3.5.0.

str のパターンとともに "re.LOCALE" や "re.ASCII" フラグを使用すること
は非推奨となりました。  (Contributed by Serhiy Storchaka in
bpo-22407.)

"'\'" と ASCII 文字からなる認識出来ない特殊シーケンスが正規表現内と置
き換えパターン内で使われた場合に、非推奨警告を出すようになりました。
Python 3.6 では禁止されるようになります。 (Contributed by Serhiy
Storchaka in bpo-23622.)

"unittest.TestLoader.loadTestsFromModule()" メソッドのドキュメントされ
ておらず非公式の *use_load_tests* デフォルト引数は非推奨となり、無視さ
れます。 (Contributed by Robert Collins and Barry A. Warsaw in
bpo-16662.)


削除
====


API と機能の削除
----------------

時代遅れとなり、以前に既に非推奨となった以下の API と機能が削除されま
した:

* email パッケージの "__version__" 属性は削除されました。email パッケ
  ージが標準ライブラリとは別々にリリースされていたのは遥か昔の話であり
  、ここのところ何回かのリリースにいたっては "__version__" 文字列が更
  新されていませんでした。

* 3.4 で非推奨となっていた "ftplib" モジュール内の内部クラス "Netrc"
  が削除されました。 (Contributed by Matt Chaput in bpo-6623.)

* ".pyo" ファイルのコンセプトは削除されました。

* 暫定 "asyncio" モジュールで 3.4.4 で非推奨となった JoinableQueue は
  削除されました。 (Contributed by A. Jesse Jiryu Davis in bpo-23464.)


Python 3.5 への移植
===================

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


Python の挙動の変更
-------------------

* 以前のバージョンの Python で、誤って以下の構文を許容してしまっていま
  した:

     f(1 for x in [1], *args)
     f(1 for x in [1], **kwargs)

  Python 3.5 は正しく "SyntaxError" を投げます。ジェネレータ式は関数へ
  の唯一の引数でない場合には、括弧で囲まなければならないのです。(---訳
  注: 一応。3.5 以前も "ff(str(i) for i in range(5), "5")" は
  SyntaxError です。上の例の通り "gg(str(i) for i in range(5), *["1",
  "2"])" や "hh(str(i) for i in range(5), **{"k1": "1", "k2": "2"})"
  が SytaxError ではなかった、という話です。---)


Python API の変更
-----------------

* **PEP 475**: Python シグナルハンドラが例外を送出しなければ、システム
  コールがシグナルに中断された場合に、 "InterruptedError" を送出せずに
  システムコールを再試行するようになりました。

* Python 3.5 以前は、 "time" オブジェクトは UTC で深夜を表すときに偽と
  みなされていました。 この挙動は分かりにくく、エラーの元となると考え
  られ、Python 3.5 で削除されました。 全詳細については bpo-13936 を参
  照してください。

* "ssl.SSLSocket.send()" メソッドは非ブロッキングソケット使用時にオペ
  レーションがブロックされると、 "ssl.SSLWantReadError" か
  "ssl.SSLWantWriteError" のどちらかを送出するようになりました。以前は
  "0" を返していました。 (Contributed by Nikolaus Rath in bpo-20951.)

* ジェネレータの "__name__" 属性の値として、以前は code オブジェクトの
  名前から取っていましたが、関数名からセットされるようになりました。
  code の方が所望の場合は "gen.gi_code.co_name" から取得してください。
  ジェネレータは新たに "__qualname__" 属性も持つようになりました。これ
  はジェネレータの正規名であり、ジェネレータの表現をする際
  ("repr(gen)") にこれを用いるようになりました。 (Contributed by
  Victor Stinner in bpo-21205.)

* 非推奨だった "HTMLParser" の "strict" モードが削除されました。つまり
  ソースコード上から "HTMLParser" クラスの "strict" 引数、
  "HTMLParser.error()" メソッド、 "HTMLParserError" 例外が削除されまし
  た。 (Contributed by Ezio Melotti in bpo-15114.)  "HTMLParser" の
  *convert_charrefs* 引数のデフォルトが "True" となりました。
  (Contributed by Berker Peksag in bpo-21047.)

* API の公式な部分とは言えないものの、移植性への考慮のために (つまりテ
  ストの修正) に、エラーメッセージの変更に注意を払っておいてください。
  かつて "'sometype' does not support the buffer protocol" の形だった
  ものが、いまでは "a *bytes-like object* is required, not 'sometype'"
  の形になっています。 (Contributed by Ezio Melotti in bpo-16518.)

* 既に存在していないディレクトリをカレントディレクトリとして指していた
  場合に、 "find_spec()" は以前は "FileNotFoundError" 例外を送出してい
  ましたが、そうではなく "None" を返却するようになりました。この際
  "sys.path_importer_cache" に "None" を **キャッシュはしません** 。こ
  れは典型的なケースとは違います(訳注: msg231477)。 (bpo-22834)

* "http.client" モジュールと "http.server" モジュールに散らばっていた
  HTTP ステータスコードと対応するメッセージを、共通の "HTTPStatus"
  enum としてまとめ直しました。"http.client" 、 "http.server" にあった
  もとの値も後方互換性のために残してあります。 (Contributed by Demian
  Brecht in bpo-21793.)

* インポートローダが "importlib.machinery.Loader.exec_module()" を定義
  する場合は、同時に "create_module()" も定義されていることを要求する
  ように変更されました (今のところ "DeprecationWarning" となりますが、
  Python 3.6 ではエラーとなります)。ローダが "importlib.abc.Loader" を
  継承していれば特にこの変更の影響を受けることはありません。そうでない
  ならば、 "None" を返すだけの "create_module()" を定義してください。
  (Contributed by Brett Cannon in bpo-23014.)

* "re.split()" 関数は常に空のパターンマッチを無視してきました。ですか
  らパターン ""x*"" はパターン ""x+"" と同じように動作し、パターン
  ""\b"" は決して動作しませんでした。今後は "re.split()" はパターンが
  空文字列に合致しうる場合に警告を出します。互換性のためには空文字列と
  はマッチしえないパターンを使ってください(たとえば ""x*"" ではなく
  ""x+"" を使ってください)。空文字列としかマッチしえないパターン(例え
  ば ""\b"")はエラーとなります。 (Contributed by Serhiy Storchaka in
  bpo-22818.)

* "http.cookies.Morsel" 辞書風インターフェイスのそれ自身での一貫性を持
  たせるようにしました: morsel の比較に "key" と "value" を考慮するよ
  うにし、 "copy()" は "dict" を返さずに "Morsel" インスタンスを返すよ
  うにし、 "update()" は更新する辞書内のいずれかのキーが不正(訳注:
  **RFC 2109** として不正なキーのことで、update 以外のインターフェイス
  では変更前も拒絶される)であれば例外を投げるようにしています。加えて
  、ドキュメントされていない "set()" の *LegalChars* パラメータは非推
  奨となり、また指定しても無視されます。 (Contributed by Demian Brecht
  in bpo-2211.)

* **PEP 488** has removed ".pyo" files from Python and introduced the
  optional "opt-" tag in ".pyc" file names. The
  "importlib.util.cache_from_source()" has gained an *optimization*
  parameter to help control the "opt-" tag. Because of this, the
  *debug_override* parameter of the function is now deprecated. *.pyo*
  files are also no longer supported as a file argument to the Python
  interpreter and thus serve no purpose when distributed on their own
  (i.e. sourceless code distribution). Due to the fact that the magic
  number for bytecode has changed in Python 3.5, all old *.pyo* files
  from previous versions of Python are invalid regardless of this PEP.

* "socket" モジュールが、linux 3.6 以降で "CAN_RAW_FD_FRAMES" 定数をエ
  クスポートするようになりました。

* **RFC 5280** に基づき、 "ssl.cert_time_to_seconds()" 関数が入力の時
  刻をローカル時刻ではなく UTC として解釈するようになりました。また、
  戻り値は常に "int" となります。 (Contributed by Akira Li in
  bpo-19940.)

* "pygettext.py" ツールが POT-Creation-Date ヘッダ内のタイムゾーン形式
  として、標準の +NNNN 形式を使うようになりました。

* "smtplib" モジュールは以前はデバッグ出力のためにモジュールレベルの
  "stderr" 変数を使っていましたが、 "sys.stderr" を使うようになりまし
  た。もしもあなたの(テスト)プログラムが、そのデバッグ出力をキャプチャ
  するためにこのモジュールレベル変数に依存してたのであれば、今後は
  sys.stderr をキャプチャするようにする必要があります。

* "str.startswith()" と "str.endswith()" メソッドは空文字列を見つけた
  場合と完全に範囲外のインデクスが渡された場合に "True" を返すことはし
  なくなりました。  (Contributed by Serhiy Storchaka in bpo-24284.)

* "inspect.getdoc()" 関数が基底クラスから継承したドキュメンテーション
  文字列を返すようになりました。その継承したドキュメンテーション文字列
  が相応しいのであれば、もはやそれを繰り返して記述する必要はありません
  。継承されたそれを抑制するには、空の文字列を記述しなければなりません
  (もしくは然るべきドキュメンテーションを埋めれば良いです)。この変更は
  "pydoc" モジュールと "help()" 関数の出力に影響します。 (Contributed
  by Serhiy Storchaka in bpo-15582.)

* ネストされた "functools.partial()" 呼び出しは平坦化されるようになり
  ました。以前の振る舞いに依存していたのであれば "functools.partial()"
  オブジェクトに属性を追加するか、または "functools.partial()" をサブ
  クラス化することで出来ます。 (--訳注: 後半が意味がある内容を言ってる
  ようには思えません。「以前の振る舞い」とはおそらく "partial" オブジ
  ェクトの "func" 属性が functools.partial そのものになることを指して
  いて、「似たことをしたければ "partial" オブジェクトに別の属性を付け
  ればりゃいんじゃね?」程度の無責任な代替案を言ってるだけのような気が
  します。そもそも後者の「サブクラス化」は出来ないと思いますし。 --)
  (Contributed by Alexander Belopolsky in bpo-7830.)


C API の変更
------------

* "PyMemoryViewObject" 構造体の (非公開の) "format" メンバが削除されま
  した。 "memoryobject.h" 内のこの構造体に関係する部分に依存している全
  ての拡張は再ビルドしなければなりません。

* "PyMemAllocator" 構造体が "PyMemAllocatorEx" にリネームされた上で
  "calloc" フィールドが追加されました。

* ドキュメントされておらず、また、参照をリークしていた "PyObject_REPR"
  マクロが削除されました。オブジェクトの "repr()" をフォーマットするに
  は "PyUnicode_FromFormat()" 的な関数でフォーマット文字 "%R" を使って
  ください。(Contributed by Serhiy Storchaka in bpo-22453.)

* "__module__" 属性の欠落は pickle 化とイントロスペクションを壊してし
  まうので、 "__module__" 属性のない組み込み型で "DeprecationWarning"
  を引き起こすようにしました。将来これは "AttributeError" にするかもし
  れません。(Contributed by Serhiy Storchaka in bpo-20204.)

* **PEP 492** 実装の一部として、 "PyTypeObject" の "tp_reserved" スロ
  ットが "tp_as_async" スロットで置き換えられました。新しい型、構造体
  、関数については コルーチンオブジェクト を参照してください。


Notable changes in Python 3.5.4
===============================


New "make regen-all" build target
---------------------------------

To simplify cross-compilation, and to ensure that CPython can reliably
be compiled without requiring an existing version of Python to already
be available, the autotools-based build system no longer attempts to
implicitly recompile generated files based on file modification times.

Instead, a new "make regen-all" command has been added to force
regeneration of these files when desired (e.g. after an initial
version of Python has already been built based on the pregenerated
versions).

More selective regeneration targets are also defined - see
Makefile.pre.in for details.

(Victor Stinner の貢献による bpo-23404)

バージョン 3.5.4 で追加.


Removal of "make touch" build target
------------------------------------

The "make touch" build target previously used to request implicit
regeneration of generated files by updating their modification times
has been removed.

It has been replaced by the new "make regen-all" target.

(Victor Stinner の貢献による bpo-23404)

バージョン 3.5.4 で変更.
