[Chicago] duck typing to handle a string or iterable of strings

John Hunter jdh2358 at gmail.com
Thu May 19 18:37:33 CEST 2011

On Thu, May 19, 2011 at 10:27 AM, Jeremy McMillan <aphor at me.com> wrote:

> So I want a function or method to operate on one or more strings, but if
> the convention is usually one, I hate requiring the tuple/list wrapper
> around a string argument. I want really smart argument handling.
> I found this, but it's not conclusive:
> http://stackoverflow.com/questions/4237434/pythonic-way-to-verify-parameter-is-a-sequence-but-not-string
> And there's this...

matplotlib.cbook defines many duck-typing functions, including
"is_string_like" and "is_sequence_of_strings".  Here is their

def iterable(obj):
    'return true if *obj* is iterable'
    try: len(obj)
    except: return False
    return True

def is_string_like(obj):
    'Return True if *obj* looks like a string'
    if isinstance(obj, (str, unicode)): return True
    # numpy strings are subclass of str, ma strings are not
    if ma.isMaskedArray(obj):
        if obj.ndim == 0 and obj.dtype.kind in 'SU':
            return True
            return False
    try: obj + ''
    except: return False
    return True

def is_sequence_of_strings(obj):
    Returns true if *obj* is iterable and contains strings
    if not iterable(obj): return False
    if is_string_like(obj): return False
    for o in obj:
        if not is_string_like(o): return False
    return True
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20110519/7084f02b/attachment-0001.html>

More information about the Chicago mailing list