[Chicago] duck typing to handle a string or iterable of strings
Alex Gaynor
alex.gaynor at gmail.com
Fri May 20 05:55:20 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
>
It wasn't in any way an oversight, in fact the __iter__ on list and tuples
are totally superflous. Types which define __getitem__ are automatically
iterable and a default iterator is used for them which calls __getitem__
with successive integers until an IndexError is raised.
Alex
--
"I disapprove of what you say, but I will defend to the death your right to
say it." -- Evelyn Beatrice Hall (summarizing Voltaire)
"The people's good is the highest law." -- Cicero
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20110519/96ffe38c/attachment.html>
More information about the Chicago
mailing list