Interface and duck typing woes

Joe Junior joe.fbs.junior at gmail.com
Wed Aug 28 17:09:22 EDT 2013


While designing a simple library, I found myself asking a
philosophical question: to check or not to check the parameter's
interface?

I think that, considering it is Python, the usual answer would be
"no", but here is the situation that got me thinking:

class Flock:

    def __init__(self):
        self.ducks= []

    def do_stuff(self):
        for duck in self.ducks:
            duck.quack()

class Duck:

    def quack(self):
        #quack-quack
        pass

f = Flock()
d = Duck()
f.ducks.append(d)
f.do_stuff()

Ok, no big deal there, the problem is if the user forgets to implement
the quack() method. The stack trace would complain that "duck.quack()"
is wrong, but that can happen hundreds of lines after the user
actually added the object to the Flock, and it can be hard to find out
what is happening and which object is wrong.

Of course I don't want to check isistance(), I like duck typing, but
should I check if hasattr() and callable() before adding to the
container? What is the pythonic way to deal with it? Am I worrying too
much ;-)?

Thanks,

Joe



More information about the Python-list mailing list