"collections.abc" --- 컨테이너의 추상 베이스 클래스
***************************************************

버전 3.3에 추가: 이전에는, 이 모듈이 "collections" 모듈의 일부였습니다
.

**소스 코드:** Lib/_collections_abc.py

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

This module provides *abstract base classes* that can be used to test
whether a class provides a particular interface; for example, whether
it is *hashable* or whether it is a mapping.

An "issubclass()" or "isinstance()" test for an interface works in one
of three ways.

1) A newly written class can inherit directly from one of the abstract
base classes.  The class must supply the required abstract methods.
The remaining mixin methods come from inheritance and can be
overridden if desired.  Other methods may be added as needed:

   class C(Sequence):                      # Direct inheritance
       def __init__(self): ...             # Extra method not required by the ABC
       def __getitem__(self, index):  ...  # Required abstract method
       def __len__(self):  ...             # Required abstract method
       def count(self, value): ...         # Optionally override a mixin method

   >>> issubclass(C, Sequence)
   True
   >>> isinstance(C(), Sequence)
   True

2) Existing classes and built-in classes can be registered as "virtual
subclasses" of the ABCs.  Those classes should define the full API
including all of the abstract methods and all of the mixin methods.
This lets users rely on "issubclass()" or "isinstance()" tests to
determine whether the full interface is supported.  The exception to
this rule is for methods that are automatically inferred from the rest
of the API:

   class D:                                 # No inheritance
       def __init__(self): ...              # Extra method not required by the ABC
       def __getitem__(self, index):  ...   # Abstract method
       def __len__(self):  ...              # Abstract method
       def count(self, value): ...          # Mixin method
       def index(self, value): ...          # Mixin method

   Sequence.register(D)                     # Register instead of inherit

   >>> issubclass(D, Sequence)
   True
   >>> isinstance(D(), Sequence)
   True

In this example, class "D" does not need to define "__contains__",
"__iter__", and "__reversed__" because the in-operator, the
*iteration* logic, and the "reversed()" function automatically fall
back to using "__getitem__" and "__len__".

3) Some simple interfaces are directly recognizable by the presence of
the required methods (unless those methods have been set to "None"):

   class E:
       def __iter__(self): ...
       def __next__(next): ...

   >>> issubclass(E, Iterable)
   True
   >>> isinstance(E(), Iterable)
   True

Complex interfaces do not support this last technique because an
interface is more than just the presence of method names.  Interfaces
specify semantics and relationships between methods that cannot be
inferred solely from the presence of specific method names.  For
example, knowing that a class supplies "__getitem__", "__len__", and
"__iter__" is insufficient for distinguishing a "Sequence" from a
"Mapping".

버전 3.9에 추가: These abstract classes now support "[]". See 제네릭
에일리어스 형 and **PEP 585**.


Collections 추상 베이스 클래스
==============================

collections 모듈은 다음과 같은 *ABC*를 제공합니다:

