Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Base Classes versus Duck Typing

Python has specific ABCs for container types. 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?)

like image 883
kojiro Avatar asked Aug 25 '13 16:08

kojiro


2 Answers

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 functions 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.

like image 136
Chris Johnson Avatar answered Sep 23 '22 00:09

Chris Johnson


To me the mixins seem to be a main part of this module. Also in most cases, yes simple is the main goal to make perfect code, to me at least(not that I ever manage it). The fact that the ABC module's functions seem to be pretty clear about what they do, helps for sharing and skimming code. Finally, I may be wrong about this, so don't count on it, though I think some of ABC's functions can check for multiple attributes in one function.

like image 41
Ben Hack Avatar answered Sep 26 '22 00:09

Ben Hack