is_iterable function.

Carsten Haese carsten at uniqsys.com
Wed Jul 25 15:46:14 EDT 2007


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.

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.

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list