blob: 27abb605fd716ba6cb2369d7314904cce18981e8 [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
Andrew Svetlovb67596d2012-12-13 19:09:33 +020015classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`;
16see the PEP for why this was added to Python. (See also :pep:`3141` and the
17:mod:`numbers` module regarding 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
Éric Araujo36226802011-06-03 20:49:39 +020021:mod:`collections.abc` submodule has some ABCs that can be used to test whether
Mark Summerfield08898b42007-09-05 08:43:04 +000022a class or instance provides a particular interface, for example, is it
23hashable or a mapping.
Georg Brandlaeaa5462007-09-04 08:11:03 +000024
25
Andrew Svetlovb67596d2012-12-13 19:09:33 +020026This module provides the following classes:
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
Éric Araujo6c3787c2011-02-24 18:03:10 +000058 .. versionchanged:: 3.3
59 Returns the registered subclass, to allow usage as a class decorator.
60
Georg Brandlaeaa5462007-09-04 08:11:03 +000061 You can also override this method in an abstract base class:
62
63 .. method:: __subclasshook__(subclass)
64
65 (Must be defined as a class method.)
66
67 Check whether *subclass* is considered a subclass of this ABC. This means
68 that you can customize the behavior of ``issubclass`` further without the
69 need to call :meth:`register` on every class you want to consider a
Georg Brandl2d140982007-09-04 15:45:25 +000070 subclass of the ABC. (This class method is called from the
71 :meth:`__subclasscheck__` method of the ABC.)
Georg Brandlaeaa5462007-09-04 08:11:03 +000072
73 This method should return ``True``, ``False`` or ``NotImplemented``. If
74 it returns ``True``, the *subclass* is considered a subclass of this ABC.
75 If it returns ``False``, the *subclass* is not considered a subclass of
76 this ABC, even if it would normally be one. If it returns
77 ``NotImplemented``, the subclass check is continued with the usual
78 mechanism.
79
Georg Brandl2d140982007-09-04 15:45:25 +000080 .. XXX explain the "usual mechanism"
Georg Brandlaeaa5462007-09-04 08:11:03 +000081
Georg Brandlaeaa5462007-09-04 08:11:03 +000082
Georg Brandl2d140982007-09-04 15:45:25 +000083 For a demonstration of these concepts, look at this example ABC definition::
Georg Brandlaeaa5462007-09-04 08:11:03 +000084
Georg Brandl2d140982007-09-04 15:45:25 +000085 class Foo:
86 def __getitem__(self, index):
87 ...
88 def __len__(self):
89 ...
90 def get_iterator(self):
91 return iter(self)
92
93 class MyIterable(metaclass=ABCMeta):
Georg Brandlaeaa5462007-09-04 08:11:03 +000094
95 @abstractmethod
Georg Brandlaeaa5462007-09-04 08:11:03 +000096 def __iter__(self):
Georg Brandl2d140982007-09-04 15:45:25 +000097 while False:
98 yield None
99
100 def get_iterator(self):
101 return self.__iter__()
Georg Brandlaeaa5462007-09-04 08:11:03 +0000102
103 @classmethod
104 def __subclasshook__(cls, C):
Georg Brandl2d140982007-09-04 15:45:25 +0000105 if cls is MyIterable:
106 if any("__iter__" in B.__dict__ for B in C.__mro__):
Georg Brandlaeaa5462007-09-04 08:11:03 +0000107 return True
108 return NotImplemented
109
Georg Brandl2d140982007-09-04 15:45:25 +0000110 MyIterable.register(Foo)
Georg Brandlaeaa5462007-09-04 08:11:03 +0000111
Georg Brandl2d140982007-09-04 15:45:25 +0000112 The ABC ``MyIterable`` defines the standard iterable method,
113 :meth:`__iter__`, as an abstract method. The implementation given here can
114 still be called from subclasses. The :meth:`get_iterator` method is also
115 part of the ``MyIterable`` abstract base class, but it does not have to be
Mark Summerfield08898b42007-09-05 08:43:04 +0000116 overridden in non-abstract derived classes.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000117
118 The :meth:`__subclasshook__` class method defined here says that any class
Georg Brandl2d140982007-09-04 15:45:25 +0000119 that has an :meth:`__iter__` method in its :attr:`__dict__` (or in that of
Mark Summerfield08898b42007-09-05 08:43:04 +0000120 one of its base classes, accessed via the :attr:`__mro__` list) is
121 considered a ``MyIterable`` too.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000122
Georg Brandl2d140982007-09-04 15:45:25 +0000123 Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
Mark Summerfield08898b42007-09-05 08:43:04 +0000124 even though it does not define an :meth:`__iter__` method (it uses the
Georg Brandl2d140982007-09-04 15:45:25 +0000125 old-style iterable protocol, defined in terms of :meth:`__len__` and
126 :meth:`__getitem__`). Note that this will not make ``get_iterator``
127 available as a method of ``Foo``, so it is provided separately.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000128
129
Andrew Svetlovb67596d2012-12-13 19:09:33 +0200130.. class:: ABC
131
Georg Brandl09bc6422012-12-16 13:32:33 +0100132 A helper class that has :class:`ABCMeta` as its metaclass. With this class,
133 an abstract base class can be created by simply deriving from :class:`ABC`,
Andrew Svetlovb67596d2012-12-13 19:09:33 +0200134 avoiding sometimes confusing metaclass usage.
135
Georg Brandl09bc6422012-12-16 13:32:33 +0100136 Note that the type of :class:`ABC` is still :class:`ABCMeta`, therefore
137 inheriting from :class:`ABC` requires the usual precautions regarding metaclass
138 usage, as multiple inheritance may lead to metaclass conflicts.
139
140 .. versionadded:: 3.4
141
Andrew Svetlovb67596d2012-12-13 19:09:33 +0200142
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500143The :mod:`abc` module also provides the following decorators:
Georg Brandlaeaa5462007-09-04 08:11:03 +0000144
Éric Araujo9bc9ab52012-12-08 18:35:31 -0500145.. decorator:: abstractmethod
Georg Brandlaeaa5462007-09-04 08:11:03 +0000146
147 A decorator indicating abstract methods.
148
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500149 Using this decorator requires that the class's metaclass is :class:`ABCMeta`
150 or is derived from it. A class that has a metaclass derived from
151 :class:`ABCMeta` cannot be instantiated unless all of its abstract methods
152 and properties are overridden. The abstract methods can be called using any
153 of the normal 'super' call mechanisms. :func:`abstractmethod` may be used
154 to declare abstract methods for properties and descriptors.
Georg Brandl2d140982007-09-04 15:45:25 +0000155
156 Dynamically adding abstract methods to a class, or attempting to modify the
157 abstraction status of a method or class once it is created, are not
158 supported. The :func:`abstractmethod` only affects subclasses derived using
159 regular inheritance; "virtual subclasses" registered with the ABC's
160 :meth:`register` method are not affected.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000161
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500162 When :func:`abstractmethod` is applied in combination with other method
163 descriptors, it should be applied as the innermost decorator, as shown in
164 the following usage examples::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000165
166 class C(metaclass=ABCMeta):
167 @abstractmethod
168 def my_abstract_method(self, ...):
169 ...
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500170 @classmethod
171 @abstractmethod
172 def my_abstract_classmethod(cls, ...):
173 ...
174 @staticmethod
175 @abstractmethod
176 def my_abstract_staticmethod(...):
177 ...
178
179 @property
180 @abstractmethod
181 def my_abstract_property(self):
182 ...
183 @my_abstract_property.setter
184 @abstractmethod
185 def my_abstract_property(self, val):
186 ...
187
188 @abstractmethod
189 def _get_x(self):
190 ...
191 @abstractmethod
192 def _set_x(self, val):
193 ...
194 x = property(_get_x, _set_x)
195
196 In order to correctly interoperate with the abstract base class machinery,
197 the descriptor must identify itself as abstract using
198 :attr:`__isabstractmethod__`. In general, this attribute should be ``True``
199 if any of the methods used to compose the descriptor are abstract. For
200 example, Python's built-in property does the equivalent of::
201
202 class Descriptor:
203 ...
204 @property
205 def __isabstractmethod__(self):
206 return any(getattr(f, '__isabstractmethod__', False) for
207 f in (self._fget, self._fset, self._fdel))
Georg Brandlaeaa5462007-09-04 08:11:03 +0000208
Georg Brandl2d140982007-09-04 15:45:25 +0000209 .. note::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000210
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000211 Unlike Java abstract methods, these abstract
Mark Summerfield08898b42007-09-05 08:43:04 +0000212 methods may have an implementation. This implementation can be
213 called via the :func:`super` mechanism from the class that
214 overrides it. This could be useful as an end-point for a
215 super-call in a framework that uses cooperative
216 multiple-inheritance.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000217
Georg Brandl2d140982007-09-04 15:45:25 +0000218
Éric Araujo9bc9ab52012-12-08 18:35:31 -0500219.. decorator:: abstractclassmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000220
221 A subclass of the built-in :func:`classmethod`, indicating an abstract
222 classmethod. Otherwise it is similar to :func:`abstractmethod`.
223
Nick Coghlancea27be2012-12-08 22:56:02 +1000224 This special case is deprecated, as the :func:`classmethod` decorator
225 is now correctly identified as abstract when applied to an abstract
226 method::
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000227
228 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000229 @classmethod
230 @abstractmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000231 def my_abstract_classmethod(cls, ...):
232 ...
233
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000234 .. versionadded:: 3.2
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500235 .. deprecated:: 3.3
Nick Coghlancea27be2012-12-08 22:56:02 +1000236 It is now possible to use :class:`classmethod` with
237 :func:`abstractmethod`, making this decorator redundant.
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000238
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000239
Éric Araujo9bc9ab52012-12-08 18:35:31 -0500240.. decorator:: abstractstaticmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000241
242 A subclass of the built-in :func:`staticmethod`, indicating an abstract
243 staticmethod. Otherwise it is similar to :func:`abstractmethod`.
244
Nick Coghlancea27be2012-12-08 22:56:02 +1000245 This special case is deprecated, as the :func:`staticmethod` decorator
246 is now correctly identified as abstract when applied to an abstract
247 method::
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000248
249 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000250 @staticmethod
251 @abstractmethod
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000252 def my_abstract_staticmethod(...):
253 ...
254
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000255 .. versionadded:: 3.2
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500256 .. deprecated:: 3.3
Nick Coghlancea27be2012-12-08 22:56:02 +1000257 It is now possible to use :class:`staticmethod` with
258 :func:`abstractmethod`, making this decorator redundant.
Benjamin Petersonad1e0c52010-08-17 03:37:20 +0000259
Benjamin Peterson45c257f2010-08-17 00:52:52 +0000260
Éric Araujo87552782011-08-19 03:53:51 +0200261.. decorator:: abstractproperty(fget=None, fset=None, fdel=None, doc=None)
Georg Brandl2d140982007-09-04 15:45:25 +0000262
Nick Coghlancea27be2012-12-08 22:56:02 +1000263 A subclass of the built-in :func:`property`, indicating an abstract
264 property.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000265
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500266 Using this function requires that the class's metaclass is :class:`ABCMeta`
267 or is derived from it. A class that has a metaclass derived from
268 :class:`ABCMeta` cannot be instantiated unless all of its abstract methods
269 and properties are overridden. The abstract properties can be called using
270 any of the normal 'super' call mechanisms.
Georg Brandlaeaa5462007-09-04 08:11:03 +0000271
Nick Coghlancea27be2012-12-08 22:56:02 +1000272 This special case is deprecated, as the :func:`property` decorator
273 is now correctly identified as abstract when applied to an abstract
274 method::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000275
276 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000277 @property
278 @abstractmethod
Georg Brandlaeaa5462007-09-04 08:11:03 +0000279 def my_abstract_property(self):
280 ...
281
Nick Coghlancea27be2012-12-08 22:56:02 +1000282 The above example defines a read-only property; you can also define a
283 read-write abstract property by appropriately marking one or more of the
284 underlying methods as abstract::
Georg Brandlaeaa5462007-09-04 08:11:03 +0000285
286 class C(metaclass=ABCMeta):
Nick Coghlancea27be2012-12-08 22:56:02 +1000287 @property
288 def x(self):
289 ...
290
291 @x.setter
292 @abstractmethod
293 def x(self, val):
294 ...
295
296 If only some components are abstract, only those components need to be
297 updated to create a concrete property in a subclass::
298
299 class D(C):
300 @C.x.setter
301 def x(self, val):
302 ...
303
Georg Brandlaeaa5462007-09-04 08:11:03 +0000304
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500305 .. deprecated:: 3.3
Nick Coghlancea27be2012-12-08 22:56:02 +1000306 It is now possible to use :class:`property`, :meth:`property.getter`,
307 :meth:`property.setter` and :meth:`property.deleter` with
308 :func:`abstractmethod`, making this decorator redundant.
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500309
Benjamin Petersond23f8222009-04-05 19:13:16 +0000310
Mark Summerfield08898b42007-09-05 08:43:04 +0000311.. rubric:: Footnotes
312
313.. [#] C++ programmers should note that Python's virtual base class
314 concept is not the same as C++'s.