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

Jeremy McMillan aphor at me.com
Thu May 19 17:27:04 CEST 2011

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:

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?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20110519/739a3983/attachment.html>

More information about the Chicago mailing list