duck-type-checking?
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Wed Nov 12 21:32:59 EST 2008
On Wed, 12 Nov 2008 08:06:31 -0700, 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.
I'm surprised nobody has pointed you at Alex Martelli's recipe here:
http://code.activestate.com/recipes/52291/
While the recipe is great, it can be tiresome to apply all the time. I
would factor out the checks into a function, something like this:
def isstringlike(obj, methods=None):
"""Return True if obj is sufficiently string-like."""
if isinstance(obj, basestring):
return True
if methods is None:
methods = ['upper', 'lower', '__len__', '__getitem__']
for method in methods:
if not hasattr(obj, method):
return False
# To really be string-like, the following test should pass.
if len(obj) > 0:
s = obj[0]
if s[0] != s:
return False
return True
--
Steven
More information about the Python-list
mailing list