blob: 58b03b9bd76804226c664328071a0a2312b036fa [file] [log] [blame]
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001:mod:`collections.abc` --- Abstract Base Classes for Containers
2===============================================================
3
4.. module:: collections.abc
5 :synopsis: Abstract base classes for containers
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Raymond Hettinger158c9c22011-02-22 00:41:50 +00007.. moduleauthor:: Raymond Hettinger <python at rcn.com>
8.. sectionauthor:: Raymond Hettinger <python at rcn.com>
9
Éric Araujob389eec2011-08-16 19:10:24 +020010.. versionadded:: 3.3
11 Formerly, this module was part of the :mod:`collections` module.
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013**Source code:** :source:`Lib/_collections_abc.py`
14
Raymond Hettinger158c9c22011-02-22 00:41:50 +000015.. testsetup:: *
16
17 from collections import *
18 import itertools
19 __name__ = '<doctest>'
20
Raymond Hettinger158c9c22011-02-22 00:41:50 +000021--------------
22
23This module provides :term:`abstract base classes <abstract base class>` that
24can be used to test whether a class provides a particular interface; for
25example, whether it is hashable or whether it is a mapping.
26
Raymond Hettinger158c9c22011-02-22 00:41:50 +000027
Éric Araujof90112e2011-06-03 19:18:41 +020028.. _collections-abstract-base-classes:
Raymond Hettinger158c9c22011-02-22 00:41:50 +000029
30Collections Abstract Base Classes
31---------------------------------
32
Ezio Melottic831a912011-03-28 19:27:09 +030033The collections module offers the following :term:`ABCs <abstract base class>`:
Raymond Hettinger158c9c22011-02-22 00:41:50 +000034
Georg Brandl44ea77b2013-03-28 13:28:44 +010035.. tabularcolumns:: |l|L|L|L|
36
Yury Selivanovf3e40fa2015-05-21 11:50:30 -040037========================== ====================== ======================= ====================================================
Ezio Melottic831a912011-03-28 19:27:09 +030038ABC Inherits from Abstract Methods Mixin Methods
Yury Selivanovf3e40fa2015-05-21 11:50:30 -040039========================== ====================== ======================= ====================================================
Raymond Hettinger158c9c22011-02-22 00:41:50 +000040:class:`Container` ``__contains__``
41:class:`Hashable` ``__hash__``
42:class:`Iterable` ``__iter__``
43:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
Guido van Rossum16ca06b2016-04-04 10:59:29 -070044:class:`Reversible` :class:`Iterable` ``__reversed__``
Raymond Hettingerbd60e8d2015-05-09 01:07:23 -040045:class:`Generator` :class:`Iterator` ``send``, ``throw`` ``close``, ``__iter__``, ``__next__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000046:class:`Sized` ``__len__``
47:class:`Callable` ``__call__``
Guido van Rossumf0666942016-08-23 10:47:07 -070048:class:`Collection` :class:`Sized`, ``__contains__``,
49 :class:`Iterable`, ``__iter__``,
50 :class:`Container` ``__len__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000051
Guido van Rossumf0666942016-08-23 10:47:07 -070052:class:`Sequence` :class:`Reversible`, ``__getitem__``, ``__contains__``, ``__iter__``, ``__reversed__``,
53 :class:`Collection` ``__len__`` ``index``, and ``count``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000054
Raymond Hettinger3ddba162013-03-23 09:07:36 -070055:class:`MutableSequence` :class:`Sequence` ``__getitem__``, Inherited :class:`Sequence` methods and
56 ``__setitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
57 ``__delitem__``, ``remove``, and ``__iadd__``
58 ``__len__``,
59 ``insert``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000060
Brett Cannon9305bba2016-07-15 12:16:18 -070061:class:`ByteString` :class:`Sequence` ``__getitem__``, Inherited :class:`Sequence` methods
62 ``__len__``
63
Guido van Rossumf0666942016-08-23 10:47:07 -070064:class:`Set` :class:`Collection` ``__contains__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
65 ``__iter__``, ``__gt__``, ``__ge__``, ``__and__``, ``__or__``,
66 ``__len__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000067
Raymond Hettinger3ddba162013-03-23 09:07:36 -070068:class:`MutableSet` :class:`Set` ``__contains__``, Inherited :class:`Set` methods and
69 ``__iter__``, ``clear``, ``pop``, ``remove``, ``__ior__``,
70 ``__len__``, ``__iand__``, ``__ixor__``, and ``__isub__``
71 ``add``,
72 ``discard``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000073
Guido van Rossumf0666942016-08-23 10:47:07 -070074:class:`Mapping` :class:`Collection` ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``,
75 ``__iter__``, ``get``, ``__eq__``, and ``__ne__``
76 ``__len__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000077
Raymond Hettinger3ddba162013-03-23 09:07:36 -070078:class:`MutableMapping` :class:`Mapping` ``__getitem__``, Inherited :class:`Mapping` methods and
79 ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
80 ``__delitem__``, and ``setdefault``
81 ``__iter__``,
82 ``__len__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000083
84
85:class:`MappingView` :class:`Sized` ``__len__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000086:class:`ItemsView` :class:`MappingView`, ``__contains__``,
87 :class:`Set` ``__iter__``
Ezio Melottic831a912011-03-28 19:27:09 +030088:class:`KeysView` :class:`MappingView`, ``__contains__``,
89 :class:`Set` ``__iter__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000090:class:`ValuesView` :class:`MappingView` ``__contains__``, ``__iter__``
Yury Selivanovf3e40fa2015-05-21 11:50:30 -040091:class:`Awaitable` ``__await__``
Yury Selivanov56fc6142015-05-29 09:01:29 -040092:class:`Coroutine` :class:`Awaitable` ``send``, ``throw`` ``close``
Yury Selivanovf3e40fa2015-05-21 11:50:30 -040093:class:`AsyncIterable` ``__aiter__``
94:class:`AsyncIterator` :class:`AsyncIterable` ``__anext__`` ``__aiter__``
Yury Selivanov22214ab2016-11-16 18:25:04 -050095:class:`AsyncGenerator` :class:`AsyncIterator` ``asend``, ``athrow`` ``aclose``, ``__aiter__``, ``__anext__``
Yury Selivanovf3e40fa2015-05-21 11:50:30 -040096========================== ====================== ======================= ====================================================
Raymond Hettinger158c9c22011-02-22 00:41:50 +000097
Ezio Melottic831a912011-03-28 19:27:09 +030098
99.. class:: Container
100 Hashable
101 Sized
102 Callable
103
104 ABCs for classes that provide respectively the methods :meth:`__contains__`,
105 :meth:`__hash__`, :meth:`__len__`, and :meth:`__call__`.
106
107.. class:: Iterable
108
109 ABC for classes that provide the :meth:`__iter__` method.
110 See also the definition of :term:`iterable`.
111
Guido van Rossumf0666942016-08-23 10:47:07 -0700112.. class:: Collection
113
114 ABC for sized iterable container classes.
115
116 .. versionadded:: 3.6
117
Ezio Melottic831a912011-03-28 19:27:09 +0300118.. class:: Iterator
119
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300120 ABC for classes that provide the :meth:`~iterator.__iter__` and
121 :meth:`~iterator.__next__` methods. See also the definition of
122 :term:`iterator`.
Ezio Melottic831a912011-03-28 19:27:09 +0300123
Guido van Rossum16ca06b2016-04-04 10:59:29 -0700124.. class:: Reversible
125
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700126 ABC for iterable classes that also provide the :meth:`__reversed__`
127 method.
Guido van Rossum16ca06b2016-04-04 10:59:29 -0700128
Georg Brandld2be07e2016-04-18 07:25:54 +0200129 .. versionadded:: 3.6
130
Raymond Hettingerbd60e8d2015-05-09 01:07:23 -0400131.. class:: Generator
132
133 ABC for generator classes that implement the protocol defined in
134 :pep:`342` that extends iterators with the :meth:`~generator.send`,
135 :meth:`~generator.throw` and :meth:`~generator.close` methods.
136 See also the definition of :term:`generator`.
137
138 .. versionadded:: 3.5
139
Ezio Melottic831a912011-03-28 19:27:09 +0300140.. class:: Sequence
141 MutableSequence
Brett Cannon9305bba2016-07-15 12:16:18 -0700142 ByteString
Ezio Melottic831a912011-03-28 19:27:09 +0300143
144 ABCs for read-only and mutable :term:`sequences <sequence>`.
145
Raymond Hettingerec219ba2015-05-22 19:29:22 -0700146 Implementation note: Some of the mixin methods, such as
147 :meth:`__iter__`, :meth:`__reversed__` and :meth:`index`, make
148 repeated calls to the underlying :meth:`__getitem__` method.
149 Consequently, if :meth:`__getitem__` is implemented with constant
150 access speed, the mixin methods will have linear performance;
151 however, if the underlying method is linear (as it would be with a
152 linked list), the mixins will have quadratic performance and will
153 likely need to be overridden.
154
155 .. versionchanged:: 3.5
156 The index() method added support for *stop* and *start*
157 arguments.
158
Ezio Melottic831a912011-03-28 19:27:09 +0300159.. class:: Set
160 MutableSet
161
162 ABCs for read-only and mutable sets.
163
164.. class:: Mapping
165 MutableMapping
166
167 ABCs for read-only and mutable :term:`mappings <mapping>`.
168
169.. class:: MappingView
170 ItemsView
171 KeysView
172 ValuesView
173
Martin Panter85b8f452015-10-07 09:56:46 +0000174 ABCs for mapping, items, keys, and values :term:`views <dictionary view>`.
Ezio Melottic831a912011-03-28 19:27:09 +0300175
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400176.. class:: Awaitable
177
Yury Selivanov66f88282015-06-24 11:04:15 -0400178 ABC for :term:`awaitable` objects, which can be used in :keyword:`await`
179 expressions. Custom implementations must provide the :meth:`__await__`
180 method.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400181
Yury Selivanov66f88282015-06-24 11:04:15 -0400182 :term:`Coroutine` objects and instances of the
183 :class:`~collections.abc.Coroutine` ABC are all instances of this ABC.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400184
Yury Selivanovcc1d0282015-07-01 12:49:00 -0400185 .. note::
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400186 In CPython, generator-based coroutines (generators decorated with
187 :func:`types.coroutine` or :func:`asyncio.coroutine`) are
188 *awaitables*, even though they do not have an :meth:`__await__` method.
189 Using ``isinstance(gencoro, Awaitable)`` for them will return ``False``.
190 Use :func:`inspect.isawaitable` to detect them.
Yury Selivanovcc1d0282015-07-01 12:49:00 -0400191
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400192 .. versionadded:: 3.5
193
194.. class:: Coroutine
195
Yury Selivanov66f88282015-06-24 11:04:15 -0400196 ABC for coroutine compatible classes. These implement the
197 following methods, defined in :ref:`coroutine-objects`:
198 :meth:`~coroutine.send`, :meth:`~coroutine.throw`, and
199 :meth:`~coroutine.close`. Custom implementations must also implement
200 :meth:`__await__`. All :class:`Coroutine` instances are also instances of
Yury Selivanov56fc6142015-05-29 09:01:29 -0400201 :class:`Awaitable`. See also the definition of :term:`coroutine`.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400202
Yury Selivanovcc1d0282015-07-01 12:49:00 -0400203 .. note::
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400204 In CPython, generator-based coroutines (generators decorated with
205 :func:`types.coroutine` or :func:`asyncio.coroutine`) are
206 *awaitables*, even though they do not have an :meth:`__await__` method.
207 Using ``isinstance(gencoro, Coroutine)`` for them will return ``False``.
208 Use :func:`inspect.isawaitable` to detect them.
Yury Selivanovcc1d0282015-07-01 12:49:00 -0400209
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400210 .. versionadded:: 3.5
211
212.. class:: AsyncIterable
213
214 ABC for classes that provide ``__aiter__`` method. See also the
215 definition of :term:`asynchronous iterable`.
216
217 .. versionadded:: 3.5
218
219.. class:: AsyncIterator
220
221 ABC for classes that provide ``__aiter__`` and ``__anext__``
222 methods. See also the definition of :term:`asynchronous iterator`.
223
224 .. versionadded:: 3.5
225
Berker Peksag61d9c862016-11-25 17:31:27 +0300226.. class:: AsyncGenerator
Yury Selivanov22214ab2016-11-16 18:25:04 -0500227
228 ABC for asynchronous generator classes that implement the protocol
229 defined in :pep:`525` and :pep:`492`.
230
231 .. versionadded:: 3.6
232
Ezio Melottic831a912011-03-28 19:27:09 +0300233
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000234These ABCs allow us to ask classes or instances if they provide
235particular functionality, for example::
236
237 size = None
Georg Brandl5f4b4ac2013-04-14 10:50:05 +0200238 if isinstance(myvar, collections.abc.Sized):
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000239 size = len(myvar)
240
241Several of the ABCs are also useful as mixins that make it easier to develop
242classes supporting container APIs. For example, to write a class supporting
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100243the full :class:`Set` API, it is only necessary to supply the three underlying
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000244abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
245The ABC supplies the remaining methods such as :meth:`__and__` and
Georg Brandl44ea77b2013-03-28 13:28:44 +0100246:meth:`isdisjoint`::
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000247
Georg Brandl5f4b4ac2013-04-14 10:50:05 +0200248 class ListBasedSet(collections.abc.Set):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300249 ''' Alternate set implementation favoring space over speed
250 and not requiring the set elements to be hashable. '''
251 def __init__(self, iterable):
252 self.elements = lst = []
253 for value in iterable:
254 if value not in lst:
255 lst.append(value)
256
257 def __iter__(self):
258 return iter(self.elements)
259
260 def __contains__(self, value):
261 return value in self.elements
262
263 def __len__(self):
264 return len(self.elements)
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000265
266 s1 = ListBasedSet('abcdef')
267 s2 = ListBasedSet('defghi')
268 overlap = s1 & s2 # The __and__() method is supported automatically
269
270Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
271
272(1)
273 Since some set operations create new sets, the default mixin methods need
274 a way to create new instances from an iterable. The class constructor is
275 assumed to have a signature in the form ``ClassName(iterable)``.
276 That assumption is factored-out to an internal classmethod called
277 :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
278 If the :class:`Set` mixin is being used in a class with a different
Antoine Pitrou36920352011-03-22 18:33:33 +0100279 constructor signature, you will need to override :meth:`_from_iterable`
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000280 with a classmethod that can construct new instances from
281 an iterable argument.
282
283(2)
284 To override the comparisons (presumably for speed, as the
Raymond Hettinger11cda472014-07-03 00:31:30 +0100285 semantics are fixed), redefine :meth:`__le__` and :meth:`__ge__`,
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000286 then the other operations will automatically follow suit.
287
288(3)
289 The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
290 for the set; however, :meth:`__hash__` is not defined because not all sets
Donald Stufft8b852f12014-05-20 12:58:38 -0400291 are hashable or immutable. To add set hashability using mixins,
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000292 inherit from both :meth:`Set` and :meth:`Hashable`, then define
293 ``__hash__ = Set._hash``.
294
295.. seealso::
296
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300297 * `OrderedSet recipe <https://code.activestate.com/recipes/576694/>`_ for an
Éric Araujo459b4522011-06-04 21:16:42 +0200298 example built on :class:`MutableSet`.
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000299
Éric Araujo459b4522011-06-04 21:16:42 +0200300 * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.