On Nov 12, 2008, at 7:32 PM, Steven D'Aprano wrote:
I'm surprised nobody has pointed you at Alex Martelli's recipe here:
http://code.activestate.com/recipes/52291/
Thanks for that -- it's clever how he combines binding the methods
he'll use with doing the checking.
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
Thanks for this, too; that's the sort of method I had in mind. That
last test for string-likeness is particularly clever. I'll need to
think more deeply about the implications.
Best,
- Joe
--
http://mail.python.org/mailman/listinfo/python-list