blob: fc6bbbfeb6a6607bc2ea8fde3f249bf9c2dfed97 [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
31The collections module offers the following ABCs:
32
33========================= ===================== ====================== ====================================================
34ABC Inherits Abstract Methods Mixin Methods
35========================= ===================== ====================== ====================================================
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
47:class:`MutableSequence` :class:`Sequence` ``__setitem__`` Inherited Sequence methods and
48 ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
Eli Bendersky0716a572011-03-04 10:38:14 +000049 and ``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
55:class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and
56 ``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
63:class:`MutableMapping` :class:`Mapping` ``__setitem__`` and Inherited Mapping methods and
64 ``__delitem__`` ``pop``, ``popitem``, ``clear``, ``update``,
65 and ``setdefault``
66
67
68:class:`MappingView` :class:`Sized` ``__len__``
69:class:`KeysView` :class:`MappingView`, ``__contains__``,
70 :class:`Set` ``__iter__``
71:class:`ItemsView` :class:`MappingView`, ``__contains__``,
72 :class:`Set` ``__iter__``
73:class:`ValuesView` :class:`MappingView` ``__contains__``, ``__iter__``
74========================= ===================== ====================== ====================================================
75
76These ABCs allow us to ask classes or instances if they provide
77particular functionality, for example::
78
79 size = None
80 if isinstance(myvar, collections.Sized):
81 size = len(myvar)
82
83Several of the ABCs are also useful as mixins that make it easier to develop
84classes supporting container APIs. For example, to write a class supporting
85the full :class:`Set` API, it only necessary to supply the three underlying
86abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
87The ABC supplies the remaining methods such as :meth:`__and__` and
88:meth:`isdisjoint` ::
89
90 class ListBasedSet(collections.Set):
91 ''' Alternate set implementation favoring space over speed
92 and not requiring the set elements to be hashable. '''
93 def __init__(self, iterable):
94 self.elements = lst = []
95 for value in iterable:
96 if value not in lst:
97 lst.append(value)
98 def __iter__(self):
99 return iter(self.elements)
100 def __contains__(self, value):
101 return value in self.elements
102 def __len__(self):
103 return len(self.elements)
104
105 s1 = ListBasedSet('abcdef')
106 s2 = ListBasedSet('defghi')
107 overlap = s1 & s2 # The __and__() method is supported automatically
108
109Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
110
111(1)
112 Since some set operations create new sets, the default mixin methods need
113 a way to create new instances from an iterable. The class constructor is
114 assumed to have a signature in the form ``ClassName(iterable)``.
115 That assumption is factored-out to an internal classmethod called
116 :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
117 If the :class:`Set` mixin is being used in a class with a different
Antoine Pitrou36920352011-03-22 18:33:33 +0100118 constructor signature, you will need to override :meth:`_from_iterable`
Raymond Hettinger158c9c22011-02-22 00:41:50 +0000119 with a classmethod that can construct new instances from
120 an iterable argument.
121
122(2)
123 To override the comparisons (presumably for speed, as the
124 semantics are fixed), redefine :meth:`__le__` and
125 then the other operations will automatically follow suit.
126
127(3)
128 The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
129 for the set; however, :meth:`__hash__` is not defined because not all sets
130 are hashable or immutable. To add set hashabilty using mixins,
131 inherit from both :meth:`Set` and :meth:`Hashable`, then define
132 ``__hash__ = Set._hash``.
133
134.. seealso::
135
136 * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ that uses
137 :class:`MutableSet`.
138
139 * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.