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

Added in version 3.3: 이전에는, 이 모듈이 "collections" 모듈의 일부였
습니다.

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

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

이 모듈은 클래스가 특정 인터페이스를 제공하는지를 검사하는 데 사용할
수 있는 *추상 베이스 클래스*를 제공합니다; 예를 들어, *해시 가능*인지
또는 *매핑*인지입니다.

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):                      # 직접 상속
          def __init__(self): ...             # ABC 가 요구하지 않는 추가 메서드
          def __getitem__(self, index):  ...  # 필수 추상 메서드
          def __len__(self):  ...             # 필수 추상 메서드
          def count(self, value): ...         # 선택적으로 믹스인 메서드를 재정의합니다

      >>> 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:                                 # 상속 없음
          def __init__(self): ...              # ABC 가 요구하지 않는 추가 메서드
          def __getitem__(self, index):  ...   # 추상 메서드
          def __len__(self):  ...              # 추상 메서드
          def count(self, value): ...          # 믹스인 메서드
          def index(self, value): ...          # 믹스인 메서드

      Sequence.register(D)                     # 상속하는 대신 등록합니다

      >>> 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__(self): ...

      >>> 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".

Added in version 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", "clear",        |
|                                |                        | "__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__",            |
|                                |                        |                         | "__rsub__", "__xor__", "__rxor__" 및 "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"                |                         | "__init__", "__len__" 및 "__repr__"                  |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "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__"                   |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+
| "Buffer" [1]                   |                        | "__buffer__"            |                                                      |
+--------------------------------+------------------------+-------------------------+------------------------------------------------------+

-[ 각주 ]-

[1] These ABCs override "__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] "isinstance(obj, Iterable)"를 검사하면 "Iterable"로 등록되었거나
    "__iter__()" 메서드가 있는 클래스를 감지하지만, "__getitem__()" 메
    서드로 이터레이트 하는 클래스는 감지하지 않습니다. 객체가 *이터러
    블*인지를 확인하는 유일하게 신뢰성 있는 방법은 "iter(obj)"를 호출
    하는 것입니다.


Collections 추상 베이스 클래스 -- 상세한 설명
=============================================

class collections.abc.Container

   "__contains__()" 메서드를 제공하는 클래스의 ABC.

class collections.abc.Hashable

   "__hash__()" 메서드를 제공하는 클래스의 ABC.

class collections.abc.Sized

   "__len__()" 메서드를 제공하는 클래스의 ABC.

class collections.abc.Callable

   "__call__()" 메서드를 제공하는 클래스의 ABC.

   See Annotating callable objects for details on how to use
   "Callable" in type annotations.

class collections.abc.Iterable

   "__iter__()" 메서드를 제공하는 클래스의 ABC.

   "isinstance(obj, Iterable)"를 검사하면 "Iterable"로 등록되었거나
   "__iter__()" 메서드가 있는 클래스를 감지하지만, "__getitem__()" 메
   서드로 이터레이트 하는 클래스는 감지하지 않습니다. 객체가 *이터러블
   *인지를 확인하는 유일하게 신뢰성 있는 방법은 "iter(obj)"를 호출하는
   것입니다.

class collections.abc.Collection

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

   Added in version 3.6.

class collections.abc.Iterator

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

class collections.abc.Reversible

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

   Added in version 3.6.

class collections.abc.Generator

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

   See Annotating generators and coroutines for details on using
   "Generator" in type annotations.

   Added in version 3.5.

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

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

   Implementation note: Some of the mixin methods, such as
   "__iter__()", "__reversed__()", and "index()" make repeated calls
   to the underlying "__getitem__()" method. Consequently, if
   "__getitem__()" is implemented with constant access speed, the
   mixin methods will have linear performance; however, if the
   underlying method is linear (as it would be with a linked list),
   the mixins will have quadratic performance and will likely need to
   be overridden.

   index(value, start=0, stop=None)

      Return first index of *value*.

      Raises "ValueError" if the value is not present.

      Supporting the *start* and *stop* arguments is optional, but
      recommended.

      버전 3.5에서 변경: The "index()" method gained support for the
      *stop* and *start* arguments.

   Deprecated since version 3.12, will be removed in version 3.17: The
   "ByteString" ABC has been deprecated.Use "isinstance(obj,
   collections.abc.Buffer)" to test if "obj" implements the buffer
   protocol at runtime. For use in type annotations, either use
   "Buffer" or a union that explicitly specifies the types your code
   supports (e.g., "bytes | bytearray | memoryview")."ByteString" was
   originally intended to be an abstract class that would serve as a
   supertype of both "bytes" and "bytearray". However, since the ABC
   never had any methods, knowing that an object was an instance of
   "ByteString" never actually told you anything useful about the
   object. Other common buffer types such as "memoryview" were also
   never understood as subtypes of "ByteString" (either at runtime or
   by static type checkers).See **PEP 688** for more details.

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의 인스턴스
   입니다.

   참고:

     In CPython, generator-based coroutines (*generators* decorated
     with "@types.coroutine") are *awaitables*, even though they do
     not have an "__await__()" method. Using "isinstance(gencoro,
     Awaitable)" for them will return "False". Use
     "inspect.isawaitable()" to detect them.

   Added in version 3.5.

class collections.abc.Coroutine

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

   참고:

     In CPython, generator-based coroutines (*generators* decorated
     with "@types.coroutine") are *awaitables*, even though they do
     not have an "__await__()" method. Using "isinstance(gencoro,
     Coroutine)" for them will return "False". Use
     "inspect.isawaitable()" to detect them.

   See Annotating generators and coroutines for details on using
   "Coroutine" in type annotations. The variance and order of type
   parameters correspond to those of "Generator".

   Added in version 3.5.

class collections.abc.AsyncIterable

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

   Added in version 3.5.

class collections.abc.AsyncIterator

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

   Added in version 3.5.

class collections.abc.AsyncGenerator

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

   See Annotating generators and coroutines for details on using
   "AsyncGenerator" in type annotations.

   Added in version 3.6.

class collections.abc.Buffer

   ABC for classes that provide the "__buffer__()" method,
   implementing the buffer protocol. See **PEP 688**.

   Added in version 3.12.


예제와 조리법
=============

ABC들은 클래스나 인스턴스가 특정 기능을 제공하는지 묻는 것을 허용합니
다, 예를 들어:

   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):
       ''' 속도보다 공간을 선호하고 집합 원소가
           해시 가능할 필요가 없는 대안 집합 구현. '''
       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            # __and__() 메서드는 자동으로 지원됩니다

"Set"과 "MutableSet"을 믹스인으로 사용할 때의 주의 사항:

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

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

3. "Set" 믹스인은 집합의 해시값을 계산하는 "_hash()" 메서드를 제공합니
   다; 그러나 모든 집합이 *해시 가능*하거나 불변이지는 않기 때문에
   "__hash__()"는 정의되지 않습니다. 믹스인을 사용하여 집합 해시 가능
   성을 추가하려면, "Set()"와 "Hashable()"을 모두 상속한 다음,
   "__hash__ = Set._hash"를 정의하십시오.

더 보기:

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

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