cpython/Doc/library/abc.rst

191 lines
6.8 KiB
ReStructuredText
Raw Normal View History

:mod:`abc` --- Abstract Base Classes
====================================
.. module:: abc
:synopsis: Abstract base classes according to PEP 3119.
.. moduleauthor:: Guido van Rossum
.. sectionauthor:: Georg Brandl
.. much of the content adapted from docstrings
Merged revisions 64623,64640,64665,64687,64689-64690,64719,64721,64735,64742,64744-64746,64756-64761,64767-64769,64771-64772,64774-64775,64788,64793,64835-64836 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r64623 | benjamin.peterson | 2008-07-01 21:51:54 +0200 (Tue, 01 Jul 2008) | 1 line write a short little section for multiprocessing; it still needs help ........ r64640 | georg.brandl | 2008-07-01 22:56:03 +0200 (Tue, 01 Jul 2008) | 2 lines Add a comment about incref'ing w. ........ r64665 | jesse.noller | 2008-07-02 18:56:51 +0200 (Wed, 02 Jul 2008) | 1 line Add #!/usr/bin/env python for ben ........ r64687 | andrew.kuchling | 2008-07-03 14:50:03 +0200 (Thu, 03 Jul 2008) | 1 line Tweak wording ........ r64689 | benjamin.peterson | 2008-07-03 14:57:35 +0200 (Thu, 03 Jul 2008) | 1 line lowercase glossary term ........ r64690 | benjamin.peterson | 2008-07-03 15:01:17 +0200 (Thu, 03 Jul 2008) | 1 line let the term be linked ........ r64719 | raymond.hettinger | 2008-07-05 04:11:55 +0200 (Sat, 05 Jul 2008) | 1 line Update comment on prediction macros. ........ r64721 | georg.brandl | 2008-07-05 12:07:18 +0200 (Sat, 05 Jul 2008) | 2 lines Fix tabs. ........ r64735 | mark.dickinson | 2008-07-05 17:25:48 +0200 (Sat, 05 Jul 2008) | 3 lines Minor rewrite of cmath_log to work around a Sun compiler bug. See issue #3168. ........ r64742 | benjamin.peterson | 2008-07-05 18:29:38 +0200 (Sat, 05 Jul 2008) | 1 line make regrtest aware of the lib2to3 resource ........ r64744 | georg.brandl | 2008-07-05 18:43:45 +0200 (Sat, 05 Jul 2008) | 2 lines Keep below 80 chars. ........ r64745 | facundo.batista | 2008-07-05 21:19:50 +0200 (Sat, 05 Jul 2008) | 3 lines Issue 3289. Removed two lines that ended doing nothing. ........ r64746 | facundo.batista | 2008-07-05 22:39:59 +0200 (Sat, 05 Jul 2008) | 4 lines Issue #3239. Differentiate the ascii call from the curses one and the builtin one. ........ r64756 | gregory.p.smith | 2008-07-06 09:16:40 +0200 (Sun, 06 Jul 2008) | 3 lines - Issue #2113: Fix error in subprocess.Popen if the select system call is interrupted by a signal. ........ r64757 | benjamin.peterson | 2008-07-06 14:39:09 +0200 (Sun, 06 Jul 2008) | 1 line remove test_compact_freelists from test_sys ........ r64758 | gregory.p.smith | 2008-07-06 19:06:29 +0200 (Sun, 06 Jul 2008) | 2 lines fix issue3304 - remove an incorrect PyMem_Free in fileio_init ........ r64759 | georg.brandl | 2008-07-06 19:36:20 +0200 (Sun, 06 Jul 2008) | 2 lines Fix opensearch template. ........ r64760 | andrew.kuchling | 2008-07-06 19:43:16 +0200 (Sun, 06 Jul 2008) | 1 line Wording fix ........ r64761 | andrew.kuchling | 2008-07-06 19:44:17 +0200 (Sun, 06 Jul 2008) | 1 line Add two items; rewrap paragraph ........ r64767 | gregory.p.smith | 2008-07-07 06:31:58 +0200 (Mon, 07 Jul 2008) | 4 lines - Issue #3309: Fix bz2.BZFile itererator to release its internal lock properly when raising an exception due to the bz2file being closed. Prevents a deadlock. ........ r64768 | josiah.carlson | 2008-07-07 06:51:46 +0200 (Mon, 07 Jul 2008) | 2 lines Fixed bugs 760475, 953599, and 1519. ........ r64769 | gregory.p.smith | 2008-07-07 06:54:31 +0200 (Mon, 07 Jul 2008) | 2 lines Add commented out #_sha256 and #_sha512 lines per issue 3183. ........ r64771 | gregory.p.smith | 2008-07-07 07:09:12 +0200 (Mon, 07 Jul 2008) | 4 lines - Issue #3094: httplib.HTTPSConnection Host: headers no longer include the redundant ":443" port number designation when the connection is using the default https port (443). ........ r64772 | skip.montanaro | 2008-07-07 13:16:14 +0200 (Mon, 07 Jul 2008) | 2 lines Correct grammar. ........ r64774 | andrew.kuchling | 2008-07-07 18:51:09 +0200 (Mon, 07 Jul 2008) | 1 line Fix example to match text ........ r64775 | facundo.batista | 2008-07-07 19:02:59 +0200 (Mon, 07 Jul 2008) | 3 lines Issue 3306. Better control for a lenght in findmax() function. ........ r64788 | georg.brandl | 2008-07-08 09:05:23 +0200 (Tue, 08 Jul 2008) | 2 lines Add missing ABCs to list. ........ r64793 | nick.coghlan | 2008-07-08 16:21:42 +0200 (Tue, 08 Jul 2008) | 1 line Add missing NEWS and ACK entries for r64791 ........ r64835 | raymond.hettinger | 2008-07-10 11:31:08 +0200 (Thu, 10 Jul 2008) | 1 line Issue 3287: Raise correct exception for float inputs. ........ r64836 | raymond.hettinger | 2008-07-10 12:28:41 +0200 (Thu, 10 Jul 2008) | 1 line Use operator.index() instead of n.__index__(). ........
2008-07-16 00:43:04 -03:00
This module provides the infrastructure for defining an :term:`abstract base
class` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
Merged revisions 64475,64544-64545,64550,64557-64558,64565,64570,64577,64582-64583,64585,64590,64592-64593,64625,64630,64638,64647,64655-64656,64663-64664 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r64475 | raymond.hettinger | 2008-06-22 22:29:28 -0500 (Sun, 22 Jun 2008) | 1 line Issue 3161: Missing import and test. ........ r64544 | georg.brandl | 2008-06-26 16:12:55 -0500 (Thu, 26 Jun 2008) | 2 lines Use newer versions of externals. ........ r64545 | benjamin.peterson | 2008-06-26 16:23:30 -0500 (Thu, 26 Jun 2008) | 1 line add a htmlview directive ........ r64550 | brett.cannon | 2008-06-26 19:32:16 -0500 (Thu, 26 Jun 2008) | 2 lines Ignore .pyc and .pyo files. ........ r64557 | mark.dickinson | 2008-06-27 05:11:52 -0500 (Fri, 27 Jun 2008) | 3 lines Remove trailing 'L's from numerator and denominator in the repr() of a Fraction instance. ........ r64558 | mark.dickinson | 2008-06-27 06:03:21 -0500 (Fri, 27 Jun 2008) | 2 lines Add Jean Brouwers for his work on math.sum ........ r64565 | raymond.hettinger | 2008-06-27 16:34:24 -0500 (Fri, 27 Jun 2008) | 1 line Fix whitespace in example code. ........ r64570 | hyeshik.chang | 2008-06-27 20:04:31 -0500 (Fri, 27 Jun 2008) | 8 lines Give information for compililation of _multiprocessing.SemLock on FreeBSD: FreeBSD's P1003.1b semaphore support is highly experimental and it's disabled by default. Even if a user loads the experimental kernel module manually, _multiprocessing doesn't work correctly due to several known incompatibilities around sem_unlink and sem_getvalue, yet. ........ r64577 | raymond.hettinger | 2008-06-28 17:16:53 -0500 (Sat, 28 Jun 2008) | 1 line Issue 3230: Do not the set specific size macro. ........ r64582 | benjamin.peterson | 2008-06-28 18:06:05 -0500 (Sat, 28 Jun 2008) | 2 lines convert test_audioop to unittest. Thanks to Giampaolo Rodola. ........ r64583 | benjamin.peterson | 2008-06-28 18:06:49 -0500 (Sat, 28 Jun 2008) | 1 line rewrap ........ r64585 | benjamin.peterson | 2008-06-28 18:35:31 -0500 (Sat, 28 Jun 2008) | 1 line fix typo ........ r64590 | benjamin.peterson | 2008-06-29 08:43:07 -0500 (Sun, 29 Jun 2008) | 1 line reinstate the ending backtick. thanks Nick :) ........ r64592 | vinay.sajip | 2008-06-29 16:25:28 -0500 (Sun, 29 Jun 2008) | 2 lines Removed out-of-date comment in _install_handlers and used issubclass in place of equality comparison of classes. ........ r64593 | vinay.sajip | 2008-06-29 16:27:15 -0500 (Sun, 29 Jun 2008) | 1 line Updated to reflect change in logging.config to remove out-of-date comment in _install_handlers and the use of issubclass in place of equality comparison of classes. ........ r64625 | georg.brandl | 2008-07-01 14:59:00 -0500 (Tue, 01 Jul 2008) | 2 lines Add a link to PEP 324. ........ r64630 | georg.brandl | 2008-07-01 15:18:10 -0500 (Tue, 01 Jul 2008) | 2 lines #3216: fix Execute's parameter description. ........ r64638 | georg.brandl | 2008-07-01 15:50:02 -0500 (Tue, 01 Jul 2008) | 2 lines #1410739: add a footnote about "is" and "unusual" behavior. ........ r64647 | benjamin.peterson | 2008-07-01 18:33:06 -0500 (Tue, 01 Jul 2008) | 1 line add ABC to the glossary ........ r64655 | mark.dickinson | 2008-07-02 04:37:01 -0500 (Wed, 02 Jul 2008) | 7 lines Replace occurrences of '\d' with '[0-9]' in Decimal regex, to make sure that the behaviour of Decimal doesn't change if/when re.UNICODE becomes assumed in Python 3.0. Also add a check that alternative Unicode digits (e.g. u'\N{FULLWIDTH DIGIT ONE}') are *not* accepted in a numeric string. ........ r64656 | nick.coghlan | 2008-07-02 08:09:19 -0500 (Wed, 02 Jul 2008) | 1 line Issue 3190: pydoc now hides module __package__ attributes ........ r64663 | jesse.noller | 2008-07-02 11:44:09 -0500 (Wed, 02 Jul 2008) | 1 line Reenable the manager tests with Amaury's threading fix ........ r64664 | facundo.batista | 2008-07-02 11:52:55 -0500 (Wed, 02 Jul 2008) | 4 lines Issue #449227: Now with the rlcompleter module, callable objects are added a '(' when completed. ........
2008-07-02 17:22:54 -03:00
was added to Python. (See also :pep:`3141` and the :mod:`numbers` module
regarding a type hierarchy for numbers based on ABCs.)
The :mod:`collections` module has some concrete classes that derive from
ABCs; these can, of course, be further derived. In addition the
:mod:`collections` module has some ABCs that can be used to test whether
a class or instance provides a particular interface, for example, is it
hashable or a mapping.
This module provides the following class:
.. 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
:func:`super`). [#]_
Classes created with a metaclass of :class:`ABCMeta` have the following method:
.. method:: register(subclass)
Register *subclass* as a "virtual subclass" of this ABC. For
example::
from abc import ABCMeta
class MyABC(metaclass=ABCMeta):
pass
MyABC.register(tuple)
assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
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
2007-09-04 12:45:25 -03:00
subclass of the ABC. (This class method is called from the
:meth:`__subclasscheck__` method of the ABC.)
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.
2007-09-04 12:45:25 -03:00
.. XXX explain the "usual mechanism"
2007-09-04 12:45:25 -03:00
For a demonstration of these concepts, look at this example ABC definition::
2007-09-04 12:45:25 -03:00
class Foo:
def __getitem__(self, index):
...
def __len__(self):
...
def get_iterator(self):
return iter(self)
2007-09-04 12:45:25 -03:00
class MyIterable(metaclass=ABCMeta):
2007-09-04 12:45:25 -03:00
@abstractmethod
def __iter__(self):
2007-09-04 12:45:25 -03:00
while False:
yield None
def get_iterator(self):
return self.__iter__()
@classmethod
def __subclasshook__(cls, C):
2007-09-04 12:45:25 -03:00
if cls is MyIterable:
if any("__iter__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
2007-09-04 12:45:25 -03:00
MyIterable.register(Foo)
2007-09-04 12:45:25 -03:00
The ABC ``MyIterable`` defines the standard iterable method,
:meth:`__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.
The :meth:`__subclasshook__` class method defined here says that any class
2007-09-04 12:45:25 -03:00
that has an :meth:`__iter__` method in its :attr:`__dict__` (or in that of
one of its base classes, accessed via the :attr:`__mro__` list) is
considered a ``MyIterable`` too.
2007-09-04 12:45:25 -03:00
Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
even though it does not define an :meth:`__iter__` method (it uses the
2007-09-04 12:45:25 -03:00
old-style iterable protocol, defined in terms of :meth:`__len__` and
:meth:`__getitem__`). Note that this will not make ``get_iterator``
available as a method of ``Foo``, so it is provided separately.
It also provides the following decorators:
.. function:: abstractmethod(function)
A decorator indicating abstract methods.
Using this decorator requires that the class's metaclass is :class:`ABCMeta` or
2009-01-03 17:18:54 -04:00
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.
2007-09-04 12:45:25 -03:00
The abstract methods can be called using any of the the normal 'super' call
mechanisms.
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.
Usage::
class C(metaclass=ABCMeta):
@abstractmethod
def my_abstract_method(self, ...):
...
2007-09-04 12:45:25 -03:00
.. note::
Unlike C++'s pure virtual functions, or Java abstract methods, these abstract
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.
2007-09-04 12:45:25 -03:00
2007-09-04 12:45:25 -03:00
.. function:: abstractproperty(fget[, fset[, fdel[, doc]]])
2007-09-04 12:45:25 -03:00
A subclass of the built-in :func:`property`, indicating an abstract property.
Using this function requires that the class's metaclass is :class:`ABCMeta` or
2009-01-03 17:18:54 -04:00
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 properties can be called using any of the normal
'super' call mechanisms.
Usage::
class C(metaclass=ABCMeta):
@abstractproperty
def my_abstract_property(self):
...
This defines a read-only property; you can also define a read-write abstract
property using the 'long' form of property declaration::
class C(metaclass=ABCMeta):
def getx(self): ...
def setx(self, value): ...
x = abstractproperty(getx, setx)
.. rubric:: Footnotes
.. [#] C++ programmers should note that Python's virtual base class
concept is not the same as C++'s.