[Chicago] duck typing to handle a string or iterable of strings
Michael Tobis
mtobis at gmail.com
Fri May 20 17:58:52 CEST 2011
OK, but still.
I have also faced this problem.
Flattening nested lists which contain strings is an example.
Because a string is an iterable, if we want a method that tolerates a
single string or a list of strings, treating the single string the
same as a list with one element, we have to be able to treat the
string as a non-iterable. The question is what the most elegant way to
do this is if we are building general purpose utility functions that
we don;'t want to violate duck typing. I recall punting, but I also
recall wondering the same thing.
So, consider a routine that is intended to flatten a nested list. We
want to write a recursive routine that takes [1,[2,3,[4,5],"fred"]] to
[1,2,3,4,5,"fred"] and not to [1,2,3,4,5,"f","r","e","d"]. And even
the latter is not as easy as you'd expect.
It totally violated least surprise for me when I did something like
>>> def atomprint(thing):
... try:
... for item in thing:
... atomprint(item)
... except TypeError:
... print thing
It works beautifully for lists of integers, floats, various other
things. I felt satisfied and ever so pythonic. But it overflows the
stack when you pass it a non-empty string!
mt
More information about the Chicago
mailing list