Abstract Base Classes versus Duck Typing
Question: Python has specific [ABCs for container
types](http://docs.python.org/3/library/collections.abc.html). It says
they're, "…used to test whether a class provides a particular interface." (And
that they're also useful for some mixins, but let's ignore that for the
moment.)

I'm having trouble figuring out why some of these ABCs are really useful.
Perhaps my problem is just that the examples in the doc are too academic, but
using these examples:

    
    
    # Verbatim
    size = None
    if isinstance(myvar, collections.abc.Sized):
        size = len(myvar)
    
    # Is that so much better than
    size = None
    if hasattr(myvar, '__len__'):
        size = len(myvar)
    

In the second case you avoid an import and the code seems more explicit to me.
You can infer what collections.abc.Sized means from its name, or look it up,
but it's just not as explicit is "If it has a length, get its length."

Is the abc approach to collection-type testing really more idiomatic Python
than explicit `hasattr` testing, and if so, why? (Does _simple is better than
complex_ trump _explicit is better than implicit_ in this case?)


Answer: You can achieve the same results with either approach. The main benefit of the
ABC approach is that some of the logic is provided for you. For example, to
implement a Set type via duck typing, you would have to write and test 14
interfaces - `__contains__, __iter__, __len__, __le__, __lt__, __eq__, __ne__,
__gt__, __ge__, __and__, __or__, __sub__, __xor__, and isdisjoint`.

However if you use the ABC, you only need to define `__contains__, __iter__
and __len__` \- the ABC uses these function you provide to implement the
remaining 11 methods for you. ABC does what you would do, but with less
effort. It's a shortcut that gets you to the same destination.

