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