Joe Strout wrote:
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?
Test for one on more of the methods that the parameter must have in that
function, that constitute 'quacking like a duck'
>>> ob = [1,2,3]
>>> assert ob.__getitem__ and ob.__setitem__
>>> ob = 3
>>> assert ob.__getitem__ and ob.__setitem__
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
assert ob.__getitem__ and ob.__setitem__
AttributeError: 'int' object has no attribute '__getitem__'
Focus on testing ones that differentiate the species you want. Lists
have __add__ and __mul__ but do not have
>>> assert ob.__sub__ and ob.__floordiv__
Since methods are always True, no need for hasattr().
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list