[Python-ideas] check interfaces, isducktype(X, A)

Nick Coghlan ncoghlan at gmail.com
Tue Dec 3 14:05:52 CET 2013


On 3 December 2013 04:42, Andrew Barnert <abarnert at yahoo.com> wrote:
> Shouldn't this be tied to ABCs rather than redesigning and reimplementing
> most of ABC to add a little bit on top?

This seems like an apropos place for this link:
http://docs.python.org/3/library/abc#abc.ABCMeta.__subclasshook__

That's the existing "formalised ducktyping" hook, that already allows
things like the following:

>>> class MyClass:
...     def __len__(self):
...         return 0
...
>>> from collections.abc import Sized
>>> isinstance(MyClass(), Sized)
True
>>> issubclass(MyClass, Sized)
True

The advantage ABCs have over ducktyping alone is that subclassing and
explicit registration allow ambiguities like the one between the
Sequence and Mapping interfaces to be resolved (you can't always just
ducktype those, as they have the same methods - they differ only in
how the __*item__ methods handle slice objects).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list