2008/11/12 Joe Strout <[EMAIL PROTECTED]>:
> Let me preface this by saying that I think I "get" the concept of
> duck-typing.
>
> However, I still want to sprinkle my code with assertions that, for example,
> my parameters are what they're supposed to be -- too often I mistakenly pass
> in something I didn't intend, and when that happens, I want the code to fail
> as early as possible, so I have the shortest possible path to track down the
> real bug.  Also, a sufficiently clever IDE could use my assertions to know
> the type of my identifiers, and so support me better with autocompletion and
> method tips.
>
> So I need functions to assert that a given identifier quacks like a string,
> or a number, or a sequence, or a mutable sequence, or a certain class, or so
> on.  (On the class check: I know about isinstance, but that's contrary to
> duck-typing -- what I would want that check to do instead is verify that
> whatever object I have, it has the same public (non-underscore) methods as
> the class I'm claiming.)
>
> Are there any standard methods or idioms for doing that?

What do you actually mean by "Quacks like a string"? Supports the
'count()' method? Then you find out if it doesn't when you try to
apply the 'count()' method. Supports some method that you don't
actually use? Then why do you care?

The point about duck typing is that something might quack like a duck
but not walk like a duck -- one of those duck calls that hunters use,
for instance. Quacking like a duck doesn't actually mean it /is/ a
duck, it means that it will do instead of a duck if the quack is all
you want.

If all you care about is that 'foo' quacks like a duck then all you
need to know is that
   hasattr(foo, "quack")
and (if so)
   callable(foo.quack)
If you need to know that it walks like a duck, mates like a duck and
tastes like a duck when roasted, you probably want it to really /be/ a
duck and should go back to inheritance.

-- 
Tim Rowe
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to