"collections.abc" --- コレクションの抽象基底クラス
**************************************************

バージョン 3.3 で追加: 以前はこのモジュールは "collections" モジュール
の一部でした。

**ソースコード:** Lib/_collections_abc.py

======================================================================

このモジュールは、 *抽象基底クラス* を提供します。抽象基底クラスは、ク
ラスが特定のインターフェースを提供しているか、例えばハッシュ可能である
かやマッピングであるかを判定します。

バージョン 3.9 で追加: These abstract classes now support "[]". See ジ
ェネリックエイリアス型 and **PEP 585**.


コレクション抽象基底クラス
==========================

collections モジュールは以下の *ABC (抽象基底クラス)* を提供します:

+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| ABC                        | 継承しているクラス     | 抽象メソッド            | mixin メソッド                                       |
|============================|========================|=========================|======================================================|
| "Container"                |                        | "__contains__"          |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Hashable"                 |                        | "__hash__"              |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Iterable"                 |                        | "__iter__"              |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Iterator"                 | "Iterable"             | "__next__"              | "__iter__"                                           |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Reversible"               | "Iterable"             | "__reversed__"          |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Generator"                | "Iterator"             | "send", "throw"         | "close", "__iter__", "__next__"                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Sized"                    |                        | "__len__"               |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Callable"                 |                        | "__call__"              |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Collection"               | "Sized", "Iterable",   | "__contains__",         |                                                      |
|                            | "Container"            | "__iter__", "__len__"   |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Sequence"                 | "Reversible",          | "__getitem__",          | "__contains__", "__iter__", "__reversed__", "index", |
|                            | "Collection"           | "__len__"               | "count"                                              |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "MutableSequence"          | "Sequence"             | "__getitem__",          | "Sequence" から継承したメソッドと、 "append",        |
|                            |                        | "__setitem__",          | "reverse", "extend", "pop", "remove", "__iadd__"     |
|                            |                        | "__delitem__",          |                                                      |
|                            |                        | "__len__", "insert"     |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "ByteString"               | "Sequence"             | "__getitem__",          | "Sequence" から継承したメソッド                      |
|                            |                        | "__len__"               |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Set"                      | "Collection"           | "__contains__",         | "__le__", "__lt__", "__eq__", "__ne__", "__gt__",    |
|                            |                        | "__iter__", "__len__"   | "__ge__", "__and__", "__or__", "__sub__", "__xor__", |
|                            |                        |                         | "isdisjoint"                                         |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "MutableSet"               | "Set"                  | "__contains__",         | "Set" から継承したメソッドと、 "clear", "pop",       |
|                            |                        | "__iter__", "__len__",  | "remove", "__ior__", "__iand__", "__ixor__",         |
|                            |                        | "add", "discard"        | "__isub__"                                           |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Mapping"                  | "Collection"           | "__getitem__",          | "__contains__", "keys", "items", "values", "get",    |
|                            |                        | "__iter__", "__len__"   | "__eq__", "__ne__"                                   |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "MutableMapping"           | "Mapping"              | "__getitem__",          | "Mapping" から継承したメソッドと、 "pop", "popitem", |
|                            |                        | "__setitem__",          | "clear", "update", "setdefault"                      |
|                            |                        | "__delitem__",          |                                                      |
|                            |                        | "__iter__", "__len__"   |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "MappingView"              | "Sized"                |                         | "__len__"                                            |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "ItemsView"                | "MappingView", "Set"   |                         | "__contains__", "__iter__"                           |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "KeysView"                 | "MappingView", "Set"   |                         | "__contains__", "__iter__"                           |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "ValuesView"               | "MappingView",         |                         | "__contains__", "__iter__"                           |
|                            | "Collection"           |                         |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Awaitable"                |                        | "__await__"             |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Coroutine"                | "Awaitable"            | "send", "throw"         | "close"                                              |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "AsyncIterable"            |                        | "__aiter__"             |                                                      |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "AsyncIterator"            | "AsyncIterable"        | "__anext__"             | "__aiter__"                                          |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+
| "AsyncGenerator"           | "AsyncIterator"        | "asend", "athrow"       | "aclose", "__aiter__", "__anext__"                   |
+----------------------------+------------------------+-------------------------+------------------------------------------------------+

