abc.rst 11.5 KB
Newer Older
1 2 3 4 5
:mod:`abc` --- Abstract Base Classes
====================================

.. module:: abc
   :synopsis: Abstract base classes according to PEP 3119.
6

7 8 9 10
.. moduleauthor:: Guido van Rossum
.. sectionauthor:: Georg Brandl
.. much of the content adapted from docstrings

11 12 13 14
**Source code:** :source:`Lib/abc.py`

--------------

Éric Araujo's avatar
Éric Araujo committed
15
This module provides the infrastructure for defining :term:`abstract base
16 17 18
classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`;
see the PEP for why this was added to Python. (See also :pep:`3141` and the
:mod:`numbers` module regarding a type hierarchy for numbers based on ABCs.)
19

20 21
The :mod:`collections` module has some concrete classes that derive from
ABCs; these can, of course, be further derived. In addition the
22
:mod:`collections.abc` submodule has some ABCs that can be used to test whether
23 24
a class or instance provides a particular interface, for example, is it
hashable or a mapping.
25 26


27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
This module provides the metaclass :class:`ABCMeta` for defining ABCs and
a helper class :class:`ABC` to alternatively define ABCs through inheritance:

.. class:: ABC

   A helper class that has :class:`ABCMeta` as its metaclass.  With this class,
   an abstract base class can be created by simply deriving from :class:`ABC`
   avoiding sometimes confusing metaclass usage, for example::

     from abc import ABC

     class MyABC(ABC):
         pass

   Note that the type of :class:`ABC` is still :class:`ABCMeta`, therefore
   inheriting from :class:`ABC` requires the usual precautions regarding
   metaclass usage, as multiple inheritance may lead to metaclass conflicts.
   One may also define an abstract base class by passing the metaclass
   keyword and using :class:`ABCMeta` directly, for example::

     from abc import ABCMeta

     class MyABC(metaclass=ABCMeta):
         pass

   .. versionadded:: 3.4

54 55 56 57 58 59 60 61 62 63 64 65

