Georg Brandl | afd05da | 2008-06-07 17:11:00 +0000 | [diff] [blame] | 1 | :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 | |
| 10 | .. versionadded:: 2.6 |
| 11 | |
Benjamin Peterson | 4e47680 | 2008-07-03 13:01:17 +0000 | [diff] [blame^] | 12 | This module provides the infrastructure for defining an :term:`abstract base |
| 13 | class` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this |
Benjamin Peterson | aac51b8 | 2008-07-01 23:33:06 +0000 | [diff] [blame] | 14 | was added to Python. (See also :pep:`3141` and the :mod:`numbers` module |
| 15 | regarding a type hierarchy for numbers based on ABCs.) |
Georg Brandl | afd05da | 2008-06-07 17:11:00 +0000 | [diff] [blame] | 16 | |
| 17 | The :mod:`collections` module has some concrete classes that derive from |
| 18 | ABCs; these can, of course, be further derived. In addition the |
| 19 | :mod:`collections` module has some ABCs that can be used to test whether |
| 20 | a class or instance provides a particular interface, for example, is it |
| 21 | hashable or a mapping. |
| 22 | |
| 23 | |
| 24 | This module provides the following class: |
| 25 | |
| 26 | .. class:: ABCMeta |
| 27 | |
| 28 | Metaclass for defining Abstract Base Classes (ABCs). |
| 29 | |
| 30 | Use this metaclass to create an ABC. An ABC can be subclassed directly, and |
| 31 | then acts as a mix-in class. You can also register unrelated concrete |
| 32 | classes (even built-in classes) and unrelated ABCs as "virtual subclasses" -- |
| 33 | these and their descendants will be considered subclasses of the registering |
| 34 | ABC by the built-in :func:`issubclass` function, but the registering ABC |
| 35 | won't show up in their MRO (Method Resolution Order) nor will method |
| 36 | implementations defined by the registering ABC be callable (not even via |
| 37 | :func:`super`). [#]_ |
| 38 | |
| 39 | Classes created with a metaclass of :class:`ABCMeta` have the following method: |
| 40 | |
| 41 | .. method:: register(subclass) |
| 42 | |
| 43 | Register *subclass* as a "virtual subclass" of this ABC. For |
| 44 | example:: |
| 45 | |
| 46 | from abc import ABCMeta |
| 47 | |
| 48 | class MyABC: |
| 49 | __metaclass__ = ABCMeta |
| 50 | |
| 51 | MyABC.register(tuple) |
| 52 | |
| 53 | assert issubclass(tuple, MyABC) |
| 54 | assert isinstance((), MyABC) |
| 55 | |
| 56 | You can also override this method in an abstract base class: |
| 57 | |
| 58 | .. method:: __subclasshook__(subclass) |
| 59 | |
| 60 | (Must be defined as a class method.) |
| 61 | |
| 62 | Check whether *subclass* is considered a subclass of this ABC. This means |
| 63 | that you can customize the behavior of ``issubclass`` further without the |
| 64 | need to call :meth:`register` on every class you want to consider a |
| 65 | subclass of the ABC. (This class method is called from the |
| 66 | :meth:`__subclasscheck__` method of the ABC.) |
| 67 | |
| 68 | This method should return ``True``, ``False`` or ``NotImplemented``. If |
| 69 | it returns ``True``, the *subclass* is considered a subclass of this ABC. |
| 70 | If it returns ``False``, the *subclass* is not considered a subclass of |
| 71 | this ABC, even if it would normally be one. If it returns |
| 72 | ``NotImplemented``, the subclass check is continued with the usual |
| 73 | mechanism. |
| 74 | |
| 75 | .. XXX explain the "usual mechanism" |
| 76 | |
| 77 | |
| 78 | For a demonstration of these concepts, look at this example ABC definition:: |
| 79 | |
| 80 | class Foo(object): |
| 81 | def __getitem__(self, index): |
| 82 | ... |
| 83 | def __len__(self): |
| 84 | ... |
| 85 | def get_iterator(self): |
| 86 | return iter(self) |
| 87 | |
| 88 | class MyIterable: |
| 89 | __metaclass__ = ABCMeta |
| 90 | |
| 91 | @abstractmethod |
| 92 | def __iter__(self): |
| 93 | while False: |
| 94 | yield None |
| 95 | |
| 96 | def get_iterator(self): |
| 97 | return self.__iter__() |
| 98 | |
| 99 | @classmethod |
| 100 | def __subclasshook__(cls, C): |
| 101 | if cls is MyIterable: |
| 102 | if any("__iter__" in B.__dict__ for B in C.__mro__): |
| 103 | return True |
| 104 | return NotImplemented |
| 105 | |
| 106 | MyIterable.register(Foo) |
| 107 | |
| 108 | The ABC ``MyIterable`` defines the standard iterable method, |
| 109 | :meth:`__iter__`, as an abstract method. The implementation given here can |
| 110 | still be called from subclasses. The :meth:`get_iterator` method is also |
| 111 | part of the ``MyIterable`` abstract base class, but it does not have to be |
| 112 | overridden in non-abstract derived classes. |
| 113 | |
| 114 | The :meth:`__subclasshook__` class method defined here says that any class |
| 115 | that has an :meth:`__iter__` method in its :attr:`__dict__` (or in that of |
| 116 | one of its base classes, accessed via the :attr:`__mro__` list) is |
| 117 | considered a ``MyIterable`` too. |
| 118 | |
| 119 | Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``, |
| 120 | even though it does not define an :meth:`__iter__` method (it uses the |
| 121 | old-style iterable protocol, defined in terms of :meth:`__len__` and |
| 122 | :meth:`__getitem__`). Note that this will not make ``get_iterator`` |
| 123 | available as a method of ``Foo``, so it is provided separately. |
| 124 | |
| 125 | |
| 126 | It also provides the following decorators: |
| 127 | |
| 128 | .. function:: abstractmethod(function) |
| 129 | |
| 130 | A decorator indicating abstract methods. |
| 131 | |
| 132 | Using this decorator requires that the class's metaclass is :class:`ABCMeta` or |
| 133 | is derived from it. |
| 134 | A class that has a metaclass derived from :class:`ABCMeta` |
| 135 | cannot be instantiated unless all of its abstract methods and |
| 136 | properties are overridden. |
| 137 | The abstract methods can be called using any of the the normal 'super' call |
| 138 | mechanisms. |
| 139 | |
| 140 | Dynamically adding abstract methods to a class, or attempting to modify the |
| 141 | abstraction status of a method or class once it is created, are not |
| 142 | supported. The :func:`abstractmethod` only affects subclasses derived using |
| 143 | regular inheritance; "virtual subclasses" registered with the ABC's |
| 144 | :meth:`register` method are not affected. |
| 145 | |
| 146 | Usage:: |
| 147 | |
| 148 | class C: |
| 149 | __metaclass__ = ABCMeta |
| 150 | @abstractmethod |
| 151 | def my_abstract_method(self, ...): |
| 152 | ... |
| 153 | |
| 154 | .. note:: |
| 155 | |
| 156 | Unlike C++'s pure virtual functions, or Java abstract methods, these abstract |
| 157 | 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. |
| 162 | |
| 163 | |
| 164 | .. function:: abstractproperty(fget[, fset[, fdel[, doc]]]) |
| 165 | |
| 166 | A subclass of the built-in :func:`property`, indicating an abstract property. |
| 167 | |
| 168 | Using this function requires that the class's metaclass is :class:`ABCMeta` or |
| 169 | is derived from it. |
| 170 | A class that has a metaclass derived from :class:`ABCMeta` cannot be |
| 171 | instantiated unless all of its abstract methods and properties are overridden. |
| 172 | The abstract properties can be called using any of the normal |
| 173 | 'super' call mechanisms. |
| 174 | |
| 175 | Usage:: |
| 176 | |
| 177 | class C: |
| 178 | __metaclass__ = ABCMeta |
| 179 | @abstractproperty |
| 180 | def my_abstract_property(self): |
| 181 | ... |
| 182 | |
| 183 | This defines a read-only property; you can also define a read-write abstract |
| 184 | property using the 'long' form of property declaration:: |
| 185 | |
| 186 | class C: |
| 187 | __metaclass__ = ABCMeta |
| 188 | def getx(self): ... |
| 189 | def setx(self, value): ... |
| 190 | x = abstractproperty(getx, setx) |
| 191 | |
| 192 | .. rubric:: Footnotes |
| 193 | |
| 194 | .. [#] C++ programmers should note that Python's virtual base class |
| 195 | concept is not the same as C++'s. |