argument type

Steven Bethard steven.bethard at
Tue Dec 28 23:58:17 CET 2004

Doug Holton wrote:
> It's me wrote:
>> The argument I wish to pass is either one string, or a list of 
>> strings, or a tuple of strings.
> def seq(x):
>     if hasattr(x,"__iter__"):
>         return x
>     else:
>         return (x,)
> def abc(arg1, arg2, arg3):
>     for item in seq(arg2):
>         print item

Note that this takes advantage of the fact that str and unicode 
implement iteration through the old __getitem__ protocol instead of the 
__iter__ protocol.  It's actually probably the most concise solution to 
your problem, but I don't think there's any guarantee that str and 
unicode won't grow __iter__ methods in the future, so you might find 
that this code breaks in some future version of Python (probably in the 
fabled Python 3.0).  Unfortunately, if this does happen, it won't break 
with an exception; it will break by treating the characters in strings 
as 'item's.

For the moment though (and I suspect in Python 2.5 as well since I 
haven't heard anyone lobbying to add __iter__ methods to str or 
unicode), this should work fine for you.


More information about the Python-list mailing list