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

Jesse London jesselondon at gmail.com
Fri May 20 06:46:44 CEST 2011


On Thu, May 19, 2011 at 10:34 PM, Carl Meyer <carl at oddbird.net> wrote:

> On 05/19/2011 10:13 PM, Jesse London wrote:
> > It sounds like what you really care about is whether or not you were
> > handed an iterable. If you don't want to say:
> >
> >     def foo(*strings):
> >         ...
> >
> > then you can reliably duck-type like so:
> >
> >     def foo(strings):
> >         if not hasattr(strings, '__iter__'):
> >             strings = (strings,)
> >         ...
>
> Not in Python 3, FWIW. Since strings are an iterable, it was really only
> ever an oversight that they lacked __iter__, and that was fixed in Python
> 3.
>
> Carl
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> http://mail.python.org/mailman/listinfo/chicago
>

Well! Good to know.

You could still perhaps duck-type, depending upon what you plan to do with
the object you're passed. If you were in fact planning to use 'split()',
then it would make sense to check for that. But, if you just want to iterate
over an iterable of strings, and you want to accommodate the single string,
(which is itself an iterable of strings), then, yeah, you'd better use
`*strings` or `isinstance(strings, basestring)`. No shame in that.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20110519/0e52407c/attachment.html>


More information about the Chicago mailing list