class collections.abc.Container

   "__contains__()" メソッドを提供するクラスの ABC です。

class collections.abc.Hashable

   "__hash__()" メソッドを提供するクラスの ABC です。

class collections.abc.Sized

   "__len__()" メソッドを提供するクラスの ABC です。

class collections.abc.Callable

   "__call__()" メソッドを提供するクラスの ABC です。

class collections.abc.Iterable

   "__iter__()" メソッドを提供するクラスの ABC です。

   メソッド "isinstance(obj, Iterable)" で使用すると、 "Iterable" や
   "__iter__()" メソッドを持っているクラスを検出できます。しかし、
   "__getitem__()" メソッドで反復するクラスは検出しません。 オブジェク
   トが *iterable* であるかどうかを判別するにあたって、信頼できる唯一
   の方法は "iter(obj)" を呼び出す方法です。

class collections.abc.Collection

   サイズ付きのイテラブルなコンテナクラスの ABC です。

   バージョン 3.6 で追加.

class collections.abc.Iterator

   "__iter__()" メソッドと "__next__()" メソッドを提供するクラスの ABC
   です。 *iterator* の定義も参照してください。

class collections.abc.Reversible

   "__reversed__()" メソッドを提供するイテラブルクラスの ABC です。

   バージョン 3.6 で追加.

class collections.abc.Generator

   **PEP 342** で定義された、イテレータを "send()", "throw()",
   "close()" の各メソッドに拡張するプロトコルを実装する、ジェネレータ
   クラスの ABC です。*generator* の定義も参照してください。

   バージョン 3.5 で追加.

class collections.abc.Sequence
class collections.abc.MutableSequence
class collections.abc.ByteString

   読み出し専用の *シーケンス* およびミュータブルな *シーケンス* の
   ABC です。

   実装における注意: "__iter__()", "__reversed__()", "index()" など、
   一部の mixin メソッドは、下層の "__getitem__()" メソッドを繰り返し
   呼び出します。その結果、"__getitem__()" が定数のアクセス速度で実装
   されている場合、mixin メソッドは線形のパフォーマンスとなります。下
   層のメソッドが線形 (リンクされたリストの場合など) の場合、mixin は
   2 乗のパフォーマンスとなるため、多くの場合上書きする必要があるでし
   ょう。

   バージョン 3.5 で変更: index() メソッドは *stop* と *start* 引数を
   サポートしました。

class collections.abc.Set
class collections.abc.MutableSet

   読み出し専用の集合およびミュータブルな集合の ABC です。

class collections.abc.Mapping
class collections.abc.MutableMapping

   読み出し専用の *マッピング* およびミュータブルな *マッピング* の
   ABC です。

class collections.abc.MappingView
class collections.abc.ItemsView
class collections.abc.KeysView
class collections.abc.ValuesView

   マッピング、要素、キー、値の *ビュー* の ABC です。

class collections.abc.Awaitable

   "await" で使用できる *awaitable* オブジェクトの ABC です。カスタム
   の実装は、"__await__()" メソッドを提供しなければなりません。

   "Coroutine" ABC の *Coroutine* オブジェクトとインスタンスは、すべて
   この ABC のインスタンスです。

   注釈:

     CPython では、ジェネレータベースのコルーチン ("types.coroutine()"
     または "asyncio.coroutine()" でデコレートされたジェネレータ) は、
     "__await__()" メソッドを持ちませんが、待機可能 (*awaitables*) で
     す。これらに対して "isinstance(gencoro, Awaitable)" を使用すると
     、 "False" が返されます。これらを検出するには、
     "inspect.isawaitable()" を使用します。

   バージョン 3.5 で追加.

