collections.abc --- 容器的抽象基类

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):                      # 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 GenericAlias 类型 and PEP 585.

容器抽象基类

这个容器模块提供了以下 ABCs:

抽象基类

继承自

抽象方法

Mixin 方法

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, Container

__contains__, __iter__, __len__

Sequence

Reversible, Collection

__getitem__, __len__

__contains__, __iter__, __reversed__, index, and count

MutableSequence

Sequence

__getitem__, __setitem__, __delitem__, __len__, insert

继承自 Sequence 的方法,以及 append, reverse, extend, pop, remove,和 __iadd__

ByteString

Sequence

__getitem__, __len__

继承自 Sequence 的方法

Set

Collection

__contains__, __iter__, __len__

__le__, __lt__, __eq__, __ne__, __gt__, __ge__, __and__, __or__, __sub__, __xor__, and isdisjoint

MutableSet

Set

__contains__, __iter__, __len__, add, discard

继承自 Set 的方法以及 clear, pop, remove, __ior__, __iand__, __ixor__,和 __isub__

Mapping

Collection

__getitem__, __iter__, __len__

__contains__, keys, items, values, get, __eq__, and __ne__

MutableMapping

Mapping

__getitem__, __setitem__, __delitem__, __iter__, __len__

继承自 Mapping 的方法以及 pop, popitem, clear, update,和 setdefault

MappingView

Sized

__len__

ItemsView

MappingView, Set

__contains__, __iter__

KeysView

MappingView, Set

__contains__, __iter__

ValuesView

MappingView, Collection

__contains__, __iter__

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(1,2,3,4,5,6,7,8,9,10,11,12,13,14)

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__() 方法的抽象基类。

class collections.abc.Hashable

提供了 __hash__() 方法的抽象基类。

class collections.abc.Sized

提供了 __len__() 方法的抽象基类。

class collections.abc.Callable

提供了 __call__() 方法的抽象基类。

class collections.abc.Iterable

提供了 __iter__() 方法的抽象基类。

使用 isinstance(obj, Iterable) 可以检测一个类是否已经注册到了 Iterable 或者实现了 __iter__() 函数,但是无法检测这个类是否能够使用 __getitem__() 方法进行迭代。检测一个对象是否是 iterable 的唯一可信赖的方法是调用 iter(obj)

class collections.abc.Collection

集合了 Sized 和 Iterable 类的抽象基类。

3.6 新版功能.

class collections.abc.Iterator

提供了 __iter__()__next__() 方法的抽象基类。参见 iterator 的定义。

class collections.abc.Reversible

为可迭代类提供了 __reversed__() 方法的抽象基类。

3.6 新版功能.

class collections.abc.Generator

生成器类,实现了 PEP 342 中定义的协议,继承并扩展了迭代器,提供了 send(), throw()close() 方法。参见 generator 的定义。

3.5 新版功能.

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

只读且可变的序列 sequences 的抽象基类。

实现笔记:一些混入(Maxin)方法比如 __iter__(), __reversed__()index() 会重复调用底层的 __getitem__() 方法。因此,如果实现的 __getitem__() 是常数级访问速度,那么相应的混入方法会有一个线性的表现;然而,如果底层方法是线性实现(例如链表),那么混入方法将会是平方级的表现,这也许就需要被重构了。

在 3.5 版更改: index() 方法支持 stopstart 参数。

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

只读且可变的集合的抽象基类。

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

只读且可变的映射 mappings 的抽象基类。

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

映射及其键和值的视图 views 的抽象基类。

class collections.abc.Awaitable

为可等待对象 awaitable 提供的类,可以被用于 await 表达式中。习惯上必须实现 __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.

3.5 新版功能.

class collections.abc.Coroutine

用于协程兼容类的抽象基类。实现了如下定义在 协程对象: 里的方法: send()throw()close()。通常的实现里还需要实现 __await__() 方法。所有的 Coroutine 实例都必须是 Awaitable 实例。参见 coroutine 的定义。

备注

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.

3.5 新版功能.

class collections.abc.AsyncIterable

提供了 __aiter__ 方法的抽象基类。参见 asynchronous iterable 的定义。

3.5 新版功能.

class collections.abc.AsyncIterator

提供了 __aiter____anext__ 方法的抽象基类。参见 asynchronous iterator 的定义。

3.5 新版功能.

class collections.abc.AsyncGenerator

为异步生成器类提供的抽象基类,这些类实现了定义在 PEP 525PEP 492 里的协议。

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)

有些抽象基类也可以用作混入类(mixin),这可以更容易地开发支持容器 API 的类。例如,要写一个支持完整 Set API 的类,只需要提供下面这三个方法: __contains__(), __iter__()__len__()。抽象基类会补充上其余的方法,比如 __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

当把 SetMutableSet 用作混入类时需注意:

  1. 由于某些集合操作会创建新集合,默认的混入方法需要一种从可迭代对象里创建新实例的方式。 假定类构造器具有 ClassName(iterable) 形式的签名。 这样它将执行一个名为 _from_iterable() 的内部类方法,该方法会调用 cls(iterable) 来产生一个新集合。 如果 Set 混入类在具有不同构造器签名的类中被使用,你将需要通过类方法或常规方法来重载 _from_iterable(),以便基于可迭代对象参数来构造新的实例。

  2. 重载比较符时时(想必是为了速度,因为其语义都是固定的),只需要重定义 __le__()__ge__() 函数,然后其他的操作会自动跟进。

  3. 混入集合类 Set 提供了一个 _hash() 方法为集合计算哈希值,然而, __hash__() 函数却没有被定义,因为并不是所有集合都是可哈希并且不可变的。为了使用混入类为集合添加哈希能力,可以同时继承 Set()Hashable() 类,然后定义 __hash__ = Set._hash

参见