duck-type-checking?

George Sakkis george.sakkis at gmail.com
Thu Nov 13 22:11:12 CET 2008


On Nov 13, 10:15 am, Joe Strout <j... at strout.net> wrote:
> On Nov 12, 2008, at 7:32 PM, Steven D'Aprano wrote:
>
> > 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.

To me this seems it combines the worst of both worlds: the
explicitness of LBYL with the heuristic nature of duck typing.. might
as well call it "doyoufeellucky typing". If you are going to Look
Before You Leap, try to stick to isinstance/issubclass checks
(especially in 2.6+ that they can be overriden) instead of crafting ad-
hoc rules of what makes an object be X-like.

George



More information about the Python-list mailing list