Interface and duck typing woes

Fabrice POMBET fp2161 at gmail.com
Thu Aug 29 02:31:25 EDT 2013


Le 29 août 2013 à 00:56, python-list-request at python.org a écrit :

"""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"""

Hey Joe,

I am no depository of the pythonic way to think(tm) but I would create flock and inherit Duck from flock, or possibly set Flock as a method of ducks.

that would look like this:

class Flock():
	def __init__(self, flock):
		self.flock=flock
class Duck(Flock):
	def __init(self, flock):
		super().__init__(flock)

then you only need to create some functions for any object to display the lists and or dicts that you will create outside these classes, in the main or in another function...

you just instantiate them like that:

Donald=Duck('Donald')
or (rather): 
flock=[]
flock.append(Duck('Donald'))

one big advantage with this method is, you can creat plenty of other bird classes and append them to a list.
Alternatively, you could have just one class Flock and then set duck as an attribute of flock, and set a list of your flock as a private attribute (the self.duck thing in your code... Well... Could be handled in a better way...) but that is another story, the one before is way simpler for your purpose.




More information about the Python-list mailing list