+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| ABC                            | 상속                   | 추상 메서드             | 믹스인 메서드                                        |
|================================|========================|=========================|======================================================|
| "Container" [1]                |                        | "__contains__"          |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Hashable" [1]                 |                        | "__hash__"              |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Iterable" [1] [2]             |                        | "__iter__"              |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Iterator" [1]                 | "Iterable"             | "__next__"              | "__iter__"                                           |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Reversible" [1]               | "Iterable"             | "__reversed__"          |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Generator"  [1]               | "Iterator"             | "send", "throw"         | "close", "__iter__", "__next__"                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Sized"  [1]                   |                        | "__len__"               |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Callable"  [1]                |                        | "__call__"              |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Collection"  [1]              | "Sized", "Iterable",   | "__contains__",         |                                                      |
|                                | "Container"            | "__iter__", "__len__"   |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Sequence"                     | "Reversible",          | "__getitem__",          | "__contains__", "__iter__", "__reversed__", "index"  |
|                                | "Collection"           | "__len__"               | 및 "count"                                           |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "MutableSequence"              | "Sequence"             | "__getitem__",          | 상속된 "Sequence" 메서드와 "append", "reverse",      |
|                                |                        | "__setitem__",          | "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", "remove",      |
|                                |                        | "__iter__", "__len__",  | "__ior__", "__iand__", "__ixor__" 및 "__isub__"      |
|                                |                        | "add", "discard"        |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Mapping"                      | "Collection"           | "__getitem__",          | "__contains__", "keys", "items", "values", "get",    |
|                                |                        | "__iter__", "__len__"   | "__eq__" 및 "__ne__"                                 |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "MutableMapping"               | "Mapping"              | "__getitem__",          | 상속된 "Mapping" 메서드와 "pop", "popitem", "clear", |
|                                |                        | "__setitem__",          | "update" 및 "setdefault"                             |
|                                |                        | "__delitem__",          |                                                      |
|                                |                        | "__iter__", "__len__"   |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "MappingView"                  | "Sized"                |                         | "__len__"                                            |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "ItemsView"                    | "MappingView", "Set"   |                         | "__contains__", "__iter__"                           |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "KeysView"                     | "MappingView", "Set"   |                         | "__contains__", "__iter__"                           |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "ValuesView"                   | "MappingView",         |                         | "__contains__", "__iter__"                           |
|                                | "Collection"           |                         |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Awaitable" [1]                |                        | "__await__"             |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Coroutine" [1]                | "Awaitable"            | "send", "throw"         | "close"                                              |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "AsyncIterable" [1]            |                        | "__aiter__"             |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "AsyncIterator" [1]            | "AsyncIterable"        | "__anext__"             | "__aiter__"                                          |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "AsyncGenerator" [1]           | "AsyncIterator"        | "asend", "athrow"       | "aclose", "__aiter__", "__anext__"                   |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+

-[ Footnotes ]-

[1] These ABCs override "object.__subclasshook__()" to support testing
    an interface by verifying the required methods are present and
    have not been set to "None".  This only works for simple
    interfaces.  More complex interfaces require registration or
    direct subclassing.

[2] Checking "isinstance(obj, Iterable)" detects classes that are
    registered as "Iterable" or that have an "__iter__()" method, but
    it does not detect classes that iterate with the "__getitem__()"
    method.  The only reliable way to determine whether an object is
    *iterable* is to call "iter(obj)".


Collections Abstract Base Classes -- Detailed Descriptions
==========================================================

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__()" 메
   서드로 이터레이트 하는 클래스는 감지하지 않습니다. 객체가 *이터러블
   *인지를 확인하는 유일하게 신뢰성 있는 방법은 "iter(obj)"를 호출하는
   것입니다.

class collections.abc.Collection

   길이가 있는 이터러블 컨테이너 클래스의 ABC.

   버전 3.6에 추가.

class collections.abc.Iterator

   "__iter__()" 와 "__next__()" 메서드를 제공하는 클래스의 ABC. *이터
   레이터*의 정의도 참조하십시오.

class collections.abc.Reversible

   "__reversed__()" 메서드도 제공하는 이터러블 클래스의 ABC.

   버전 3.6에 추가.

class collections.abc.Generator

   "send()", "throw()" 및 "close()" 메서드로 이터레이터를 확장하는
   **PEP 342**에 정의된 프로토콜을 구현하는 제너레이터 클래스의 ABC. *
   제너레이터*의 정의도 참조하십시오.

   버전 3.5에 추가.

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

   읽기 전용과 가변 *시퀀스*의 ABC.

   구현 참고 사항: "__iter__()", "__reversed__()" 및 "index()"와 같은
   일부 믹스인(mixin) 메서드는 하부 "__getitem__()" 메서드를 반복적으
   로 호출합니다. 따라서, "__getitem__()"이 상수 액세스 속도로 구현되
   면 믹스인 메서드는 선형 성능을 갖습니다; 그러나 하부 메서드가 선형
   이면 (링크드 리스트에서처럼), 믹스인은 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" 표현식에서 사용할 수 있는 *어웨이터블* 객체의 ABC. 사용자
   정의 구현은 "__await__()" 메서드를 제공해야 합니다.

   *코루틴* 객체와 "Coroutine" ABC의 인스턴스는 모두 이 ABC의 인스턴스
   입니다.

   참고:

     CPython에서, 제너레이터 기반 코루틴("types.coroutine()"이나
     "asyncio.coroutine()"으로 데코레이트 된 제너레이터)은,
     "__await__()" 메서드가 없어도 *어웨이터블* 입니다. 이들에 대해
     "isinstance(gencoro, Awaitable)"를 사용하면 "False"가 반환됩니다.
     이들을 감지하려면 "inspect.isawaitable()"을 사용하십시오.

   버전 3.5에 추가.

