blob: 58354f85711b05af2ab44303e87aa0a183fe7356 [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
6.. moduleauthor:: Raymond Hettinger <python at rcn.com>
7.. sectionauthor:: Raymond Hettinger <python at rcn.com>
8
9.. testsetup:: *
10
11 from collections import *
12 import itertools
13 __name__ = '<doctest>'
14
15**Source code:** :source:`Lib/collections/abc.py`
16
17--------------
18
19This module provides :term:`abstract base classes <abstract base class>` that
20can be used to test whether a class provides a particular interface; for
21example, whether it is hashable or whether it is a mapping.
22
23.. versionchanged:: 3.3
24 Formerly, this module was part of the :mod:`collections` module.
25
26.. _abstract-base-classes:
27
28Collections Abstract Base Classes
29---------------------------------
30
Ezio Melottic831a912011-03-28 19:27:09 +030031The collections module offers the following :term:`ABCs <abstract base class>`:
Raymond Hettinger158c9c22011-02-22 00:41:50 +000032
33========================= ===================== ====================== ====================================================
Ezio Melottic831a912011-03-28 19:27:09 +030034ABC Inherits from Abstract Methods Mixin Methods
Raymond Hettinger158c9c22011-02-22 00:41:50 +000035========================= ===================== ====================== ====================================================
36:class:`Container` ``__contains__``
37:class:`Hashable` ``__hash__``
38:class:`Iterable` ``__iter__``
39:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
40:class:`Sized` ``__len__``
41:class:`Callable` ``__call__``
42
43:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``, ``__iter__``, ``__reversed__``,
44 :class:`Iterable`, ``index``, and ``count``
45 :class:`Container`
46
Ezio Melottic831a912011-03-28 19:27:09 +030047:class:`MutableSequence` :class:`Sequence` ``__setitem__`` Inherited :class:`Sequence` methods and
Raymond Hettinger158c9c22011-02-22 00:41:50 +000048 ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
Ezio Melottic831a912011-03-28 19:27:09 +030049 ``insert`` ``remove``, ``clear``, and ``__iadd__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000050
51:class:`Set` :class:`Sized`, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
52 :class:`Iterable`, ``__gt__``, ``__ge__``, ``__and__``, ``__or__``,
53 :class:`Container` ``__sub__``, ``__xor__``, and ``isdisjoint``
54
Ezio Melottic831a912011-03-28 19:27:09 +030055:class:`MutableSet` :class:`Set` ``add``, Inherited :class:`Set` methods and
Raymond Hettinger158c9c22011-02-22 00:41:50 +000056 ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``,
57 ``__iand__``, ``__ixor__``, and ``__isub__``
58
59:class:`Mapping` :class:`Sized`, ``__getitem__`` ``__contains__``, ``keys``, ``items``, ``values``,
60 :class:`Iterable`, ``get``, ``__eq__``, and ``__ne__``
61 :class:`Container`
62
Ezio Melottic831a912011-03-28 19:27:09 +030063:class:`MutableMapping` :class:`Mapping` ``__setitem__``, Inherited :class:`Mapping` methods and
Raymond Hettinger158c9c22011-02-22 00:41:50 +000064 ``__delitem__`` ``pop``, ``popitem``, ``clear``, ``update``,
65 and ``setdefault``
66
67
68:class:`MappingView` :class:`Sized` ``__len__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000069:class:`ItemsView` :class:`MappingView`, ``__contains__``,
70 :class:`Set` ``__iter__``
Ezio Melottic831a912011-03-28 19:27:09 +030071:class:`KeysView` :class:`MappingView`, ``__contains__``,
72 :class:`Set` ``__iter__``
Raymond Hettinger158c9c22011-02-22 00:41:50 +000073:class:`ValuesView` :class:`MappingView` ``__contains__``, ``__iter__``
74========================= ===================== ====================== ====================================================
75
Ezio Melottic831a912011-03-28 19:27:09 +030076
77.. class:: Container
78 Hashable
79 Sized
80 Callable
81
82 ABCs for classes that provide respectively the methods :meth:`__contains__`,
83 :meth:`__hash__`, :meth:`__len__`, and :meth:`__call__`.
84
85.. class:: Iterable
86
87 ABC for classes that provide the :meth:`__iter__` method.
88 See also the definition of :term:`iterable`.
89
90.. class:: Iterator
91
92 ABC for classes that provide the :meth:`__iter__` and :meth:`next` methods.
93 See also the definition of :term:`iterator`.
94
95.. class:: Sequence
96 MutableSequence
97
98 ABCs for read-only and mutable :term:`sequences <sequence>`.
99
100.. class:: Set
101 MutableSet
102
103 ABCs for read-only and mutable sets.
104
105.. class:: Mapping
106 MutableMapping
107
108 ABCs for read-only and mutable :term:`mappings <mapping>`.
109
110.. class:: MappingView
111 ItemsView
112 KeysView
113 ValuesView
114
115 ABCs for mapping, items, keys, and values :term:`views <view>`.
116
117
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000118These ABCs allow us to ask classes or instances if they provide
119particular functionality, for example::
120
121 size = None
122 if isinstance(myvar, collections.Sized):
123 size = len(myvar)
124
125Several of the ABCs are also useful as mixins that make it easier to develop
126classes supporting container APIs. For example, to write a class supporting
127the full :class:`Set` API, it only necessary to supply the three underlying
128abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
129The ABC supplies the remaining methods such as :meth:`__and__` and
130:meth:`isdisjoint` ::
131
132 class ListBasedSet(collections.Set):
133 ''' Alternate set implementation favoring space over speed
134 and not requiring the set elements to be hashable. '''
135 def __init__(self, iterable):
136 self.elements = lst = []
137 for value in iterable:
138 if value not in lst:
139 lst.append(value)
140 def __iter__(self):
141 return iter(self.elements)
142 def __contains__(self, value):
143 return value in self.elements
144 def __len__(self):
145 return len(self.elements)
146
147 s1 = ListBasedSet('abcdef')
148 s2 = ListBasedSet('defghi')
149 overlap = s1 & s2 # The __and__() method is supported automatically
150
151Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
152
153(1)
154 Since some set operations create new sets, the default mixin methods need
155 a way to create new instances from an iterable. The class constructor is
156 assumed to have a signature in the form ``ClassName(iterable)``.
157 That assumption is factored-out to an internal classmethod called
158 :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
159 If the :class:`Set` mixin is being used in a class with a different
Antoine Pitrou36920352011-03-22 18:33:33 +0100160 constructor signature, you will need to override :meth:`_from_iterable`
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000161 with a classmethod that can construct new instances from
162 an iterable argument.
163
164(2)
165 To override the comparisons (presumably for speed, as the
166 semantics are fixed), redefine :meth:`__le__` and
167 then the other operations will automatically follow suit.
168
169(3)
170 The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
171 for the set; however, :meth:`__hash__` is not defined because not all sets
172 are hashable or immutable. To add set hashabilty using mixins,
173 inherit from both :meth:`Set` and :meth:`Hashable`, then define
174 ``__hash__ = Set._hash``.
175
176.. seealso::
177
178 * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ that uses
179 :class:`MutableSet`.
180
181 * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.