is_iterable function.

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Jul 25 17:11:25 EDT 2007


On Wed, 25 Jul 2007 15:46:14 -0400, Carsten Haese wrote:

> On Wed, 2007-07-25 at 19:11 +0000, Marc 'BlackJack' Rintsch wrote:
>> And just calling `iter()` doesn't work either:
>> 
>> In [72]: class A:
>>    ....:     def __getitem__(self, key):
>>    ....:         if key == 42:
>>    ....:             return 'answer'
>>    ....:         raise KeyError
>>    ....:
>> 
>> In [73]: iter(A())
>> Out[73]: <iterator object at 0xb7829b2c>
>> 
>> In [74]: a = iter(A())
>> 
>> In [75]: a.next()
>> ---------------------------------------------------------------------------
>> <type 'exceptions.KeyError'>            Traceback (most recent call last)
>> 
>> /home/bj/<ipython console> in <module>()
>> 
>> /home/bj/<ipython console> in __getitem__(self, key)
>> 
>> <type 'exceptions.KeyError'>:
>> 
>> 
>> So there's no reliable way to test for "iterables" other than actually
>> iterate over the object.
> 
> You seem to say that your 'a' object is not iterable. I disagree. While
> it's true that it raises an exception upon retrieval of the zeroth
> iteration, that situation is quite different from attempting to iterate
> over the number 10, where you can't even ask for a zeroth iteration.

But it raises that exception on every attempt to iterate and was clearly
not meant to be iterable.  The docs say objects that offer no `__iter__()`
but a `__getitem__()` are iterable if this `__getitem__()` can be called
with consecutive integers from zero up and if there is an upper limit it
must be signaled by an `IndexError`.  The object above doesn't follow this
protocol.  For me an "iterable" is about behavior.  If it doesn't quack
like a duck…

> To illustrate this point further, imagine you write an object that
> iterates over the lines of text read from a socket. If the connection is
> faulty and closes the socket before you read the first line, the zeroth
> iteration raises an exception. Does that mean the object is iterable or
> not depending on the reliability of the socket connection? I find that
> notion hard to swallow.

It is an iterable as there is at least the chance or the intent of the
programmer that it will behave like an iterable.  The duck tries hard to
quack but may be hoarse.  :-)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list