ABC question: what is the purpose of the register() method?

Kay Schluehr kay.schluehr at gmx.net
Sat Jun 7 20:37:53 CEST 2008


I was reading PEP 3119 (http://www.python.org/dev/peps/pep-3119/ ) and
have done some experiments using Python 3.0a5. Now I'm somewhat
puzzled about the purpose of the ABCMeta.register() method.

One can use the register() method to register any class as a virtual
subclass of any ABC. For example one can register `int` on `Iterable`
and therefore it is a subclass which is confirmed in the issubclass
check. What is that good for?

This registration might even conflict with the implementation of
__subclasscheck__. So one might expect that register(C) leads to an
acceptance of a class as a subclass but this isnt't true if
__subclasscheck__(C) rejects it. Why isn't __subclasscheck__ not
sufficient?

Example:
--------------

class Interface(metaclass = ABCMeta):
    @classmethod
    def __subclasscheck__(cls, C):
         return cls.__abstractmethods__.issubset(C.__dict__)    # some
contract...

class IAppendable(Interface):
    @abstractmethod
    def append(self, item): pass

>>> issubclass(list, IAppendable)
True
>>> issubclass(tuple, IAppendable)
False
>>> IAppendable.register(int)
>>> issubclass(int, IAppendable)
False

>>> import collections.Iterable as Iterable
>>> Iterable.register(int)
>>> issubclass(int, Iterable)
True






More information about the Python-list mailing list