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

Ken Schutte kenschutte at gmail.com
Thu May 19 17:37:42 CEST 2011


What about doing this: ?

def foo(x):
    if isinstance(x, basestring):
        x = [x]
    # now, assume x is a list of strings.




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...
>
>>>> foo = set(dir('a string!'))
>>>> bar = set(dir(['a string', 'and another one']))
>>>> foo.difference(bar)
> set(['upper', 'lstrip', 'rpartition', 'replace', 'endswith', 'splitlines',
> 'expandtabs', 'strip', 'isdigit', '__rmod__', '__getnewargs__', 'find',
> 'rjust', 'ljust', 'isalnum', 'title', 'rindex', 'rsplit', 'decode',
> 'isalpha', 'split', 'rstrip', 'encode', '_formatter_parser', 'translate',
> 'isspace', 'startswith', 'format', 'swapcase', 'zfill', 'capitalize',
> 'lower', 'join', 'center', '__mod__', 'partition', 'rfind', 'istitle',
> '_formatter_field_name_split', 'islower', 'isupper'])
>>>> len(foo.difference(bar))
> 41
>
> The whole point of duck-typing is to be as lenient as possible with
> subclasses and workalike objects. Theoretically, it would work pretty well
> to use any of those 41 methods and attributes, but which one is optimal
> depends on convention. Which one is least likely to be left out of some
> stringlike object? Can anyone weigh in on forward compatibility with
> Python3?
> My guess: I think the string method I use most heavily is split. I would
> feel deep disappointment if something returned a string object and
> discovered later that it didn't implement split(). Moreover: this is the
> canonical way to convert a string into an iterable of stings, so I think it
> is formally correct. For instance, it seems absurd for an iterable to
> implement split().
> I went to the interwebs for confirmation, but I don't see an understanding,
> so now ChiPy please tell me what you think?
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> http://mail.python.org/mailman/listinfo/chicago
>
>


More information about the Chicago mailing list