Interface and duck typing woes
jussi.santti at ard.fi
jussi.santti at ard.fi
Fri Aug 30 01:37:39 EDT 2013
On Thursday, August 29, 2013 12:09:22 AM UTC+3, Joe Junior wrote:
> While designing a simple library, I found myself asking a
>
> philosophical question: to check or not to check the parameter's
>
> interface?
>
Design by contract discipline says: do not.
>
>
> 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