[3.6] bpo-30096: Use ABC in abc reference examples (GH-1220) by miss-islington · Pull Request #3408 · python/cpython
This module provides the following classes: 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
.. class:: ABCMeta
from abc import ABCMeta from abc import ABC
class MyABC(metaclass=ABCMeta): pass class MyABC(ABC): pass
MyABC.register(tuple) MyABC.register(tuple)
assert issubclass(tuple, MyABC) assert isinstance((), MyABC) assert issubclass(tuple, MyABC) assert isinstance((), MyABC)
.. versionchanged:: 3.3 Returns the registered subclass, to allow usage as a class decorator.
class MyIterable(metaclass=ABCMeta): class MyIterable(ABC):
@abstractmethod def __iter__(self):
.. 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.
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.
.. versionadded:: 3.4
The :mod:`abc` module also provides the following decorators:
class C(metaclass=ABCMeta): class C(ABC): @abstractmethod def my_abstract_method(self, ...): ...
class C(metaclass=ABCMeta): class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, ...):
class C(metaclass=ABCMeta): class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(...):
class C(metaclass=ABCMeta): class C(ABC): @property @abstractmethod def my_abstract_property(self):
class C(metaclass=ABCMeta): class C(ABC): @property def x(self): ...