class collections.abc.Coroutine

   코루틴 호환 클래스의 ABC. 코루틴 객체(Coroutine Objects)에 정의된
   다음 메서드를 구현합니다: "send()", "throw()" 및 "close()". 사용자
   정의 구현은 "__await__()"도 구현해야 합니다. 모든 "Coroutine" 인스
   턴스는 "Awaitable"의 인스턴스이기도 합니다. *코루틴*의 정의도 참조
   하십시오.

   참고:

     CPython에서, 제너레이터 기반 코루틴("types.coroutine()"이나
     "asyncio.coroutine()"으로 데코레이트 된 제너레이터)은,
     "__await__()" 메서드가 없어도 *어웨이터블* 입니다. 이들에 대해
     "isinstance(gencoro, Coroutine)"을 사용하면 "False"가 반환됩니다.
     이들을 감지하려면 "inspect.isawaitable()"을 사용하십시오.

   버전 3.5에 추가.

class collections.abc.AsyncIterable

   "__aiter__" 메서드를 제공하는 클래스의 ABC. *비동기 이터러블*의 정
   의도 참조하십시오.

   버전 3.5에 추가.

class collections.abc.AsyncIterator

   "__aiter__" 와 "__anext__" 메서드를 제공하는 클래스의 ABC. *비동기
   이터레이터*의 정의도 참조하십시오.

   버전 3.5에 추가.

class collections.abc.AsyncGenerator

   **PEP 525**와 **PEP 492**에 정의된 프로토콜을 구현하는 비동기 제너
   레이터 클래스의 ABC.

   버전 3.6에 추가.


Examples and Recipes
====================

ABCs allow us to ask classes or instances if they provide particular
functionality, for example:

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

ABC 중 일부는 믹스인으로도 유용하여 컨테이너 API를 지원하는 클래스를
쉽게 개발할 수 있게 합니다. 예를 들어, 전체 "Set" API를 지원하는 클래
스를 작성하려면, "__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"을 믹스인으로 사용할 때의 주의 사항:

1. 일부 집합 연산은 새로운 집합을 만들기 때문에, 기본 믹스인 메서드는
   이터러블로부터 새 인스턴스를 만드는 방법이 필요합니다. 클래스 생성
   자가 "ClassName(iterable)" 형식의 서명을 가진 것으로 가정합니다. 이
   가정은 새로운 집합을 생성하기 위해 "cls(iterable)"를 호출하는
   "_from_iterable()"이라는 내부 클래스 메서드로 분리되었습니다. "Set"
   믹스인이 다른 생성자 서명을 갖는 클래스에서 사용되고 있으면, 이터러
   블 인자로부터 새 인스턴스를 생성할 수 있는 클래스 메서드나 일반 메
   서드로 "_from_iterable()"을 재정의해야 합니다.

2. 비교를 재정의하려면 (의미는 고정되었으므로, 아마도 속도 때문에),
   "__le__()"와 "__ge__()"를 재정의하십시오, 그러면 다른 연산은 자동으
   로 맞춰집니다.

3. The "Set" mixin provides a "_hash()" method to compute a hash value
   for the set; however, "__hash__()" is not defined because not all
   sets are *hashable* or immutable.  To add set hashability using
   mixins, inherit from both "Set()" and "Hashable()", then define
   "__hash__ = Set._hash".

더 보기:

  * "MutableSet"으로 구축한 예제 OrderedSet 조리법.

  * ABC에 대한 자세한 내용은, "abc" 모듈과 **PEP 3119**를 참조하십시오
    .
