Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53184
| Date | 2013-08-28 18:09 -0300 |
|---|---|
| Subject | Interface and duck typing woes |
| From | Joe Junior <joe.fbs.junior@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.327.1377724351.19984.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Interface and duck typing woes Joe Junior <joe.fbs.junior@gmail.com> - 2013-08-28 18:09 -0300
Re: Interface and duck typing woes Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-08-28 23:24 +0000
Re: Interface and duck typing woes Nobody <nobody@nowhere.com> - 2013-08-29 10:41 +0100
Re: Interface and duck typing woes Joe Junior <joe.fbs.junior@gmail.com> - 2013-08-29 09:40 -0300
Re: Interface and duck typing woes alex23 <wuwei23@gmail.com> - 2013-08-30 10:14 +1000
Re: Interface and duck typing woes Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-08-30 02:42 +0000
Re: Interface and duck typing woes Roy Smith <roy@panix.com> - 2013-08-30 06:35 -0400
Re: Interface and duck typing woes Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-08-31 00:13 +0000
Re: Interface and duck typing woes Ned Batchelder <ned@nedbatchelder.com> - 2013-08-30 20:45 -0400
Re: Interface and duck typing woes Joshua Landau <joshua@landau.ws> - 2013-09-01 00:18 +0100
Re: Interface and duck typing woes Roy Smith <roy@panix.com> - 2013-08-31 20:52 -0400
Re: Interface and duck typing woes Chris Angelico <rosuav@gmail.com> - 2013-08-29 23:07 +1000
Re: Interface and duck typing woes Joe Junior <joe.fbs.junior@gmail.com> - 2013-08-29 11:11 -0300
Re: Interface and duck typing woes jussi.santti@ard.fi - 2013-08-29 22:37 -0700
csiph-web