blob: 1048b24c088c0519065e27fd912d9c81b85535eb [file] [log] [blame]
Georg Brandlaeaa5462007-09-04 08:11:03 +00001:mod:`abc` --- Abstract Base Classes
2====================================
3
4.. module:: abc
5 :synopsis: Abstract base classes according to PEP 3119.
6.. moduleauthor:: Guido van Rossum
7.. sectionauthor:: Georg Brandl
8.. much of the content adapted from docstrings
9
Raymond Hettingeread49752011-01-24 16:28:06 +000010**Source code:** :source:`Lib/abc.py`
11
12--------------
13
Éric Araujo8ddf7c22011-06-15 17:49:20 +020014This module provides the infrastructure for defining :term:`abstract base
15classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
Benjamin Peterson41181742008-07-02 20:22:54 +000016was added to Python. (See also :pep:`3141` and the :mod:`numbers` module
17regarding a type hierarchy for numbers based on ABCs.)
Georg Brandlaeaa5462007-09-04 08:11:03 +000018
Mark Summerfield08898b42007-09-05 08:43:04 +000019The :mod:`collections` module has some concrete classes that derive from
20ABCs; these can, of course, be further derived. In addition the
21:mod:`collections` module has some ABCs that can be used to test whether
22a class or instance provides a particular interface, for example, is it
23hashable or a mapping.
Georg Brandlaeaa5462007-09-04 08:11:03 +000024
25
Mark Summerfield08898b42007-09-05 08:43:04 +000026This module provides the following class:
Georg Brandlaeaa5462007-09-04 08:11:03 +000027
28.. class:: ABCMeta
29
30 Metaclass for defining Abstract Base Classes (ABCs).
31
32 Use this metaclass to create an ABC. An ABC can be subclassed directly, and
33 then acts as a mix-in class. You can also register unrelated concrete
34 classes (even built-in classes) and unrelated ABCs as "virtual subclasses" --
35 these and their descendants will be considered subclasses of the registering
36 ABC by the built-in :func:`issubclass` function, but the registering ABC
37 won't show up in their MRO (Method Resolution Order) nor will method
38 implementations defined by the registering ABC be callable (not even via
Mark Summerfield08898b42007-09-05 08:43:04 +000039 :func:`super`). [#]_
Georg Brandlaeaa5462007-09-04 08:11:03 +000040
41 Classes created with a metaclass of :class:`ABCMeta` have the following method:
42
43 .. method:: register(subclass)
44
Mark Summerfield08898b42007-09-05 08:43:04 +000045 Register *subclass* as a "virtual subclass" of this ABC. For
46 example::
Georg Brandlaeaa5462007-09-04 08:11:03 +000047
Georg Brandla1c6a1c2009-01-03 21:26:05 +000048 from abc import ABCMeta
Mark Summerfield08898b42007-09-05 08:43:04 +000049
Georg Brandla1c6a1c2009-01-03 21:26:05 +000050 class MyABC(metaclass=ABCMeta):
51 pass
Mark Summerfield08898b42007-09-05 08:43:04 +000052
Georg Brandla1c6a1c2009-01-03 21:26:05 +000053 MyABC.register(tuple)
Mark Summerfield08898b42007-09-05 08:43:04 +000054
Georg Brandla1c6a1c2009-01-03 21:26:05 +000055 assert issubclass(tuple, MyABC)
56 assert isinstance((), MyABC)
Georg Brandlaeaa5462007-09-04 08:11:03 +000057
58 You can also override this method in an abstract base class:
59
60 .. method:: __subclasshook__(subclass)
61
62 (Must be defined as a class method.)
63
64 Check whether *subclass* is considered a subclass of this ABC. This means
65 that you can customize the behavior of ``issubclass`` further without the
66 need to call :meth:`register` on every class you want to consider a
Georg Brandl2d140982007-09-04 15:45:25 +000067 subclass of the ABC. (This class method is called from the
68 :meth:`__subclasscheck__` method of the ABC.)
Georg Brandlaeaa5462007-09-04 08:11:03 +000069
70 This method should return ``True``, ``False`` or ``NotImplemented``. If
71 it returns ``True``, the *subclass* is considered a subclass of this ABC.
72 If it returns ``False``, the *subclass* is not considered a subclass of
73 this ABC, even if it would normally be one. If it returns
74 ``NotImplemented``, the subclass check is continued with the usual
75 mechanism.
76
Georg Brandl2d140982007-09-04 15:45:25 +000077 .. XXX explain the "usual mechanism"
Georg Brandlaeaa5462007-09-04 08:11:03 +000078
Georg Brandlaeaa5462007-09-04 08:11:03 +000079
Georg Brandl2d140982007-09-04 15:45:25 +000080 For a demonstration of these concepts, look at this example ABC definition::
Georg Brandlaeaa5462007-09-04 08:11:03 +000081
Georg Brandl2d140982007-09-04 15:45:25 +000082 class Foo:
83 def __getitem__(self, index):
84 ...
85 def __len__(self):
86 ...
87 def get_iterator(self):
88 return iter(self)
89
90 class MyIterable(metaclass=ABCMeta):
Georg Brandlaeaa5462007-09-04 08:11:03 +000091
92 @abstractmethod
Georg Brandlaeaa5462007-09-04 08:11:03 +000093 def __iter__(self):
Georg Brandl2d140982007-09-04 15:45:25 +000094 while False:
95 yield None
96
97 def get_iterator(self):
98 return self.__iter__()
Georg Brandlaeaa5462007-09-04 08:11:03 +000099
100 @classmethod
101 def __subclasshook__(cls, C):
Georg Brandl2d140982007-09-04 15:45:25 +0000102 if cls is MyIterable:
103 if any("__iter__" in B.__dict__ for B in C.__mro__):
Georg Brandlaeaa5462007-09-04 08:11:03 +0000104 return True
105 return NotImplemented
106
Georg Brandl2d140982007-09-04 15:45:25 +0000107 MyIterable.register(Foo)
Georg Brandlaeaa5462007-09-04 08:11:03 +0000108
Georg Brandl2d140982007-09-04 15:45:25 +0000109 The ABC ``MyIterable`` defines the standard iterable method,
110 :meth:`__iter__`, as an abstract method. The implementation given here can
111 still be called from subclasses. The :meth:`get_iterator` method is also
112 part of the ``MyIterable`` abstract base class, but it does not have to be
Mark Summerfield08898b42007-09-05 08:43:04 +0000113 overridden in non-abstract derived classes.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000114
115 The :meth:`__subclasshook__` class method defined here says that any class
Georg Brandl2d140982007-09-04 15:45:25 +0000116 that has an :meth:`__iter__` method in its :attr:`__dict__` (or in that of
Mark Summerfield08898b42007-09-05 08:43:04 +0000117 one of its base classes, accessed via the :attr:`__mro__` list) is
118 considered a ``MyIterable`` too.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000119
Georg Brandl2d140982007-09-04 15:45:25 +0000120 Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
Mark Summerfield08898b42007-09-05 08:43:04 +0000121 even though it does not define an :meth:`__iter__` method (it uses the
Georg Brandl2d140982007-09-04 15:45:25 +0000122 old-style iterable protocol, defined in terms of :meth:`__len__` and
123 :meth:`__getitem__`). Note that this will not make ``get_iterator``
124 available as a method of ``Foo``, so it is provided separately.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000125
126
127It also provides the following decorators:
128
Georg Brandl8a1caa22010-07-29 16:01:11 +0000129.. decorator:: abstractmethod(function)
Georg Brandlaeaa5462007-09-04 08:11:03 +0000130
131 A decorator indicating abstract methods.
132
Mark Summerfield08898b42007-09-05 08:43:04 +0000133 Using this decorator requires that the class's metaclass is :class:`ABCMeta` or
Georg Brandl48310cd2009-01-03 21:18:54 +0000134 is derived from it.
Mark Summerfield08898b42007-09-05 08:43:04 +0000135 A class that has a metaclass derived from :class:`ABCMeta`
136 cannot be instantiated unless all of its abstract methods and
137 properties are overridden.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000138 The abstract methods can be called using any of the normal 'super' call
Georg Brandl2d140982007-09-04 15:45:25 +0000139 mechanisms.
140
141 Dynamically adding abstract methods to a class, or attempting to modify the
142 abstraction status of a method or class once it is created, are not
143 supported. The :func:`abstractmethod` only affects subclasses derived using
144 regular inheritance; "virtual subclasses" registered with the ABC's
145 :meth:`register` method are not affected.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000146
147 Usage::
148
149 class C(metaclass=ABCMeta):
150 @abstractmethod
151 def my_abstract_method(self, ...):
152 ...
153
Georg Brandl2d140982007-09-04 15:45:25 +0000154 .. note::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000155
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000156 Unlike Java abstract methods, these abstract
Mark Summerfield08898b42007-09-05 08:43:04 +0000157 methods may have an implementation. This implementation can be
158 called via the :func:`super` mechanism from the class that
159 overrides it. This could be useful as an end-point for a
160 super-call in a framework that uses cooperative
161 multiple-inheritance.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000162
Georg Brandl2d140982007-09-04 15:45:25 +0000163
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000164.. decorator:: abstractclassmethod(function)
165
166 A subclass of the built-in :func:`classmethod`, indicating an abstract
167 classmethod. Otherwise it is similar to :func:`abstractmethod`.
168
169 Usage::
170
171 class C(metaclass=ABCMeta):
172 @abstractclassmethod
173 def my_abstract_classmethod(cls, ...):
174 ...
175
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000176 .. versionadded:: 3.2
177
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000178
179.. decorator:: abstractstaticmethod(function)
180
181 A subclass of the built-in :func:`staticmethod`, indicating an abstract
182 staticmethod. Otherwise it is similar to :func:`abstractmethod`.
183
184 Usage::
185
186 class C(metaclass=ABCMeta):
187 @abstractstaticmethod
188 def my_abstract_staticmethod(...):
189 ...
190
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000191 .. versionadded:: 3.2
192
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000193
Georg Brandlb868a662009-04-02 02:56:10 +0000194.. function:: abstractproperty(fget=None, fset=None, fdel=None, doc=None)
Georg Brandl2d140982007-09-04 15:45:25 +0000195
196 A subclass of the built-in :func:`property`, indicating an abstract property.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000197
Mark Summerfield08898b42007-09-05 08:43:04 +0000198 Using this function requires that the class's metaclass is :class:`ABCMeta` or
Georg Brandl48310cd2009-01-03 21:18:54 +0000199 is derived from it.
Mark Summerfield08898b42007-09-05 08:43:04 +0000200 A class that has a metaclass derived from :class:`ABCMeta` cannot be
201 instantiated unless all of its abstract methods and properties are overridden.
202 The abstract properties can be called using any of the normal
203 'super' call mechanisms.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000204
205 Usage::
206
207 class C(metaclass=ABCMeta):
208 @abstractproperty
209 def my_abstract_property(self):
210 ...
211
212 This defines a read-only property; you can also define a read-write abstract
213 property using the 'long' form of property declaration::
214
215 class C(metaclass=ABCMeta):
216 def getx(self): ...
217 def setx(self, value): ...
218 x = abstractproperty(getx, setx)
219
Benjamin Petersond23f8222009-04-05 19:13:16 +0000220
Mark Summerfield08898b42007-09-05 08:43:04 +0000221.. rubric:: Footnotes
222
223.. [#] C++ programmers should note that Python's virtual base class
224 concept is not the same as C++'s.