function taking scalar or list argument

Peter Otten __peter__ at web.de
Tue Aug 24 02:23:11 EDT 2004


Terry Reedy wrote:

> 
> "Steven Bethard" <steven.bethard at gmail.com> wrote in message
> news:loom.20040824T052140-517 at post.gmane.org...
>> Well, you can always test for the protocol, e.g.:
>>
>> def twice(x):
>>     if hasattr(x, "__iter__"):
>>         return map(twice, x)
> 
> In 2.2.1:
>>>> hasattr([1,2,3], '__iter__')
> 0
> so this does not seem to work as you seem to expect.  hasattr(iter(x),
> '__iter__') will.

No it won't:

[Python 2.2]
>>> hasattr(iter(1), "__iter__")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: iteration over non-sequence


Here the only reliable test for iterability is to just try it.
Unfortunately, while in most cases you want to treat them as scalars,
strings are iterables, too.

In 2.3 Steven's proposal works:

>>> hasattr(1, "__iter__")
False
>>> hasattr([], "__iter__")
True

Peter




More information about the Python-list mailing list