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

Carl Meyer carl at oddbird.net
Thu May 19 17:53:49 CEST 2011


On 05/19/2011 10:27 AM, Jeremy McMillan 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.

So, in the (apparently popular) spirit of not actually answering your
question, why not just do this:

def foo(*strings):
    # you can safely assume "strings" is a tuple


Then it can be called like foo("one") or foo("one", "two").

I think the reason your actual question isn't getting answered is that
there isn't a great answer. Personally, I think choosing any one of
those 41 methods as the definitive marker of "string-ness" is wrong and
kind of smelly. I'd much sooner use "isinstance(x, basestr)" (in Python
2) or "from types import StringType; isinstance(x, StringType)". I know
that isn't duck-typing, but duck-typing isn't an absolute imperative.

Frankly, I don't think there is any inherent behavioral difference
between strings and other iterables in Python that allows you to
differentiate them reliably via duck-typing. I certainly don't think
"split" qualifies as such a behavior (and I can certainly imagine many
possible non-string iterable types that would have good reason to have a
method named "split").

Also, FWIW, I've never in the wild seen a type that was attempting to
masquerade as string-like that didn't inherit from a real string type.

My .02,

Carl


More information about the Chicago mailing list