.. class:: ABCMeta

   Metaclass for defining Abstract Base Classes (ABCs).

   Use this metaclass to create an ABC.  An ABC can be subclassed directly, and
   then acts as a mix-in class.  You can also register unrelated concrete
   classes (even built-in classes) and unrelated ABCs as "virtual subclasses" --
   these and their descendants will be considered subclasses of the registering
   ABC by the built-in :func:`issubclass` function, but the registering ABC
   won't show up in their MRO (Method Resolution Order) nor will method
   implementations defined by the registering ABC be callable (not even via
66
   :func:`super`). [#]_
67 68 69 70 71

   Classes created with a metaclass of :class:`ABCMeta` have the following method:

   .. method:: register(subclass)

72 73
      Register *subclass* as a "virtual subclass" of this ABC. For
      example::
74

75
         from abc import ABC
76

77 78
         class MyABC(ABC):
             pass
79

80
         MyABC.register(tuple)
81

82 83
         assert issubclass(tuple, MyABC)
         assert isinstance((), MyABC)
84

85 86 87
      .. versionchanged:: 3.3
         Returns the registered subclass, to allow usage as a class decorator.

88 89 90 91
      .. versionchanged:: 3.4
         To detect calls to :meth:`register`, you can use the
         :func:`get_cache_token` function.

92 93 94 95 96 97 98 99 100
   You can also override this method in an abstract base class:

   .. method:: __subclasshook__(subclass)

      (Must be defined as a class method.)

      Check whether *subclass* is considered a subclass of this ABC.  This means
      that you can customize the behavior of ``issubclass`` further without the
      need to call :meth:`register` on every class you want to consider a
Georg Brandl's avatar
Georg Brandl committed
101 102
      subclass of the ABC.  (This class method is called from the
      :meth:`__subclasscheck__` method of the ABC.)
103 104 105 106 107 108 109 110

      This method should return ``True``, ``False`` or ``NotImplemented``.  If
      it returns ``True``, the *subclass* is considered a subclass of this ABC.
      If it returns ``False``, the *subclass* is not considered a subclass of
      this ABC, even if it would normally be one.  If it returns
      ``NotImplemented``, the subclass check is continued with the usual
      mechanism.

Georg Brandl's avatar
Georg Brandl committed
111
      .. XXX explain the "usual mechanism"
112 113


Georg Brandl's avatar
Georg Brandl committed
114
   For a demonstration of these concepts, look at this example ABC definition::
115

Georg Brandl's avatar
Georg Brandl committed
116 117 118 119 120 121 122
      class Foo:
          def __getitem__(self, index):
              ...
          def __len__(self):
              ...
          def get_iterator(self):
              return iter(self)
123

124
      class MyIterable(ABC):
125

Georg Brandl's avatar
Georg Brandl committed
126
          @abstractmethod
127
          def __iter__(self):
Georg Brandl's avatar
Georg Brandl committed
128 129 130 131 132
              while False:
                  yield None

          def get_iterator(self):
              return self.__iter__()
133 134 135

          @classmethod
          def __subclasshook__(cls, C):
Georg Brandl's avatar
Georg Brandl committed
136 137
              if cls is MyIterable:
                  if any("__iter__" in B.__dict__ for B in C.__mro__):
138 139 140
                      return True
              return NotImplemented

Georg Brandl's avatar
Georg Brandl committed
141
      MyIterable.register(Foo)
142

Georg Brandl's avatar
Georg Brandl committed
143
   The ABC ``MyIterable`` defines the standard iterable method,
144 145 146 147
   :meth:`~iterator.__iter__`, as an abstract method.  The implementation given
   here can still be called from subclasses.  The :meth:`get_iterator` method
   is also part of the ``MyIterable`` abstract base class, but it does not have
   to be overridden in non-abstract derived classes.
148 149

   The :meth:`__subclasshook__` class method defined here says that any class
150 151 152
   that has an :meth:`~iterator.__iter__` method in its
   :attr:`~object.__dict__` (or in that of one of its base classes, accessed
   via the :attr:`~class.__mro__` list) is considered a ``MyIterable`` too.
153

Georg Brandl's avatar
Georg Brandl committed
154
   Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
155 156
   even though it does not define an :meth:`~iterator.__iter__` method (it uses
   the old-style iterable protocol, defined in terms of :meth:`__len__` and
Georg Brandl's avatar
Georg Brandl committed
157 158
   :meth:`__getitem__`).  Note that this will not make ``get_iterator``
   available as a method of ``Foo``, so it is provided separately.
159 160


161

162

163
The :mod:`abc` module also provides the following decorator:
164

165
.. decorator:: abstractmethod
166 167 168

   A decorator indicating abstract methods.

169 170 171 172 173 174
   Using this decorator requires that the class's metaclass is :class:`ABCMeta`
   or is derived from it.  A class that has a metaclass derived from
   :class:`ABCMeta` cannot be instantiated unless all of its abstract methods
   and properties are overridden.  The abstract methods can be called using any
   of the normal 'super' call mechanisms.  :func:`abstractmethod` may be used
   to declare abstract methods for properties and descriptors.
Georg Brandl's avatar
Georg Brandl committed
175 176 177 178 179 180

   Dynamically adding abstract methods to a class, or attempting to modify the
   abstraction status of a method or class once it is created, are not
   supported.  The :func:`abstractmethod` only affects subclasses derived using
   regular inheritance; "virtual subclasses" registered with the ABC's
   :meth:`register` method are not affected.
181

182 183 184
   When :func:`abstractmethod` is applied in combination with other method
   descriptors, it should be applied as the innermost decorator, as shown in
   the following usage examples::
185

186
      class C(ABC):
187 188 189
          @abstractmethod
          def my_abstract_method(self, ...):
              ...
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
          @classmethod
          @abstractmethod
          def my_abstract_classmethod(cls, ...):
              ...
          @staticmethod
          @abstractmethod
          def my_abstract_staticmethod(...):
              ...

          @property
          @abstractmethod
          def my_abstract_property(self):
              ...
          @my_abstract_property.setter
          @abstractmethod
          def my_abstract_property(self, val):
              ...

          @abstractmethod
          def _get_x(self):
              ...
          @abstractmethod
          def _set_x(self, val):
              ...
          x = property(_get_x, _set_x)

   In order to correctly interoperate with the abstract base class machinery,
   the descriptor must identify itself as abstract using
   :attr:`__isabstractmethod__`. In general, this attribute should be ``True``
   if any of the methods used to compose the descriptor are abstract. For
   example, Python's built-in property does the equivalent of::

      class Descriptor:
          ...
          @property
          def __isabstractmethod__(self):
              return any(getattr(f, '__isabstractmethod__', False) for
                         f in (self._fget, self._fset, self._fdel))
228

Georg Brandl's avatar
Georg Brandl committed
229 230
   .. note::

231
      Unlike Java abstract methods, these abstract
232 233 234 235 236
      methods may have an implementation. This implementation can be
      called via the :func:`super` mechanism from the class that
      overrides it.  This could be useful as an end-point for a
      super-call in a framework that uses cooperative
      multiple-inheritance.
Georg Brandl's avatar
Georg Brandl committed
237

238

239 240
The :mod:`abc` module also supports the following legacy decorators:

241
.. decorator:: abstractclassmethod
242

243 244 245 246 247
   .. versionadded:: 3.2
   .. deprecated:: 3.3
       It is now possible to use :class:`classmethod` with
       :func:`abstractmethod`, making this decorator redundant.

248 249 250
   A subclass of the built-in :func:`classmethod`, indicating an abstract
   classmethod. Otherwise it is similar to :func:`abstractmethod`.

251 252 253
   This special case is deprecated, as the :func:`classmethod` decorator
   is now correctly identified as abstract when applied to an abstract
   method::
254

255
      class C(ABC):
256 257
          @classmethod
          @abstractmethod
258 259 260
          def my_abstract_classmethod(cls, ...):
              ...

261 262 263

.. decorator:: abstractstaticmethod

Benjamin Peterson's avatar
Benjamin Peterson committed
264
   .. versionadded:: 3.2
265
   .. deprecated:: 3.3
266
       It is now possible to use :class:`staticmethod` with
267
       :func:`abstractmethod`, making this decorator redundant.
Benjamin Peterson's avatar
Benjamin Peterson committed
268

269 270 271
   A subclass of the built-in :func:`staticmethod`, indicating an abstract
   staticmethod. Otherwise it is similar to :func:`abstractmethod`.

272 273 274
   This special case is deprecated, as the :func:`staticmethod` decorator
   is now correctly identified as abstract when applied to an abstract
   method::
275

276
      class C(ABC):
277 278
          @staticmethod
          @abstractmethod
279 280 281 282
          def my_abstract_staticmethod(...):
              ...


283
.. decorator:: abstractproperty
284

285 286 287 288 289
   .. deprecated:: 3.3
       It is now possible to use :class:`property`, :meth:`property.getter`,
       :meth:`property.setter` and :meth:`property.deleter` with
       :func:`abstractmethod`, making this decorator redundant.

290 291
   A subclass of the built-in :func:`property`, indicating an abstract
   property.
292

293 294 295
   This special case is deprecated, as the :func:`property` decorator
   is now correctly identified as abstract when applied to an abstract
   method::
296

297
      class C(ABC):
298 299
          @property
          @abstractmethod
300 301 302
          def my_abstract_property(self):
              ...

303 304 305
   The above example defines a read-only property; you can also define a
   read-write abstract property by appropriately marking one or more of the
   underlying methods as abstract::
306

307
      class C(ABC):
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
          @property
          def x(self):
              ...

          @x.setter
          @abstractmethod
          def x(self, val):
              ...

   If only some components are abstract, only those components need to be
   updated to create a concrete property in a subclass::

      class D(C):
          @C.x.setter
          def x(self, val):
              ...

325

326 327 328 329 330 331
The :mod:`abc` module also provides the following functions:

.. function:: get_cache_token()

   Returns the current abstract base class cache token.

332 333 334
   The token is an opaque object (that supports equality testing) identifying
   the current version of the abstract base class cache for virtual subclasses.
   The token changes with every call to :meth:`ABCMeta.register` on any ABC.
335 336 337 338

   .. versionadded:: 3.4


339 340 341 342
.. rubric:: Footnotes

.. [#] C++ programmers should note that Python's virtual base class
   concept is not the same as C++'s.