blob: 966003bd45ada1ffb670d4480c26034fc275edd7 [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandlaeaa5462007-09-04 08:11:03 +00007.. moduleauthor:: Guido van Rossum
8.. sectionauthor:: Georg Brandl
9.. much of the content adapted from docstrings
10
Raymond Hettingeread49752011-01-24 16:28:06 +000011**Source code:** :source:`Lib/abc.py`
12
13--------------
14
Éric Araujo8ddf7c22011-06-15 17:49:20 +020015This module provides the infrastructure for defining :term:`abstract base
Andrew Svetlovb67596d2012-12-13 19:09:33 +020016classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`;
17see the PEP for why this was added to Python. (See also :pep:`3141` and the
18:mod:`numbers` module regarding a type hierarchy for numbers based on ABCs.)
Georg Brandlaeaa5462007-09-04 08:11:03 +000019
Mark Summerfield08898b42007-09-05 08:43:04 +000020The :mod:`collections` module has some concrete classes that derive from
21ABCs; these can, of course, be further derived. In addition the
Éric Araujo36226802011-06-03 20:49:39 +020022:mod:`collections.abc` submodule has some ABCs that can be used to test whether
Mark Summerfield08898b42007-09-05 08:43:04 +000023a class or instance provides a particular interface, for example, is it
24hashable or a mapping.
Georg Brandlaeaa5462007-09-04 08:11:03 +000025
26
Andrew Svetlovb67596d2012-12-13 19:09:33 +020027This module provides the following classes:
Georg Brandlaeaa5462007-09-04 08:11:03 +000028
29.. class:: ABCMeta
30
31 Metaclass for defining Abstract Base Classes (ABCs).
32
33 Use this metaclass to create an ABC. An ABC can be subclassed directly, and
34 then acts as a mix-in class. You can also register unrelated concrete
35 classes (even built-in classes) and unrelated ABCs as "virtual subclasses" --
36 these and their descendants will be considered subclasses of the registering
37 ABC by the built-in :func:`issubclass` function, but the registering ABC
38 won't show up in their MRO (Method Resolution Order) nor will method
39 implementations defined by the registering ABC be callable (not even via
Mark Summerfield08898b42007-09-05 08:43:04 +000040 :func:`super`). [#]_
Georg Brandlaeaa5462007-09-04 08:11:03 +000041
42 Classes created with a metaclass of :class:`ABCMeta` have the following method:
43
44 .. method:: register(subclass)
45
Mark Summerfield08898b42007-09-05 08:43:04 +000046 Register *subclass* as a "virtual subclass" of this ABC. For
47 example::
Georg Brandlaeaa5462007-09-04 08:11:03 +000048
Georg Brandla1c6a1c2009-01-03 21:26:05 +000049 from abc import ABCMeta
Mark Summerfield08898b42007-09-05 08:43:04 +000050
Georg Brandla1c6a1c2009-01-03 21:26:05 +000051 class MyABC(metaclass=ABCMeta):
52 pass
Mark Summerfield08898b42007-09-05 08:43:04 +000053
Georg Brandla1c6a1c2009-01-03 21:26:05 +000054 MyABC.register(tuple)
Mark Summerfield08898b42007-09-05 08:43:04 +000055
Georg Brandla1c6a1c2009-01-03 21:26:05 +000056 assert issubclass(tuple, MyABC)
57 assert isinstance((), MyABC)
Georg Brandlaeaa5462007-09-04 08:11:03 +000058
Éric Araujo6c3787c2011-02-24 18:03:10 +000059 .. versionchanged:: 3.3
60 Returns the registered subclass, to allow usage as a class decorator.
61
Łukasz Langaeadd8cf2013-05-25 18:41:50 +020062 .. versionchanged:: 3.4
63 To detect calls to :meth:`register`, you can use the
64 :func:`get_cache_token` function.
65
Georg Brandlaeaa5462007-09-04 08:11:03 +000066 You can also override this method in an abstract base class:
67
68 .. method:: __subclasshook__(subclass)
69
70 (Must be defined as a class method.)
71
72 Check whether *subclass* is considered a subclass of this ABC. This means
73 that you can customize the behavior of ``issubclass`` further without the
74 need to call :meth:`register` on every class you want to consider a
Georg Brandl2d140982007-09-04 15:45:25 +000075 subclass of the ABC. (This class method is called from the
76 :meth:`__subclasscheck__` method of the ABC.)
Georg Brandlaeaa5462007-09-04 08:11:03 +000077
78 This method should return ``True``, ``False`` or ``NotImplemented``. If
79 it returns ``True``, the *subclass* is considered a subclass of this ABC.
80 If it returns ``False``, the *subclass* is not considered a subclass of
81 this ABC, even if it would normally be one. If it returns
82 ``NotImplemented``, the subclass check is continued with the usual
83 mechanism.
84
Georg Brandl2d140982007-09-04 15:45:25 +000085 .. XXX explain the "usual mechanism"
Georg Brandlaeaa5462007-09-04 08:11:03 +000086
Georg Brandlaeaa5462007-09-04 08:11:03 +000087
Georg Brandl2d140982007-09-04 15:45:25 +000088 For a demonstration of these concepts, look at this example ABC definition::
Georg Brandlaeaa5462007-09-04 08:11:03 +000089
Georg Brandl2d140982007-09-04 15:45:25 +000090 class Foo:
91 def __getitem__(self, index):
92 ...
93 def __len__(self):
94 ...
95 def get_iterator(self):
96 return iter(self)
97
98 class MyIterable(metaclass=ABCMeta):
Georg Brandlaeaa5462007-09-04 08:11:03 +000099
100 @abstractmethod
Georg Brandlaeaa5462007-09-04 08:11:03 +0000101 def __iter__(self):
Georg Brandl2d140982007-09-04 15:45:25 +0000102 while False:
103 yield None
104
105 def get_iterator(self):
106 return self.__iter__()
Georg Brandlaeaa5462007-09-04 08:11:03 +0000107
108 @classmethod
109 def __subclasshook__(cls, C):
Georg Brandl2d140982007-09-04 15:45:25 +0000110 if cls is MyIterable:
111 if any("__iter__" in B.__dict__ for B in C.__mro__):
Georg Brandlaeaa5462007-09-04 08:11:03 +0000112 return True
113 return NotImplemented
114
Georg Brandl2d140982007-09-04 15:45:25 +0000115 MyIterable.register(Foo)
Georg Brandlaeaa5462007-09-04 08:11:03 +0000116
Georg Brandl2d140982007-09-04 15:45:25 +0000117 The ABC ``MyIterable`` defines the standard iterable method,
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300118 :meth:`~iterator.__iter__`, as an abstract method. The implementation given
119 here can still be called from subclasses. The :meth:`get_iterator` method
120 is also part of the ``MyIterable`` abstract base class, but it does not have
121 to be overridden in non-abstract derived classes.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000122
123 The :meth:`__subclasshook__` class method defined here says that any class
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300124 that has an :meth:`~iterator.__iter__` method in its
125 :attr:`~object.__dict__` (or in that of one of its base classes, accessed
126 via the :attr:`~class.__mro__` list) is considered a ``MyIterable`` too.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000127
Georg Brandl2d140982007-09-04 15:45:25 +0000128 Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300129 even though it does not define an :meth:`~iterator.__iter__` method (it uses
130 the old-style iterable protocol, defined in terms of :meth:`__len__` and
Georg Brandl2d140982007-09-04 15:45:25 +0000131 :meth:`__getitem__`). Note that this will not make ``get_iterator``
132 available as a method of ``Foo``, so it is provided separately.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000133
134
Andrew Svetlovb67596d2012-12-13 19:09:33 +0200135.. class:: ABC
136
Georg Brandl09bc6422012-12-16 13:32:33 +0100137 A helper class that has :class:`ABCMeta` as its metaclass. With this class,
138 an abstract base class can be created by simply deriving from :class:`ABC`,
Andrew Svetlovb67596d2012-12-13 19:09:33 +0200139 avoiding sometimes confusing metaclass usage.
140
Georg Brandl09bc6422012-12-16 13:32:33 +0100141 Note that the type of :class:`ABC` is still :class:`ABCMeta`, therefore
142 inheriting from :class:`ABC` requires the usual precautions regarding metaclass
143 usage, as multiple inheritance may lead to metaclass conflicts.
144
145 .. versionadded:: 3.4
146
Andrew Svetlovb67596d2012-12-13 19:09:33 +0200147
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500148The :mod:`abc` module also provides the following decorators:
Georg Brandlaeaa5462007-09-04 08:11:03 +0000149
Éric Araujo9bc9ab52012-12-08 18:35:31 -0500150.. decorator:: abstractmethod
Georg Brandlaeaa5462007-09-04 08:11:03 +0000151
152 A decorator indicating abstract methods.
153
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500154 Using this decorator requires that the class's metaclass is :class:`ABCMeta`
155 or is derived from it. A class that has a metaclass derived from
156 :class:`ABCMeta` cannot be instantiated unless all of its abstract methods
157 and properties are overridden. The abstract methods can be called using any
158 of the normal 'super' call mechanisms. :func:`abstractmethod` may be used
159 to declare abstract methods for properties and descriptors.
Georg Brandl2d140982007-09-04 15:45:25 +0000160
161 Dynamically adding abstract methods to a class, or attempting to modify the
162 abstraction status of a method or class once it is created, are not
163 supported. The :func:`abstractmethod` only affects subclasses derived using
164 regular inheritance; "virtual subclasses" registered with the ABC's
165 :meth:`register` method are not affected.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000166
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500167 When :func:`abstractmethod` is applied in combination with other method
168 descriptors, it should be applied as the innermost decorator, as shown in
169 the following usage examples::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000170
171 class C(metaclass=ABCMeta):
172 @abstractmethod
173 def my_abstract_method(self, ...):
174 ...
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500175 @classmethod
176 @abstractmethod
177 def my_abstract_classmethod(cls, ...):
178 ...
179 @staticmethod
180 @abstractmethod
181 def my_abstract_staticmethod(...):
182 ...
183
184 @property
185 @abstractmethod
186 def my_abstract_property(self):
187 ...
188 @my_abstract_property.setter
189 @abstractmethod
190 def my_abstract_property(self, val):
191 ...
192
193 @abstractmethod
194 def _get_x(self):
195 ...
196 @abstractmethod
197 def _set_x(self, val):
198 ...
199 x = property(_get_x, _set_x)
200
201 In order to correctly interoperate with the abstract base class machinery,
202 the descriptor must identify itself as abstract using
203 :attr:`__isabstractmethod__`. In general, this attribute should be ``True``
204 if any of the methods used to compose the descriptor are abstract. For
205 example, Python's built-in property does the equivalent of::
206
207 class Descriptor:
208 ...
209 @property
210 def __isabstractmethod__(self):
211 return any(getattr(f, '__isabstractmethod__', False) for
212 f in (self._fget, self._fset, self._fdel))
Georg Brandlaeaa5462007-09-04 08:11:03 +0000213
Georg Brandl2d140982007-09-04 15:45:25 +0000214 .. note::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000215
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000216 Unlike Java abstract methods, these abstract
Mark Summerfield08898b42007-09-05 08:43:04 +0000217 methods may have an implementation. This implementation can be
218 called via the :func:`super` mechanism from the class that
219 overrides it. This could be useful as an end-point for a
220 super-call in a framework that uses cooperative
221 multiple-inheritance.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000222
Georg Brandl2d140982007-09-04 15:45:25 +0000223
Éric Araujo9bc9ab52012-12-08 18:35:31 -0500224.. decorator:: abstractclassmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000225
226 A subclass of the built-in :func:`classmethod`, indicating an abstract
227 classmethod. Otherwise it is similar to :func:`abstractmethod`.
228
Nick Coghlancea27be2012-12-08 22:56:02 +1000229 This special case is deprecated, as the :func:`classmethod` decorator
230 is now correctly identified as abstract when applied to an abstract
231 method::
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000232
233 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000234 @classmethod
235 @abstractmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000236 def my_abstract_classmethod(cls, ...):
237 ...
238
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000239 .. versionadded:: 3.2
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500240 .. deprecated:: 3.3
Nick Coghlancea27be2012-12-08 22:56:02 +1000241 It is now possible to use :class:`classmethod` with
242 :func:`abstractmethod`, making this decorator redundant.
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000243
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000244
Éric Araujo9bc9ab52012-12-08 18:35:31 -0500245.. decorator:: abstractstaticmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000246
247 A subclass of the built-in :func:`staticmethod`, indicating an abstract
248 staticmethod. Otherwise it is similar to :func:`abstractmethod`.
249
Nick Coghlancea27be2012-12-08 22:56:02 +1000250 This special case is deprecated, as the :func:`staticmethod` decorator
251 is now correctly identified as abstract when applied to an abstract
252 method::
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000253
254 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000255 @staticmethod
256 @abstractmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000257 def my_abstract_staticmethod(...):
258 ...
259
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000260 .. versionadded:: 3.2
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500261 .. deprecated:: 3.3
Nick Coghlancea27be2012-12-08 22:56:02 +1000262 It is now possible to use :class:`staticmethod` with
263 :func:`abstractmethod`, making this decorator redundant.
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000264
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000265
Éric Araujo87552782011-08-19 03:53:51 +0200266.. decorator:: abstractproperty(fget=None, fset=None, fdel=None, doc=None)
Georg Brandl2d140982007-09-04 15:45:25 +0000267
Nick Coghlancea27be2012-12-08 22:56:02 +1000268 A subclass of the built-in :func:`property`, indicating an abstract
269 property.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000270
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500271 Using this function requires that the class's metaclass is :class:`ABCMeta`
272 or is derived from it. A class that has a metaclass derived from
273 :class:`ABCMeta` cannot be instantiated unless all of its abstract methods
274 and properties are overridden. The abstract properties can be called using
275 any of the normal 'super' call mechanisms.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000276
Nick Coghlancea27be2012-12-08 22:56:02 +1000277 This special case is deprecated, as the :func:`property` decorator
278 is now correctly identified as abstract when applied to an abstract
279 method::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000280
281 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000282 @property
283 @abstractmethod
Georg Brandlaeaa5462007-09-04 08:11:03 +0000284 def my_abstract_property(self):
285 ...
286
Nick Coghlancea27be2012-12-08 22:56:02 +1000287 The above example defines a read-only property; you can also define a
288 read-write abstract property by appropriately marking one or more of the
289 underlying methods as abstract::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000290
291 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000292 @property
293 def x(self):
294 ...
295
296 @x.setter
297 @abstractmethod
298 def x(self, val):
299 ...
300
301 If only some components are abstract, only those components need to be
302 updated to create a concrete property in a subclass::
303
304 class D(C):
305 @C.x.setter
306 def x(self, val):
307 ...
308
Georg Brandlaeaa5462007-09-04 08:11:03 +0000309
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500310 .. deprecated:: 3.3
Nick Coghlancea27be2012-12-08 22:56:02 +1000311 It is now possible to use :class:`property`, :meth:`property.getter`,
312 :meth:`property.setter` and :meth:`property.deleter` with
313 :func:`abstractmethod`, making this decorator redundant.
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500314
Benjamin Petersond23f8222009-04-05 19:13:16 +0000315
Łukasz Langaeadd8cf2013-05-25 18:41:50 +0200316The :mod:`abc` module also provides the following functions:
317
318.. function:: get_cache_token()
319
320 Returns the current abstract base class cache token.
321
R David Murray3edcc782013-12-24 16:13:32 -0500322 The token is an opaque object (that supports equality testing) identifying
323 the current version of the abstract base class cache for virtual subclasses.
324 The token changes with every call to :meth:`ABCMeta.register` on any ABC.
Łukasz Langaeadd8cf2013-05-25 18:41:50 +0200325
326 .. versionadded:: 3.4
327
328
Mark Summerfield08898b42007-09-05 08:43:04 +0000329.. rubric:: Footnotes
330
331.. [#] C++ programmers should note that Python's virtual base class
332 concept is not the same as C++'s.