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

Jesse London jesselondon at gmail.com
Fri May 20 05:13:49 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.
>

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,)
        ...

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


More information about the Chicago mailing list