class collections.abc.Coroutine

   コルーチンと互換性のあるクラスの ABC です。これらは、コルーチンオブ
   ジェクト で定義された "send()", "throw()", "close()" のメソッドを実
   装します。カスタムの実装は、"__await__()" も実装しなければなりませ
   ん。"Coroutine" のすべてのインスタンスは、 "Awaitable" のインスタン
   スでもあります。*coroutine* の定義も参照してください。

   注釈:

     CPython では、ジェネレータベースのコルーチン ("types.coroutine()"
     または "asyncio.coroutine()" でデコレートされたジェネレータ) は、
     "__await__()" メソッドを持ちませんが、待機可能 (*awaitables*) で
     す。これらに対して "isinstance(gencoro, Coroutine)" を使用すると
     、 "False" が返されます。これらを検出するには、
     "inspect.isawaitable()" を使用します。

   バージョン 3.5 で追加.

class collections.abc.AsyncIterable

   "__aiter__" メソッドを提供するクラスの ABC です。*asynchronous
   iterable* の定義も参照してください。

   バージョン 3.5 で追加.

class collections.abc.AsyncIterator

   "__aiter__" および "__anext__" メソッドを提供するクラスの ABC です
   。*asynchronous iterator* の定義も参照してください。

   バージョン 3.5 で追加.

class collections.abc.AsyncGenerator

   **PEP 525** と **PEP 492** に定義されているプロトコルを実装した非同
   期ジェネレータクラスの ABC です。

   バージョン 3.6 で追加.

これらの ABC はクラスやインスタンスが特定の機能を提供しているかどうか
を調べるのに使えます。例えば:

   size = None
   if isinstance(myvar, collections.abc.Sized):
       size = len(myvar)

幾つかの ABC はコンテナ型 API を提供するクラスを開発するのを助ける
mixin 型としても使えます。例えば、 "Set" API を提供するクラスを作る場
合、3つの基本になる抽象メソッド "__contains__()", "__iter__()",
"__len__()" だけが必要です。ABC が残りの "__and__()" や "isdisjoint()"
といったメソッドを提供します:

   class ListBasedSet(collections.abc.Set):
       ''' Alternate set implementation favoring space over speed
           and not requiring the set elements to be hashable. '''
       def __init__(self, iterable):
           self.elements = lst = []
           for value in iterable:
               if value not in lst:
                   lst.append(value)

       def __iter__(self):
           return iter(self.elements)

       def __contains__(self, value):
           return value in self.elements

       def __len__(self):
           return len(self.elements)

   s1 = ListBasedSet('abcdef')
   s2 = ListBasedSet('defghi')
   overlap = s1 & s2            # The __and__() method is supported automatically

"Set" と "MutableSet" を mixin 型として利用するときの注意点:

1. 幾つかの set の操作は新しい set を作るので、デフォルトの mixin メソ
   ッドは iterable から新しいインスタンスを作成する方法を必要とします
   。クラスのコンストラクタは "ClassName(iterable)" の形のシグネチャを
   持つと仮定されます。内部の "_from_iterable()" というクラスメソッド
   が "cls(iterable)" を呼び出して新しい set を作る部分でこの仮定が使
   われています。コンストラクタのシグネチャが異なるクラスで "Set" を使
   う場合は、 iterable 引数から新しいインスタンスを生成できるクラスメ
   ソッドあるいは仕様に沿ったメソッドで "_from_iterable()" をオーバー
   ライドする必要があります。

2. (たぶん意味はそのままに速度を向上する目的で)比較をオーバーライドす
   る場合、 "__le__()" と "__ge__()" だけを再定義すれば、その他の演算
   は自動的に追随します。

3. "Set" mixin型は set のハッシュ値を計算する "_hash()" メソッドを提供
   しますが、すべての set が hashable や immutable とは限らないので、
   "__hash__()" は提供しません。 mixin を使ってハッシュ可能な set を作
   る場合は、 "Set" と "Hashable" の両方を継承して、 "__hash__ =
   Set._hash" と定義してください。

参考:

  * "MutableSet" を使った例として OrderedSet recipe。

  * ABCs についての詳細は、 "abc" モジュールと **PEP 3119** を参照して
    ください。
